Home > database >  Counting the number of iterations through a ROS subscriber node
Counting the number of iterations through a ROS subscriber node

Time:11-23

I am trying to write a subscriber that will take images from a camera in a gazebo simulation and save them. I am able to take pictures and save them, however I am trying to increment the image name each time, yet I am finding it difficult to do so. I tried to create a class and then increment a number (image_number) inside the class each time I run the image_callback funcion, however I get an error. I also tried defining a global variable and incrementing that, yet it did not recognize the variable inside the functions. I have attached the code and error below, any help is greatly appreciated!

# rospy for the subscriber
import rospy, time
# ROS Image message
from sensor_msgs.msg import Image
# ROS Image message -> OpenCV2 image converter
from cv_bridge import CvBridge, CvBridgeError
# OpenCV2 for saving an image
import cv2

# Instantiate CvBridge
bridge = CvBridge()
  
class Image(object):
    def __init__(self):
        self.image_number = 0
        #rospy.init_node('image_listener')
        # Define your image topic
        image_topic = "/wamv/sensors/cameras/front_left_camera/image_raw"
        # Set up your subscriber and define its callback
        rospy.Subscriber(image_topic, Image, self.image_callback)
        #rospy.spin()
    
    def image_callback(self, msg):
        print("Received an image!")
        try:
            # Convert your ROS Image message to OpenCV2
            cv2_img = bridge.imgmsg_to_cv2(msg, "bgr8")
        except CvBridgeError as e:
            print(e)
        else:
            # Save your OpenCV2 image as a jpeg 
            cv2.imwrite('croc_{}'.format(self.image_number) '.png', cv2_img)
            print("Saved Image!")
            self.image_number  = 1 
            time.sleep(3.0) 

if __name__ == '__main__':
    rospy.init_node('image_listener')
    image_node = Image()

and the error:

Traceback (most recent call last):
  File "/home/jehan/PycharmProjects/spawner/take_photo.py", line 73, in <module>
    image_node = Image()
  File "/home/jehan/PycharmProjects/spawner/take_photo.py", line 54, in __init__
    rospy.Subscriber(image_topic, Image, self.image_callback)
  File "/opt/ros/noetic/lib/python3/dist-packages/rospy/topics.py", line 563, in __init__
    super(Subscriber, self).__init__(name, data_class, Registration.SUB)
  File "/opt/ros/noetic/lib/python3/dist-packages/rospy/topics.py", line 144, in __init__
    raise ValueError("data_class [%s] is not a message data class"           
  • Related