简体   繁体   English

“cv2.imdecode(numpyArray, cv2.CV_LOAD_IMAGE_COLOR)”返回无

[英]“cv2.imdecode(numpyArray, cv2.CV_LOAD_IMAGE_COLOR)” returns None

I'm trying to convert an image into Opencv (into numpy array) and use the array to publish the message over a ROS node.我正在尝试将图像转换为 Opencv(转换为 numpy 数组)并使用该数组通过 ROS 节点发布消息。 I tried doing the same through the following code我尝试通过以下代码做同样的事情

    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)

But, when I tried doing this I get an error message但是,当我尝试这样做时,我收到一条错误消息

AttributeError: 'NoneType' object has no attribute 'shape'

So, I tried printing the values of both the numpy array whose values were [255 191 191 ..., 191 191 191] .因此,我尝试打印值为[255 191 191 ..., 191 191 191]的 numpy 数组的值。 And what i didn't understand is img_np value was None .我不明白的是img_np值是None I don't know where I went wrong.我不知道我哪里错了。 Any help is appreciated.任何帮助表示赞赏。

I have encountered similar problems recently.我最近遇到了类似的问题。

The np.fromstring() method returns an 1-D np.array from the parameter string, regardless of the original resource. np.fromstring()方法从参数字符串返回一个一维np.array ,而不管原始资源如何。 To use the np.array as an image array in OpenCV, you may need to reshape it according to the image width and height.要将np.array用作 OpenCV 中的图像数组,您可能需要根据图像的宽度和高度对其进行np.array

Try this:尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM