我正在尝试订阅“/ camera / image_color”主题,该主题是我的相机中的数据。然后,我想在opencv中对这些图像进行一些巫术设计,并以特定的频率发布它们。这样我就可以通过另一个节点订阅它们。

我已经尝试过以下代码及其许多变体。此时,代码什么都不做。没有图像被发布到“/ imagetimer”主题。我得到一个输出“Timing images”,然后什么也没有发生。

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import os
import numpy as np


class Nodo(object):
    def __init__(self):
        # Params
        self.image = None
        self.br = CvBridge()
        # Node cycle rate (in Hz).
        self.loop_rate = rospy.Rate(1)

        # Publishers
        self.pub = rospy.Publisher('imagetimer', Image,queue_size=10)

        # Subscribers
        rospy.Subscriber("/camera/image_color",Image,self.callback)


    def callback(self, msg):
        self.image = self.br.imgmsg_to_cv2(msg)


    def start(self):
        rospy.loginfo("Timing images")
        rospy.spin()
        br = CvBridge()
        while not rospy.is_shutdown():
            rospy.loginfo('publishing image')
            #br = CvBridge()
            self.pub.publish(br.cv2_to_imgmsg(self.image))
            rate.sleep()

if __name__ == '__main__':
    rospy.init_node("imagetimer111", anonymous=True)
    my_node = Nodo()
    my_node.start()

最佳答案

一旦运行rospy.spin(),该代码就不会继续。在rospy中,只要有了rospy.Subsriber()行,它就会从另一个线程中剥离出来进行回调。 rospy.spin()本质上使节点保持 Activity 状态,因此回调并不断变化。
在这里,您使用while循环来保持节点 Activity ,因此不需要rospy.spin()
这个版本应该工作:

import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import os
import numpy as np

class Nodo(object):
    def __init__(self):
        # Params
        self.image = None
        self.br = CvBridge()
        # Node cycle rate (in Hz).
        self.loop_rate = rospy.Rate(1)

        # Publishers
        self.pub = rospy.Publisher('imagetimer', Image,queue_size=10)

        # Subscribers
        rospy.Subscriber("/camera/image_color",Image,self.callback)

    def callback(self, msg):
        rospy.loginfo('Image received...')
        self.image = self.br.imgmsg_to_cv2(msg)


    def start(self):
        rospy.loginfo("Timing images")
        #rospy.spin()
        while not rospy.is_shutdown():
            rospy.loginfo('publishing image')
            #br = CvBridge()
            if self.image is not None:
                self.pub.publish(br.cv2_to_imgmsg(self.image))
            self.loop_rate.sleep()

if __name__ == '__main__':
    rospy.init_node("imagetimer111", anonymous=True)
    my_node = Nodo()
    my_node.start()

10-08 14:01