Converting OpenCV-ROS images using cv_bridge

This is an image callback function and it basically converts the ROS image messages into OpenCV cv::Mat type using the CvBridge APIs. 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 provided by cv_bridge, which consists of information such as an OpenCV image, its encoding, ROS header, and so on. Using this type,
we can easily convert an ROS image to OpenCV, and vice versa.

cv_ptr = cv_bridge::toCvCopy(msg, 
sensor_msgs::image_encodings::BGR8);

We can handle the ROS image message in two ways: either we can make a copy of the image or we can share the image data. When we copy the image, we can process the image, but if we use shared pointer, we can't modify the data. We use toCvCopy() for creating a copy of the ROS image, and the toCvShare() function is used to get the pointer of the image. Inside these functions, we should mention the ROS message and the type of encoding.

    if (cv_ptr->image.rows > 400 && cv_ptr->image.cols > 600){ 
  detect_edges(cv_ptr->image); 
      image_pub_.publish(cv_ptr->toImageMsg()); 
  } 

In this section, we are extracting the image and its properties from the CvImage instance, and accessing the cv::Mat object from this instance. This code simply checks whether the rows and columns of the image are in a particular range, and if it is true, it will call another method called detect_edges(cv::Mat), which will process the image given as argument and display the edge detected image.

image_pub_.publish(cv_ptr->toImageMsg()); 

The preceding line will publish the edge detected image after converting to ROS image message. Here we are using the toImageMsg() function for converting the CvImage instance to a ROS image message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.238.171