当然!以下是C++代码的示例,使用OpenCV和ROS发布cv::Mat图像:
"'cpp
#包含<ros/ros. h>
#包含<sensor_msgs/Image. h>
#包含<cv_bridge/cv_bridge. h>
int main(int argc, char**argv)
{
//初始化ROS节点
ROS::init(argc, argv,"image_publisher");
ROS::NodeHandle nh;
//创建发布者对象
ROS::Publisherimage_pub=nh.广告<sensor_msgs::图像>("image_topic",1);
//使用OpenCV加载图像
::垫图像=cv::imread("path_to_image. png",cv::IMREAD_COLOR);
//创建sensor_msgs::图像消息
sensor_msgs::ImagePtr msg=cv_bridge::CvImage(std_msgs::Header(),"bgr8", image).toImageMsg();
//循环发布图片
ROS::loop_rate(10);//以10 Hz发布
而(ros::ok())
{
//发布图片消息
image_pub出版(味精);
//旋转一次处理回调
ROS::旋转一次();
//睡眠以保持所需的发布速率
loop_rate睡眠();
}
返回0;
}
```
在此代码中,您需要将“path_to_image. png”替换为图像文件的实际路径。代码创建一个ROS节点,为“image_topic”主题初始化一个发布者,并使用OpenCV加载图像。然后,它使用cv_bridge库将cv::Mat图像转换为sensor_msgs::图像消息。图像使用image_pub发布者以10 Hz的速率循环发布。最后,代码旋转以处理任何回调并休眠以保持所需的发布速率。
Certainly! Here's an example of C++ code to publish a cv::Mat image using OpenCV and ROS:
```cpp
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <cv_bridge/cv_bridge.h>
int main(int argc, char** argv)
{
// Initialize ROS node
ros::init(argc, argv, "image_publisher");
ros::NodeHandle nh;
// Create publisher object
ros::Publisher image_pub = nh.advertise<sensor_msgs::Image>("image_topic", 1);
// Load image using OpenCV
cv::Mat image = cv::imread("path_to_image.png", cv::IMREAD_COLOR);
// Create a sensor_msgs::Image message
sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();
// Loop to publish the image
ros::Rate loop_rate(10); // Publish at 10 Hz
while (ros::ok())
{
// Publish the image message
image_pub.publish(msg);
// Spin once to process callbacks
ros::spinOnce();
// Sleep to maintain desired publishing rate
loop_rate.sleep();
}
return 0;
}
```
In this code, you need to replace "path_to_image.png" with the actual path to your image file. The code creates a ROS node, initializes a publisher for the "image_topic" topic, and loads the image using OpenCV. Then, it converts the cv::Mat image to a sensor_msgs::Image message using the cv_bridge library. The image is published in a loop at a rate of 10 Hz using the image_pub publisher. Finally, the code spins to process any callbacks and sleeps to maintain the desired publishing rate.