Home > Enterprise >  How can I publish an image topic using opencv on ros without cvbridge
How can I publish an image topic using opencv on ros without cvbridge

Time:09-22

I was trying to publish a live video using python script.

#!/usr/bin/env python3

import rospy
from sensor_msgs import msg
import cv2
from sensor_msgs.msg import Image



def takes_data_from_camera():
     
    rate = rospy.Rate(10)  
    vid = cv2.VideoCapture(0)
    
    while not rospy.is_shutdown():
       
        ret, frame = vid.read()
        #video_bridge = bridge.cv2_to_imgmsg(frame, "passthrough")
        pub.publish(frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            vid.release()
            cv2.destroyAllWindows()
            break
    
  


if __name__ == '__main__':
    
    rospy.init_node('Server',anonymous = True)
    pub = rospy.Publisher('TestOps/Camera', Image, queue_size=10)
    takes_data_from_camera()
    

but when i try to run i get the following error

  File "/home/akash-j/catkin_ws/src/test_package/src/py-server.py", line 19, in takes_data_from_camera
    pub.publish(frame)
  File "/opt/ros/noetic/lib/python3/dist-packages/rospy/topics.py", line 879, in publish
    data = args_kwds_to_message(self.data_class, args, kwds)
  File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 122, in args_kwds_to_message
    return data_class(*args)
  File "/opt/ros/noetic/lib/python3/dist-packages/sensor_msgs/msg/_Image.py", line 77, in __init__
    super(Image, self).__init__(*args, **kwds)
  File "/opt/ros/noetic/lib/python3/dist-packages/genpy/message.py", line 354, 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(array([[[209, 200, 193],

I don't know what has been wrong here and I don't want to use cv bridge. and the code works fine with cv bridge.i am using ubuntu 20 and ros noetic and python 3

CodePudding user response:

The Image message type expects this data structure below.

>>> from sensor_msgs.msg import Image
>>> Image.__slots__
['header', 'height', 'width', 'encoding', 'is_bigendian', 'step', 'data']
>>> Image._slot_types
['std_msgs/Header', 'uint32', 'uint32', 'string', 'uint8', 'uint32', 'uint8[]']

And looks like only the video 'data' frame is published.

pub.publish(frame)

Hopefully this is enough for you to troubleshoot further

  • Related