How do I convert an ROS image into a numpy array?
Hi All,
I'm trying to read ROS images published from a video camera (from MORSE) into a numpy array in my python script, but I don't know what is the correct way to do this, and everything I have tried hasn't worked.
Does anyone know how to do this?
Here is a snippet of what I have tried so far:
import numpy
import rospy
from sensor_msgs.msg import Image
def vis_callback( data ):
im = numpy.array( data.data, dtype=numpy.uint8 )
doSomething( im )
rospy.init_node('bla',anonymous=True)
sub_vis = rospy.Subscriber('navbot/camera/image',Image,vis_callback)
rospy.spin()
I get an error that looks like this:
[ERROR] [WallTime: 1370383204.000265] bad callback: <function vis_callback at 0x32e2398>
Traceback (most recent call last):
File "/opt/ros/fuerte/lib/python2.7/dist-packages/ros_comm-1.8.15-py2.7.egg/rospy/topics.py", line 678, in _invoke_callback
cb(msg)
File "ros_simulate.py", line 55, in vis_callback
im = numpy.array(data.data,dtype=numpy.uint8)
ValueError: invalid literal for long() with base 10: "':\x0f\xff';\x10\xff+A\x12\xff7Q\x16\xffB`\x18\xffGg\x18\xffDa\x15\xff=W\x12\xff2H\r\xff*<\x0b\xff&8\n\xff$6\t\xff%6\t\xff'9\n\xff*>\n\xff0G\x0b\xff8S\x0b\xff;Y\n\xff:X\t\xff8V\x07\xff6T\x06\xff2N\x04\xff-F\x04\xff+B\x03\xff&<\x03\xff(?\x05\xff#8\x07\xff\x1e0\x07\xff\x19)\x07\xff\x19(\x08\xff\x1b+\t\xff\x1e0\x0b\xff\x1e0\x0b\xff 3\x0c\xff\x1e1\x0b\xff\x1e1\x0b\xff\x1d/\n\xff\x1c-\t\xff\x1c,\t\xff\x1a*\x08\xff\x1d.\x08\xff(>\x0b\xff-F\x0c\xff<[\x0f\xffJo\x12\xffJp\x12\xffKr\x12\xffLs\x12\xffMt\x13\xffMu\x13\xff"
I noticed that the Image object has a deserialize_numpy() method, I couldn't find any documentation on how to use it, so I crossed my fingers and tried it out:
def vis_callback( data ):
im = numpy.array(data.deserialize_numpy(data.data, numpy ), dtype=numpy.uint8)
doSomething( im )
and got more errors:
[ERROR] [WallTime: 1370383699.289428] bad callback: <function vis_callback at 0x34b5410>
Traceback (most recent call last):
File "/opt/ros/fuerte/lib/python2.7/dist-packages/ros_comm-1.8.15-py2.7.egg/rospy/topics.py", line 678, in _invoke_callback
cb(msg)
File "ros_simulate.py", line 53, in vis_callback
im = numpy.array(data.deserialize_numpy(data.data, numpy ), dtype=numpy.uint8)
File "/opt/ros/fuerte/lib/python2.7/dist-packages/sensor_msgs/msg/_Image.py", line 282, in deserialize_numpy
raise genpy.DeserializationError(e) #most likely buffer underfill
DeserializationError: unpack requires a string argument of length 8