ROS2与opencv,Qt之间图像类型(image)转换

ROS2与OpenCV,Qt之间图像类型(image)转换

最近做的项目需要把opencv获得的图像数据通过ROS2发布,订阅后用Qt显示出来。但三者间有各自image类型,所以本文探讨下三者的数据类型转换

三者类型定义·

//OpenCV
cv::Mat opencv_image;
//ROS2
sensor_msgs::msg::Image ROS2_msg;
//Qt
QImage qt_image

OpenCV转ROS2

std::string rclcomm_image::mat_type23encoding(int mat_type)
{
    switch (mat_type)
    {
    case CV_8UC1:
        return "mono8";
    case CV_8UC3:
        return "bgr8";
    case CV_16SC1:
        return "mono16";
    case CV_8UC4:
        return "rgba8";
        default:
    }
}
auto stamp = clock.now();  //时间戳
ROS2_msg.header.stamp = stamp;
ROS2_msg.header.frame_id = "";
ROS2_msg.height = opencv_image.rows; //高
ROS2_msg.width = opencv_image.cols; //宽
ROS2_msg.encoding = mat_type23encoding(opencv_image.type()); //type
ROS2_msg.is_bigendian = false;
ROS2_msg.step = static_cast<sensor_msgs::msg::Image::_step_type>(opencv_image.step);
 ROS2_msg.data.assign(opencv_image.datastart, opencv_image.dataend);

OpenCV转Qt

//色彩空间转化
cvtColor(opencv_image, opencv_image, cv::COLOR_BGR2RGB); //参数1要处理的 参数2处理后的
//转化成QPixmap在label中显示
QPixmap showImage = QPixmap::fromImage(QImage((const uchar*)(opencv_image.data),
                                                                  opencv_image.cols,
                                                                  opencv_image.rows,
                                                                  opencv_image.step,
                                                                  QImage::Format_RGB888));

ROS2转Qt

可以转为Opencv格式再转为Qt格式

QImage::Format format;
format = QImage::Format_RGB888;

 cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(ROS2_msg,sensor_msgs::image_encodings::RGB8);
uchar *uchar_iamge_data = cv_ptr->image.data;
QPixmap showImage = QPixmap::fromImage(QImage(uchar_iamge_data,ROS2_msg.width,ROS2_msg.height,ROS2_msg.step,format));

ROS2也有直接转换的API

QImage qt_image = ros_image_to_qimage::Convert(ROS2_msg);

你可能感兴趣的:(opencv,qt,c++)