随手笔记——将ROS图像话题转为OpenCV图像格式处理后再转为ROS图像话题发布(C++版)

随手笔记——将ROS图像话题转为OpenCV图像格式处理后再转为ROS图像话题发布(C++版)

  • 说明
  • 关键函数
  • 代码

说明

将ROS图像话题转为OpenCV图像格式处理后再转为ROS图像话题发布,主要通过cv_bridge的toImageMsg()和toCvCopy()函数(C++版)。

关键函数

CvImagePtr toCvCopy(const sensor_msgs::ImageConstPtr& source,
                     const std::string& encoding = std::string());
CvImagePtr toCvCopy(const sensor_msgs::Image& source,
                     const std::string& encoding = std::string());
class CvImage
 {
   sensor_msgs::ImagePtr toImageMsg() const;
​
   // Overload mainly intended for aggregate messages that contain
   // a sensor_msgs::Image as a member.
   void toImageMsg(sensor_msgs::Image& ros_image) const;
 };

代码

 #include <ros/ros.h>
 #include <image_transport/image_transport.h>
 #include <cv_bridge/cv_bridge.h>
 #include <sensor_msgs/image_encodings.h>
 #include <opencv2/imgproc/imgproc.hpp>
 #include <opencv2/highgui/highgui.hpp>
  static const std::string OPENCV_WINDOW = "Image window";
 
 class ImageConverter
 {
   ros::NodeHandle nh_;
   image_transport::ImageTransport it_;
   image_transport::Subscriber image_sub_;
   image_transport::Publisher image_pub_;
​
 public:
   ImageConverter()
     : it_(nh_)
   {
     // Subscrive to input video feed and publish output video feed
     image_sub_ = it_.subscribe("/camera/image_raw", 1,
       &ImageConverter::imageCb, this);
     image_pub_ = it_.advertise("/image_converter/output_video", 1);
​
    cv::namedWindow(OPENCV_WINDOW);
   }
 
   ~ImageConverter()
   {
     cv::destroyWindow(OPENCV_WINDOW);
   }
 
   void imageCb(const sensor_msgs::ImageConstPtr& msg)
   {
      cv_bridge::CvImagePtr cv_ptr;
     try
     {
       cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
     }
     catch (cv_bridge::Exception& e)
     {
       ROS_ERROR("cv_bridge exception: %s", e.what());
       return;
     }
​
     // Draw an example circle on the video stream
     if (cv_ptr->image.rows > 60 && cv_ptr->image.cols > 60)
     cv::circle(cv_ptr->image, cv::Point(50, 50), 10, CV_RGB(255,0,0));
     // Update GUI Window
     cv::imshow(OPENCV_WINDOW, cv_ptr->image);
     cv::waitKey(3);
 
     // Output modified video stream
     image_pub_.publish(cv_ptr->toImageMsg());
   }
 };
 
 int main(int argc, char** argv)
 {
   ros::init(argc, argv, "image_converter");
   ImageConverter ic;
   ros::spin();
   return 0;
 }

代码来自wiki文章来源地址https://uudwc.com/A/0n39a

原文地址:https://blog.csdn.net/jppdss/article/details/131548433

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年07月06日 07:31
读书笔记-《ON JAVA 中文版》-摘要19[第十八章 字符串-2]
下一篇 2023年07月06日 07:33