“cv2.imdecode(numpyArray, cv2.CV_LOAD_IMAGE_COLOR)

2019-06-01 08:32发布

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条回答
相关推荐>>
2楼-- · 2019-06-01 09:20

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)
查看更多
登录 后发表回答