Converting OpenCV to ROS images using cv_bridge

This is an image callback function, and it basically converts the ROS image messages into the OpenCV cv::Mat type using the CvBridge APIs. The following is how we can convert ROS to OpenCV, and vice versa:

  void imageCb(const sensor_msgs::ImageConstPtr& msg) 
  { 
 
    cv_bridge::CvImagePtr cv_ptr; 
    namespace enc = sensor_msgs::image_encodings; 
 
    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; 
    } 

To start with CvBridge, we should start with creating an instance of a CvImage. Given next is the creation of the CvImage pointer:

 cv_bridge::CvImagePtr cv_ptr; 

The CvImage type is a class ...

Get Mastering ROS for Robotics Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.