ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Not able to publish image to std_msg/Image

asked 2019-08-02 11:43:40 -0500

TristanNoctis gravatar image

I am trying to run a publisher code that publishes an Image to a topic. But, whenever I run the code, I get an error. The code I have written is below -

#!/usr/bin/env python

import rospy
import numpy as np
import cv2
from sensor_msgs.msg import Image

video_capture = cv2.VideoCapture(0)

def main():
rospy.init_node('Tennis Ball Publisher', anonymous = True)

pub = rospy.Publisher("tennis_ball_image", Image, queue_size = 10)

rate = rospy.Rate(1)

while (True):
    ret, frame = video_capture.read()

    pub.publish(frame)

    rate.sleep()


if __name__=='__main__':
    main()

This is the error that I get on running the code -

Traceback (most recent call last):
  File "tennis_ball_publisher.py", line 26, in <module>
    main()
  File "tennis_ball_publisher.py", line 20, in main
    pub.publish(frame)
  File "/opt/ros/melodic/lib/python2.7/dist-packages/rospy/topics.py", line 879, in publish
    data = args_kwds_to_message(self.data_class, args, kwds)
  File "/opt/ros/melodic/lib/python2.7/dist-packages/rospy/msg.py", line 122, in args_kwds_to_message
    return data_class(*args)

  File "/opt/ros/melodic/lib/python2.7/dist-packages/sensor_msgs/msg/_Image.py", line 78, in __init__
    super(Image, self).__init__(*args, **kwds)
  File "/opt/ros/melodic/lib/python2.7/dist-packages/genpy/message.py", line 294, in __init__
    raise TypeError("Invalid number of arguments, args should be %s"%str(self.__slots__)+" args are"+str(args))
TypeError: Invalid number of arguments, args should be ['header', 'height', 'width', 'encoding', 'is_bigendian', 'step', 'data'] args are(None,)

I suspect that the error is in the way I am publishing the frame but I am not able to rectify it. Any help is appreciated.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2019-08-02 12:19:13 -0500

jayess gravatar image

It looks like you're trying to publish the OpenCV image directly. From what I can recall, you need to convert it to an Image message before you can publish it. To do that use, cv_bridge. Here's a brief example that should help you get started (I've included only the bare minimum, for more info see the tutorial on the wiki)

from cv_bridge import CvBridge

...

bridge = CvBridge()

...

pub.publish(bridge.cv2_to_imgmsg(frame, "bgr8"))
edit flag offensive delete link more

Comments

Thanks for your help! Really sorry for not responding earlier. I have been a bit busy the last few days.

TristanNoctis gravatar image TristanNoctis  ( 2019-08-05 12:07:32 -0500 )edit

No worries

jayess gravatar image jayess  ( 2019-08-05 14:22:50 -0500 )edit

Question Tools

2 followers

Stats

Asked: 2019-08-02 11:43:40 -0500

Seen: 1,333 times

Last updated: Aug 02 '19