美文网首页
ros(c++)之cv_bridge库简单使用

ros(c++)之cv_bridge库简单使用

作者: 5john家安 | 来源:发表于2017-11-10 18:53 被阅读0次

    结果

    一个彩色视图窗口和一个灰色视图窗口

    内部逻辑

    订阅rgb/image_raw话题,利用cv_bridge将收到的sensor_msgs/image类型消息转为cv_bridge::CvImagePtr类型数据,其内部属性即有Mat格式图片数据,调用cvtColor函数将彩色Mat转为灰色Mat,最终展示两个窗口

    源码

    cpp

    #include "ros/ros.h"
    #include "image_transport/image_transport.h"
    #include "opencv2/highgui/highgui.hpp"
    #include "cv_bridge/cv_bridge.h"
    #include "sensor_msgs/image_encodings.h"
    
    void showColorGrayView(const sensor_msgs::ImageConstPtr msgImg)
    {
      cv_bridge::CvImagePtr cvImgPtr;
      try{
        cvImgPtr=cv_bridge::toCvCopy(msgImg,sensor_msgs::image_encodings::BGR8);
      }
      catch(cv_bridge::Exception e){
        ROS_ERROR_STREAM("Cv_bridge Exception:"<<e.what());
        return;
      }
      cv::Mat cvColorImgMat=cvImgPtr->image;
      cv::Mat cvGrayImgMat;
      cv::cvtColor(cvColorImgMat,cvGrayImgMat,CV_BGR2GRAY);
      cv::imshow("colorview",cvColorImgMat);
      cv::imshow("grayview",cvGrayImgMat);
      cv::waitKey(5);
    }
    int main(int argc, char **argv)
    {
      ros::init(argc, argv, "grayview");
      ros::NodeHandle nh;
      image_transport::ImageTransport it(nh);
      cv::namedWindow("colorview",cv::WINDOW_NORMAL);
      cv::moveWindow("colorview",100,100);
      cv::namedWindow("grayview",cv::WINDOW_NORMAL);
      cv::moveWindow("grayview",600,100);
      image_transport::Subscriber sub = it.subscribe("/rgb/image_raw", 1, showColorGrayView);
      ros::spin();
    
      return 0;
    }
    

    package.xml

    <?xml version="1.0"?>
    <package format="2">
      <name>graycamera</name>
      <version>0.1.0</version>
      <description>The graycamera package</description>
      <maintainer email="fivejohn@5john.cn">fivejohn</maintainer>
      <license>Apache 2.0</license>
      <author >fivejohn</author>
      <buildtool_depend>catkin</buildtool_depend>
      <build_depend>roscpp</build_depend>
      <build_export_depend>roscpp</build_export_depend>
      <exec_depend>roscpp</exec_depend>
    </package>
    

    CMakeList.txt

    cmake_minimum_required(VERSION 2.8.3)
    project(graycamera)
    find_package(catkin REQUIRED COMPONENTS
      roscpp
      image_transport
      cv_bridge
      sensor_msgs
    )
    catkin_package()
    include_directories(
      ${catkin_INCLUDE_DIRS}
    )
    find_package(OpenCV)
    include_directories(
      ${OpenCV_INCLUDE_DIRS}
    )
    add_executable(grayview src/grayview.cpp)
    target_link_libraries(grayview
      ${catkin_LIBRARIES}
      ${OpenCV_LIBRARIES}
    )
    

    相关文章

      网友评论

          本文标题:ros(c++)之cv_bridge库简单使用

          本文链接:https://www.haomeiwen.com/subject/ttcimxtx.html