Search code examples
pythonrosrospy

Confirming an Image is Published to ROS


I've been trying to get an image to post to ROS (using Python/rospy), and while I think I have the method right, I'm having a hard time confirming it. Using

rosrun image_view image_view image:=(topic)

doesn't seem to show anything. I've also tried rqtbag, but I don't really know how that thing works, other than it doesn't show things published, anyways.

A few notes before pasting my current code:

  1. The code I use right now is based off of code I have gotten to work previously. I've used a similar setup to post text images to ROS, and those output fairly reliably.
  2. This is slightly modified here. Most of this code is part of an on_message function, since this all runs through MQTT when implemented. (The logic is acquire image on one system -> encode it -> transfer to other system -> decode -> publish to ROS.)
  3. I'm using Python 2.7 on Ubuntu, and ROS Indigo.

Without further ado, my current code for publishing:

rospy.init_node('BringInAnImage', log_level = rospy.INFO)

def convert(messagepayload):
    t = open('newpic.bmp','w')
    t.write(messagepayload)
    t.close()

def on_message(client, userdata, msg):
    img = base64.b64decode(msg.payload)

    convert(img)
    time.sleep(5) 
    source = cv2.imread('newpic.bmp')  #this should be a mat file

    # talk to ROS
    bridge = CvBridge()
    pub2 = rospy.Publisher('/BringInAnImage', Image, queue_size = 10)
    pub2.publish(bridge.cv2_to_imgmsg(source, "bgr8"))
    print "uh..... done??"

I'm using a basic listening function to try and see what is going on (this is within a different script I execute in a separate terminal):

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("/BringInAnImage", Image, callback)
    rospy.spin()

if __name__ == '__main__':
    listener()

The callback just prints out that the image was received.


Solution

  • How to check if something is published on topic xyz

    To check if a message is really published, you can use the rostopic command. Run the following in a terminal to print everything that is published on the specified topic. This is the easiest way to check if there is something published.

    rostopic echo <topic_name>
    

    See the ROS wiki for more useful things rostopic can do.

    Why is the image not received by image_view?

    While you are doing it basically right, your images will not be received by any subscriber for a not so obvious but fatal problem in your code: You are using the publisher (pub2) immediately after initializing it. Subscribers need some time to register to the new publisher and will not be ready before you publish the image (see also this answer).

    ➔ Do not initialize a publisher just before you need it but do it right in the beginning, when initializing the node.