“cv2.imdecode(numpyArray,cv2.CV_LOAD_IMAGE_COLOR)”返回无
问题描述:
我试图将图像转换为Opencv(转换为numpy数组),并使用该数组将消息发布到ROS节点上。我试图通过下面的代码“cv2.imdecode(numpyArray,cv2.CV_LOAD_IMAGE_COLOR)”返回无
fig.canvas.draw()
nparr = np.fromstring (fig.canvas.tostring_argb(), np.uint8)
print nparr
img_np = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)
print img_np
image_message = bridge.cv2_to_imgmsg(img_np, encoding="passthrough")
pub.publish(image_message)
但是,当我试着这样做,我得到一个错误消息,做同样的
AttributeError: 'NoneType' object has no attribute 'shape'
于是,我试着打印两个numpy的数组,其值是值[255 191 191 ..., 191 191 191]
。而我不明白的是img_np
值是None
。我不知道我错在哪里。任何帮助表示赞赏。
答
我最近遇到类似问题。
np.fromstring()
方法从参数字符串返回1-Dnp.array
,不管原始资源如何。要将np.array
用作OpenCV中的图像数组,您可能需要根据图像的宽度和高度对其进行重新整形。
试试这个:
img_str = np.fromstring (fig.canvas.tostring_argb(), np.uint8)
ncols, nrows = fig.canvas.get_width_height()
nparr = np.fromstring(img_str, dtype=np.uint8).reshape(nrows, ncols, 3)
img_np = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)