【问题标题】:Counting the number of iterations through a ROS subscriber node计算通过 ROS 订阅者节点的迭代次数
【发布时间】:2021-11-21 23:59:44
【问题描述】:

我正在尝试编写一个订阅者,它将在凉亭模拟中从相机拍摄图像并保存它们。我可以拍照并保存它们,但是我每次都尝试增加图像名称,但我发现这样做很难。我尝试创建一个类,然后每次运行 image_callback 函数时在类内增加一个数字(image_number),但是我得到一个错误。我还尝试定义一个全局变量并对其进行递增,但它无法识别函数内的变量。我附上了下面的代码和错误,非常感谢任何帮助!

# 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()

和错误:

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"%data_class.__class__.__name__)
ValueError: data_class [type] is not a message data class

【问题讨论】:

    标签: python class global-variables ros


    【解决方案1】:

    您的问题不在于计数器。事实上,你的类被称为Image,就像消息类型一样。这意味着您将重新定义导入的消息类型。然后当您创建订阅者时,Image 类型实际上就是类;不是 ROS 消息类型。我建议使用不同的类名:

    class ImageNode(object):
    
    image_node = ImageNode()
    

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      相关资源
      最近更新 更多