Home > Software design >  How to publish multiarray msg as a Image.msg?
How to publish multiarray msg as a Image.msg?

Time:12-15

I am trying to send multiarray message that contains feature descriptors in the form of like 112x92. I found something that I should use Image msg for multiarrays. How can I send this message as an ROS2 msg?

First edit : This is my code. I have pandas dataframe(self.df) that contains feature descriptor. I convert it to numpy array. Then I give it to the cv2_to_imgmsg() function and publish the message.

            # Publish the coordinates to the topics
            feature_data = self.df.to_numpy()
            print("feature_data", feature_data)
            feature_data = self.featuresSendingBridge.cv2_to_imgmsg(feature_data)
            self.publisher_features.publish(feature_data)

My feature data is below as a numpy array.

feature_data [[nan nan] [1.0 array([[ 3, 56, 30, ..., 1, 1, 0], [ 18, 3, 1, ..., 0, 0, 1], [ 40, 19, 0, ..., 9, 1, 0], ..., [ 0, 0, 2, ..., 1, 0, 0], [ 1, 2, 5, ..., 4, 13, 7], [ 2, 1, 3, ..., 3, 1, 2]], dtype=float32)]]

I received this error :

Exception has occurred: KeyError 'object'

CodePudding user response:

If you want to publish a multiarray message as an image message using ROS2 and cv2, you can use the cv2_to_image_msg() function from the cv_bridge package. This function takes in a cv2 image and a ROS2 image message and returns a ROS2 image message with the data from the cv2 image.

Here is an example of how you can use this function:

import cv2
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
    
# Create a CvBridge object to convert between ROS2 image messages and cv2 images
bridge = CvBridge()

# Load your cv2 image
img = cv2.imread("my_image.png")
    
# Create a ROS2 image message
msg = Image()
    
# Convert the cv2 image to a ROS2 image message
msg = cv2_to_image_msg(img, msg)
    
# Publish the ROS2 image message
pub.publish(msg)

Note that this example assumes that you have already created a ROS2 publisher and have subscribed to the appropriate topic. You will also need to have the cv_bridge package installed in your workspace.

  • Related