[Goal]

  • sensor_msgs::Image 를 cv::Mat & cv::Mat 을 sensor_msgs::Image 로 변환

[Reference Site]


[Convert sensor_msgs::Image to cv::Mat]


  • Code example
cv::Mat sensorMsg2cvMat(const sensor_msgs::ImageConstPtr &img_msg)
{
    cv_bridge::CvImageConstPtr ptr;
    if (img_msg->encoding == "8UC1")
    {
        sensor_msgs::Image img;
        img.header = img_msg->header;
        img.height = img_msg->height;
        img.width = img_msg->width;
        img.is_bigendian = img_msg->is_bigendian;
        img.step = img_msg->step;
        img.data = img_msg->data;
        img.encoding = "mono8";
        ptr = cv_bridge::toCvCopy(img, sensor_msgs::image_encodings::MONO8);
    }
    else
        ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::MONO8);

    cv::Mat img = ptr->image.clone();
    cv::cvtColor(img,img,cv::COLOR_BGRA2BGR);

    return img;
}

[Convert cv::Mat to sensor_msgs::Image]


  • Code example
sensor_msgs::Image cvMat2sensorMsg(cv::Mat image, std_msgs::Header header)
{
    cv_bridge::CvImage img_bridge;
    sensor_msgs::Image img;

    img_bridge = cv_bridge::CvImage(header, sensor_msgs::image_encodings::RGB8, image);
    img_bridge.toImageMsg(img);

    return img;
}

[Others]


    • To change return following as:
cv::Mat sensorMsg2cvMat(const sensor_msgs::Image &img_msg)
{
    // ***** fill in your code ***** //
    cv_bridge::CvImageConstPtr ptr;
    ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::MONO8);
    cv::Mat img = ptr->image.clone();

    // Case 1. return empty image 
    return cv::Mat{};

    // Case 2. return black image same size as img_msg
    return cv::Mat{img.size(), img.type(), cv::Scalar{0,0,0}};
}

[Error]

    • Code change following as (이미지 filter 문제):
cv::cvtColor(img, img, cv::COLOR_BGRA2BGR);

 


// Error Code Line
ptr = cv_bridge::toCvCopy(img, sensor_msgs::image_encodings::MONO8);

// Modfied following as:
ptr = cv_bridge::toCvCopy(img_msg, sensor_msgs::image_encodings::BGRA8);

+ Recent posts