1

我在 ROS 2 中有一个发布者,它发布如下图像消息:

#!/usr/bin/env python3
# Revision $Id$

import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
import cv2
import numpy as np


class MinimalPublisher(Node):

    def __init__(self):

        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(Image, 'Image', 10)
        timer_period = 0.5  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0
        self.im_list = []
        
        self.cv_image = cv2.imread('test.jpg') ### an RGB image 
        self.bridge = CvBridge()
       
    def timer_callback(self):
        
        self.publisher_.publish(self.bridge.cv2_to_imgmsg(np.array(self.cv_image), "bgr8"))
        self.get_logger().info('Publishing an image')
       

def main(args=None):

    rclpy.init(args=args)
    minimal_publisher = MinimalPublisher()
    rclpy.spin(minimal_publisher)
    minimal_publisher.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()

它适用于单个图像。但我想发布一批具有给定形状的图像:

[12, 3, 224, 224] => [批次、通道、宽度、高度]

我尝试将其作为图像列表发送,但失败了。怎么做?

更多信息:

python 3.6
ROS 2 - 雄辩的(从源代码构建)
Ubuntu 18

4

1 回答 1

0

最后,我构建了一个自定义消息,如下所示:

sensor_msgs/图像[2]数据

批量大小为 2。

然后,将其添加到我的发布者,如下所示:

#!/usr/bin/env python3
# Revision $Id$


import rclpy
from rclpy.node import Node
from custom_batch.msg import Batch #### import custom message
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
import cv2
import numpy as np


class MinimalPublisher(Node):

    def __init__(self):
        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(Batch, 'Image', 10) #### change here
        timer_period = 0.5  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0
        self.im_list = []
        self.cv_image1 = cv2.imread('3.jpg')
        self.cv_image2 = cv2.imread('2.jpg')
        self.bridge = CvBridge()

    def timer_callback(self):

        #### custom message
        my_msg = Batch()
        my_msg.data[0] = self.bridge.cv2_to_imgmsg(np.array(self.cv_image1), "bgr8")
        my_msg.data[1] = self.bridge.cv2_to_imgmsg(np.array(self.cv_image2), "bgr8")
        #####
        self.publisher_.publish(my_msg) ## custom message
        self.get_logger().info('Publishing a batch of images')

def main(args=None):

    rclpy.init(args=args)
    minimal_publisher = MinimalPublisher()
    rclpy.spin(minimal_publisher)
    minimal_publisher.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
     main()

您可以在此处找到有关 ROS2 中自定义消息的有用说明。

于 2020-08-10T06:06:13.770 回答