RealSense SDK 使用方式与典型场景
四、使用方式与典型场景
下面给出三个可运行的示例,覆盖最常用的场景。
示例一,C++ 最小取流程序。这是验证环境是否正常的标准写法,注意深度单位是从设备读取的:
#include <librealsense2/rs.hpp>
#include <iostream>
int main() {
rs2::pipeline pipe;
rs2::config cfg;
cfg.enable_stream(RS2_STREAM_DEPTH, 640, 480, RS2_FORMAT_Z16, 30);
cfg.enable_stream(RS2_STREAM_COLOR, 640, 480, RS2_FORMAT_BGR8, 30);
rs2::pipeline_profile profile = pipe.start(cfg);
auto depth_sensor = profile.get_device().first<rs2::depth_sensor>();
float depth_scale = depth_sensor.get_depth_scale();
std::cout << "depth scale = " << depth_scale << std::endl;
rs2::align align_to_color(RS2_STREAM_COLOR);
while (true) {
rs2::frameset frames = pipe.wait_for_frames();
frames = align_to_color.process(frames);
rs2::depth_frame depth = frames.get_depth_frame();
float d = depth.get_distance(320, 240);
std::cout << "center distance = " << d << " m" << std::endl;
}
return 0;
}
编译时链接 librealsense2 即可:
g++ demo.cpp -o demo -lrealsense2 -std=c++11
示例二,Python 取流并保存一帧深度图与彩色图,适合快速做数据检查:
import pyrealsense2 as rs
import numpy as np
import cv2
pipe = rs.pipeline()
cfg = rs.config()
cfg.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
cfg.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
profile = pipe.start(cfg)
scale = profile.get_device().first_depth_sensor().get_depth_scale()
align = rs.align(rs.stream.color)
for _ in range(30): # 丢弃前若干帧,等待自动曝光稳定
frames = pipe.wait_for_frames()
frames = align.process(frames)
depth = np.asanyarray(frames.get_depth_frame().get_data()) * scale
color = np.asanyarray(frames.get_color_frame().get_data())
cv2.imwrite("color.png", color)
cv2.imwrite("depth_vis.png", cv2.applyColorMap(
cv2.convertScaleAbs(depth, alpha=255.0 / max(depth.max(), 1e-6)),
cv2.COLORMAP_JET))
pipe.stop()
print("saved, depth unit =", scale, "m")
示例三,ROS 中启动相机并把深度对齐到彩色。这是机器人项目里最常见的启动方式,注意下游算法要订阅 aligned_depth_to_color 这个话题而不是原始深度话题,否则彩色与深度不会在同一视角下:
roslaunch realsense2_camera rs_camera.launch \
align_depth:=true \
enable_gyro:=true \
enable_accel:=true \
unite_imu_method:="linear_interpolation" \
depth_width:=640 depth_height:=480 depth_fps:=30 \
color_width:=640 color_height:=480 color_fps:=30
适用与不适用场景对照。
| 场景 | 是否合适 | 说明 |
|---|---|---|
| 室内机器人避障与抓取 | 非常合适 | D 系列的主场,深度质量与帧率均衡 |
| 三维重建与体积测量 | 合适 | 需注意深度噪声与空洞,配合滤波链使用 |
| 手势与人体姿态交互 | 合适 | 近距离效果好,ToF 型号更稳定 |
| 室外强阳光下的测距 | 不合适 | 红外投射器被阳光淹没,深度大面积失效 |
| 远超有效距离的测距 | 不合适 | 超出量程后精度急剧下降,应改用激光雷达 |
| 镜面、玻璃、深色吸光表面 | 需谨慎 | 反射或吸收导致深度缺失,需调整安装角度或补光 |
| 多机同场高密度部署 | 需设计 | 红外互相干扰,需错开或分时工作 |

