【问题标题】:Why is ROS publisher not publishing first message?为什么 ROS 发布者不发布第一条消息?
【发布时间】:2019-08-06 06:59:54
【问题描述】:

我有一个发布者发布两个主题为“图像”和“深度”的图像,一个订阅者正在收听这两个主题。

发布者从两个文件夹中读取图像并在同一个循环中发布。每个图像都有一个对应的深度,并且这两个用相同的名称映射。发布速率为 1hz。

订阅者没有获得第一对图像。我试图转储订阅到文件夹的图像。除第一对图像外,所有已发布的图像都被丢弃。

这是发布者的代码

import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import os


def talker():

    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(1) # 1hz
    bridge = CvBridge()
    hello_str = "hello world %s" % rospy.get_time()
    rospy.loginfo(hello_str)
    path = "/home/test_img/"
    imglist = os.listdir(path)
    path_depth = "/home/out_depth/"


    for i in range(0,len(imglist)):
        topic = 'image'
        print(topic)
        pub = rospy.Publisher(topic, Image, queue_size=10)
        fn = path+imglist[i]
        print(fn)
        img = cv2.imread(fn)
        imgMsg = bridge.cv2_to_imgmsg(img, "bgr8")
        pub.publish(imgMsg)




        topic = 'depth'
        print(topic)
        pub = rospy.Publisher(topic, Image, queue_size=10)
        fn = path_depth+imglist[i]
        print(fn)
        img = cv2.imread(fn)
        imgMsg = bridge.cv2_to_imgmsg(img, "bgr8")
        pub.publish(imgMsg)
        rate.sleep()




if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

这是订阅者的代码

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


def callback(data):


    bridge = CvBridge()
    # Convert your ROS Image message to OpenCV2
    cv2_img = bridge.imgmsg_to_cv2(data, "bgr8")
    cv2.imwrite('out_rgbd/'+datetime.now().strftime("%I:%M%S%f")+".jpg", cv2_img)

def listener():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # name are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)



    topic = 'image'
    print(topic)
    rospy.Subscriber(topic, Image, callback)

    topic = 'depth'
    print(topic)
    rospy.Subscriber(topic, Image, callback)

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

在执行发布者时,会列出所有图像(来自 print(fn) 行)。但是订阅者没有获得第一对图像。

我尝试使用“rosrecord”记录消息。它也没有获得第一对。

可能是什么原因?

【问题讨论】:

  • 我要改变的一件事是在 for 循环之外创建发布者一次,而不是每次都重新创建它。可能导致数据丢失的另一件事是节点出现的顺序,如果发布者先于订阅者出现,那么第一条消息可能永远不会到达订阅者。

标签: python ros


【解决方案1】:

在初始化发布者时尝试设置latch=True。
请参阅https://answers.ros.org/question/195348/about-subscriber-structure-and-latch-on-publisher/ 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2021-09-13
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多