RGB数组到MIME类型图像到字符串

问题描述 投票:0回答:1

我正在使用 ROS。我正在订阅主题 /camera,它每秒更新我 30 次消息。该消息包含框架的宽度和高度以及整数数组(0-255)。数组看起来像:

[pixel_1_r, pixel_1_g, pixel_1_b, pixel_2_r, pixel_2_g, pixel_2_b, ...]

最后我想在我的网络服务器中显示相机图像。为此,首先我需要使用 C++ 代码中的数据创建 MIME 类型图像。然后我想将该图像转换为字符串,然后我将在主题 /camera_converted 上发布该字符串。 JS会听那个话题。在 JS 中,我将收到带有图像的字符串,我必须将其转换为 MIME 类型并在 img 标签中显示。

我正在寻找用 C++ 将 RGB 数组转换为 jpeg/png/whatever 并将其转换为 JS 可以转换为 jpeg/png/whatever 并在 img 标签中显示的字符串的最简单方法。

javascript c++ opencv image-processing ros
1个回答
0
投票

你可以做这样的事情:

包括c++:

#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <opencv2/opencv.hpp>

void cameraCallback(const sensor_msgs::Image::ConstPtr& msg) {

    cv::Mat image(msg->height, msg->width, CV_8UC3, const_cast<uint8_t*>(msg->data.data()));

    std::vector<uint8_t> jpegData;
    cv::imencode(".jpg", image, jpegData);

    std::string jpegString(jpegData.begin(), jpegData.end());

}

int main(int argc, char** argv) {
    ros::init(argc, argv, "image_converter");
    ros::NodeHandle nh;
    
    ros::Subscriber sub = nh.subscribe("/camera", 1, cameraCallback);

    ros::spin();
    return 0;
}

然后在js中:

const ROSLIB = require('roslib');

const ros = new ROSLIB.Ros();
ros.connect('ws://localhost:9090');
// or whatever your server port is

const imageTopic = new ROSLIB.Topic({
    ros: ros,
    name: '/camera_converted',
    messageType: 'std_msgs/String', // Adjust the message type as needed
});

imageTopic.subscribe(function (message) {
    const imageDataUri = `data:image/jpeg;base64,${message.data}`;
    const img = document.getElementById('cameraImage');
    img.src = imageDataUri;
});
© www.soinside.com 2019 - 2024. All rights reserved.