ros的web可视化开发-视频流的接入
2023-12-08 # 实用教程

前言

最近在开发ros的网页后台,因为网上这类开发教程跟资料挺少的,所以我想记录顺便分享下自己的开发过程。

实现框架

我看了下目前所能参考的开源项目,真正对二次开发比较友好的项目可能就只有Robot Web Tools提供的这些js库跟它下面的应用案例,参考过它的案例就大概对ros的web开发有一定思路了。我以自己接入的摄像头数据流为例,给大家介绍下,大概框架如下图所示。

framework

从左往右看,原始摄像头通过usb_cam节点把摄像头以ros topic的形式接入到了ros中,然后借助rosbridge节点基于websocket协议实现了跟浏览器的通信,roslib.js在获取到来自ros的视频流数据后便可修改html中img对象来显示实时的图像了。

前端开发

可以新建一个index.html文件,写入网页代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ROS Connection Status</title>
</head>
<body>
<div><h1>ROS Connection Status</h1><p id="status">Connecting...</p></div>
<img id="imageDisplay" src="" alt="ROS Image">

<script src="https://cdn.jsdelivr.net/npm/roslib@1/build/roslib.js"></script>
<script>
// Replace 'ws://localhost:9090' with the actual WebSocket URL of your ROS server
const ros = new ROSLIB.Ros({
url: 'ws://localhost:9090'
});
ros.on('connection', () => {
updateStatus('Connected to ROS');
});
ros.on('error', (error) => {
updateStatus(`Error: ${error}`);
});
ros.on('close', () => {
updateStatus('Connection closed');
});
function updateStatus(message) {
document.getElementById('status').textContent = message;
}

const imageTopic = new ROSLIB.Topic({
ros: ros,
name: '/usb_cam/image_raw/compressed', // ros topic name
messageType: 'sensor_msgs/CompressedImage'
});

const imageElement = document.getElementById('imageDisplay');
imageTopic.subscribe(function (message) {
const imageData = "data:image/png;base64," + message.data; // Assuming the image data is in base64 format
imageElement.src = imageData;
});
</script>

</body>
</html>

主要编写的代码就这些,需要关注的就是websocket的地址和视频流ros topic的名字跟类型,然后就到实际调试了。

最终实现

  1. 首先在ros下启动rosbridgeusb_cam节点,确保视频流的topic是正常输出的。
  2. 打开浏览器,把上面写好的index.html文件拖入浏览器中即可看到效果如下。

result