message_filters不调用回调函数

时间:2019-02-20 18:00:48

标签: python ros rospy

我正在尝试使用message_filters来订阅两个主题。这是我的代码

class sync_listener:
    def __init__(self):
        self.image_sub = message_filters.Subscriber('camera/rgb/image_color', Image)
        self.info_sub = message_filters.Subscriber('camera/projector/camera_info', CameraInfo)
        self.ts = message_filters.TimeSynchronizer([self.image_sub, self.info_sub], 10)
        self.ts.registerCallback(self.callback)

    def callback(self, image, camera_info):
        print("done")

def main(args):
    ls = sync_listener()
    rospy.init_node('sample_message_filters', anonymous=True)
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")

if __name__ == '__main__':
    main(sys.argv)

但是它永远不会进入回调函数。它只是冻结在rospy.spin()

1 个答案:

答案 0 :(得分:1)

我使用TimeSynchronizer而不是使用ApproximateTimeSynchronizer,它起作用了。因此,我将代码更改为-

class sync_listener:
    def __init__(self):
        self.image_sub = message_filters.Subscriber('camera/rgb/image_color', Image)
        self.info_sub = message_filters.Subscriber('camera/projector/camera_info', CameraInfo)
        self.ts = message_filters.ApproximateTimeSynchronizer([self.image_sub, self.info_sub], 1, 1) # Changed code
        self.ts.registerCallback(self.callback)

    def callback(self, image, camera_info):
        print("done")

def main(args):
    ls = sync_listener()
    rospy.init_node('sample_message_filters', anonymous=True)
    try:
        rospy.spin()
    except KeyboardInterrupt:
        print("Shutting down")

if __name__ == '__main__':
    main(sys.argv)

在找到此解决方案之前,我只是使用全局变量来访问第一个主题的消息,方法是将消息分配给回调中的全局变量,并在第二个回调中使用它,这就是我能够工作的方式既。它不干净,但可以省去数小时的挫败感。