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

这一生的挚爱 提交于 2020-01-14 03:05:13

问题


I'm trying to convert an image into Opencv (into numpy array) and use the array to publish the message over a ROS node. 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]. And what i didn't understand is img_np value was None. I don't know where I went wrong. Any help is appreciated.


回答1:


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. To use the np.array as an image array in OpenCV, you may need to reshape it according to the image width and height.

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)


来源:https://stackoverflow.com/questions/26611536/cv2-imdecodenumpyarray-cv2-cv-load-image-color-returns-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!