ROS

收到彩色影像,發布灰階影像topic的方法

最近在做VSLAM相關的東西,剛好要用到web cam來做研究,所以研究了一下ROS的web cam driver,後來決定使用BOSCH寫的usb_cam。不過他們產生的topic只有彩色影像,我需要的是灰階影像,所以自己寫了個小程式來轉灰階。

 #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>
 using namespace cv;

 ros::Publisher pub;
 void transformer(const sensor_msgs::Image::ConstPtr& img)
 {
      cv_bridge::CvImagePtr cvimg = cv_bridge::toCvCopy(img , sensor_msgs::image_encodings::BGR8);
      //To Grayscale
      cv::Mat img_conv;
      cv::cvtColor(cvimg->image,img_conv,CV_BGR2GRAY);
      
      //Publish it
      cvimg->image = img_conv;
      cvimg->encoding = "mono8"; //這一行超容易忘記= =
      pub.publish(cvimg->toImageMsg());
 }

 int main(int argc, char** argv)
 {
      ros::init(argc, argv, "color_to_gray_node");
      ros::NodeHandle node;

      pub = node.advertise("/usb_cam/image_mono", 1000);
      ros::Subscriber sub = node.subscribe("/usb_cam/image_raw", 1, transformer);

      ros::spin();
}

其實滿簡單的,不過不熟ROS的人可能會不知道要改msg的encoding(就是cvimg->encoding = “mono8″),所以還是寫一篇出來供之後可能會用到的人參考~

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s