如何使用 Python 在 ROS 中订阅两个图像主题

How to subscribe to two image topics in ROS using Python

我正在尝试从车辆读取左右摄像头图像以进行一些图像处理。我不确定如何使用相同的回调函数来处理每个图像。我已经看到 where the data type was different, but not where both are of the same type, such as images. In this example,使用了单独的回调。

这是我目前的尝试:

import rospy
import cv2
import os
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
import message_filters

def read_cameras():
    imageL = rospy.Subscriber("/camera/left/image_raw", Image, image_callback)
    imageR = rospy.Subscriber("/camera/right/image_raw", Image, image_callback)
    # Synch images here ? 
    ts = message_filters.ApproximateTimeSynchronizer([imageL, imageR], 10)
    rospy.spin()
    
def image_callback(imageL, imageR):
    br = CvBridge()
    rospy.loginfo("receiving frame")
    imageLeft = br.imgmsg_to_cv2(imageL)
    imageRight = br.imgmsg_to_cv2(imageR)
    # Do some fancy computations on each image
    
if __name__ == '__main__':
    try:
        read_cameras()
    except rospy.ROSInterruptException:
        pass

此外,即使看了documentation on approximate time synchronization,我仍然不明白我需要输入的参数。每个摄像头都应该以 24fps 的速度输出图像。

每个节点都需要先初始化自己,然后才能使用 rospy.init_node().

与 ROS 网络交互

此外,您需要提供两个 message_filter.Subscriber 而不是 rospy.Subscribermessage_filter.ApproximateTimeSynchronizer。 最后,不要为每个订阅者设置回调,而应该使用 registerCallback.

ApproximateTimeSynchronizer 设置一次

这是一个工作示例:

#! /usr/bin/env python2

import rospy
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
import message_filters

def read_cameras():
    imageL = message_filters.Subscriber("/camera/left/image_raw", Image)
    imageR = message_filters.Subscriber("/camera/right/image_raw", Image)

    # Synchronize images
    ts = message_filters.ApproximateTimeSynchronizer([imageL, imageR], queue_size=10, slop=0.5)
    ts.registerCallback(image_callback)
    rospy.spin()

def image_callback(imageL, imageR):
    br = CvBridge()
    rospy.loginfo("receiving frame")
    imageLeft = br.imgmsg_to_cv2(imageL)
    imageRight = br.imgmsg_to_cv2(imageR)
    # Process images...

if __name__ == '__main__':
    rospy.init_node('my_node')
    try:
        read_cameras()
    except rospy.ROSInterruptException:
        pass

请务必检查您的 ApproximateTimeSynchronizer 的延迟 (slop) 并根据您的数据进行设置。