首页
/ Intel RealSense深度摄像头Python开发实战指南

Intel RealSense深度摄像头Python开发实战指南

2026-04-16 08:22:50作者:卓艾滢Kingsley

准备阶段:环境配置与依赖管理

开发环境基础组件安装

构建Intel RealSense Python开发环境需要以下核心组件支持:

  • Python 3.6+:推荐使用Python 3.9或更高版本以获得最佳兼容性
  • CMake 3.10+:用于项目构建系统配置
  • Git:用于代码仓库克隆与版本控制
  • C++编译器:GCC 7.5+或Clang 6.0+(Linux)、Visual Studio 2019+(Windows)

在Ubuntu系统中可通过以下命令安装基础依赖:

sudo apt-get update && sudo apt-get install -y \
    python3 python3-pip python3-dev \
    cmake git build-essential \
    libssl-dev libusb-1.0-0-dev pkg-config libgtk-3-dev

源代码获取与项目结构

克隆librealsense项目仓库:

git clone https://gitcode.com/GitHub_Trending/li/librealsense
cd librealsense

项目核心Python开发资源分布:

  • 绑定源码:wrappers/python/src/
  • 示例程序:examples/python/
  • 官方文档:doc/api/python.md

安装阶段:编译与配置

构建配置参数设置

创建构建目录并配置CMake参数:

mkdir build && cd build
cmake .. -DBUILD_PYTHON_BINDINGS=ON \
         -DCMAKE_BUILD_TYPE=Release \
         -DPYTHON_EXECUTABLE=$(which python3) \
         -DBUILD_EXAMPLES=ON

关键配置参数说明:

  • -DBUILD_PYTHON_BINDINGS=ON:启用Python绑定生成
  • -DCMAKE_BUILD_TYPE=Release:优化编译模式
  • -DPYTHON_EXECUTABLE:指定Python解释器路径
  • -DBUILD_EXAMPLES=ON:构建示例程序

编译与安装流程

执行编译命令:

make -j$(nproc)  # 使用所有可用CPU核心
sudo make install

安装完成后,Python模块会被安装到系统Python路径,通常位于/usr/local/lib/pythonX.Y/dist-packages/或虚拟环境的对应目录。

pyrealsense2包安装验证

通过pip验证安装状态:

pip list | grep pyrealsense2

若显示版本信息,则表示安装成功。如需升级到最新版本:

pip install --upgrade pyrealsense2

验证阶段:设备连接与基础功能测试

设备连接状态诊断

创建设备检测脚本device_detection.py

import pyrealsense2 as rs

# 创建上下文对象
ctx = rs.context()

# 列出所有连接的设备
devices = ctx.query_devices()
if len(devices) == 0:
    print("未检测到RealSense设备")
else:
    print(f"检测到{len(devices)}个RealSense设备:")
    for dev in devices:
        print(f"设备名称: {dev.get_info(rs.camera_info.name)}")
        print(f"序列号: {dev.get_info(rs.camera_info.serial_number)}")
        print(f"固件版本: {dev.get_info(rs.camera_info.firmware_version)}\n")

运行脚本检测设备连接状态:

python3 device_detection.py

深度流与彩色流获取

创建基础流获取示例stream_capture.py

import pyrealsense2 as rs
import numpy as np

# 配置流参数
width, height = 640, 480
fps = 30

# 创建管道和配置对象
pipeline = rs.pipeline()
config = rs.config()

# 启用深度流和彩色流
config.enable_stream(rs.stream.depth, width, height, rs.format.z16, fps)
config.enable_stream(rs.stream.color, width, height, rs.format.bgr8, fps)

try:
    # 启动流
    pipeline.start(config)
    
    # 获取并打印流信息
    profile = pipeline.get_active_profile()
    depth_profile = rs.video_stream_profile(profile.get_stream(rs.stream.depth))
    color_profile = rs.video_stream_profile(profile.get_stream(rs.stream.color))
    
    print(f"深度流分辨率: {depth_profile.width()}x{depth_profile.height()}")
    print(f"彩色流分辨率: {color_profile.width()}x{color_profile.height()}")
    
    # 捕获一帧数据
    frames = pipeline.wait_for_frames()
    depth_frame = frames.get_depth_frame()
    color_frame = frames.get_color_frame()
    
    if depth_frame and color_frame:
        # 转换为numpy数组
        depth_image = np.asanyarray(depth_frame.get_data())
        color_image = np.asanyarray(color_frame.get_data())
        
        print(f"深度数据形状: {depth_image.shape}")
        print(f"彩色数据形状: {color_image.shape}")
        print(f"深度范围: {np.min(depth_image)} - {np.max(depth_image)}")

finally:
    # 停止流
    pipeline.stop()

RealSense Viewer工具使用

RealSense Viewer是设备调试的重要工具,可通过以下命令启动:

realsense-viewer

RealSense Viewer界面 RealSense Viewer工具界面,显示设备连接状态和流控制选项

实践阶段:核心功能实现

深度数据处理与可视化

创建深度数据可视化脚本depth_visualization.py

import pyrealsense2 as rs
import numpy as np
import cv2

# 配置深度和彩色流
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

# 启动流
pipeline.start(config)

# 创建对齐对象(将深度框与彩色框对齐)
align_to = rs.stream.color
align = rs.align(align_to)

try:
    while True:
        # 等待帧
        frames = pipeline.wait_for_frames()
        
        # 对齐深度帧与彩色帧
        aligned_frames = align.process(frames)
        aligned_depth_frame = aligned_frames.get_depth_frame()
        color_frame = aligned_frames.get_color_frame()
        
        if not aligned_depth_frame or not color_frame:
            continue
        
        # 转换为numpy数组
        depth_image = np.asanyarray(aligned_depth_frame.get_data())
        color_image = np.asanyarray(color_frame.get_data())
        
        # 应用颜色映射到深度图像(图像可视化)
        depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)
        
        # 水平堆叠图像
        images = np.hstack((color_image, depth_colormap))
        
        # 显示图像
        cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('RealSense', images)
        
        # 按'q'键退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

finally:
    # 停止流
    pipeline.stop()
    cv2.destroyAllWindows()

点云数据生成与导出

创建点云导出脚本pointcloud_export.py

import pyrealsense2 as rs
import numpy as np

# 配置流
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.rgb8, 30)

# 启动流
pipeline.start(config)

# 创建点云对象
pc = rs.pointcloud()
points = rs.points()

try:
    # 等待高质量帧
    for _ in range(10):
        frames = pipeline.wait_for_frames()
    
    depth_frame = frames.get_depth_frame()
    color_frame = frames.get_color_frame()
    
    if not depth_frame or not color_frame:
        raise RuntimeError("无法获取帧数据")
    
    # 生成点云
    pc.map_to(color_frame)
    points = pc.calculate(depth_frame)
    
    # 获取点云和纹理数据
    vtx = np.asanyarray(points.get_vertices())
    tex = np.asanyarray(points.get_texture_coordinates())
    
    print(f"生成点云数量: {len(vtx)}")
    
    # 导出为PLY文件
    ply = points.export_to_ply("output.ply", color_frame)
    print(f"点云已导出至: output.ply")

finally:
    pipeline.stop()

3D重建应用示例

利用OpenCV的kinfu模块实现实时3D重建:

import pyrealsense2 as rs
import cv2
import numpy as np

# 配置RealSense流
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)

# 启动流
pipeline.start(config)

# 创建kinfu对象
kinfu = cv2.rgbd.KinfuCreator_create()

try:
    while True:
        # 获取深度帧
        frames = pipeline.wait_for_frames()
        depth_frame = frames.get_depth_frame()
        
        if not depth_frame:
            continue
            
        # 转换为OpenCV格式
        depth_image = np.asanyarray(depth_frame.get_data())
        
        # 预处理深度图像
        depth_image = cv2.normalize(depth_image, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)
        
        # 运行kinfu重建
        success, state = kinfu.update(depth_image)
        
        if success:
            # 获取渲染图像
            render_image = kinfu.render()
            
            # 显示结果
            cv2.imshow('3D Reconstruction', render_image)
            
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

finally:
    pipeline.stop()
    cv2.destroyAllWindows()

3D重建效果 基于RealSense深度数据的实时3D重建效果,展示了室内场景的点云构建过程

进阶阶段:高级功能与优化

多设备同步配置

多摄像头同步采集示例multi_camera_sync.py

import pyrealsense2 as rs
import numpy as np
import cv2

# 设备配置
devices = []
pipelines = []
configs = []

# 获取所有连接的设备
ctx = rs.context()
connected_devices = ctx.query_devices()

for dev in connected_devices:
    pipeline = rs.pipeline()
    config = rs.config()
    
    # 为每个设备配置唯一的流
    config.enable_device(dev.get_info(rs.camera_info.serial_number))
    config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
    config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
    
    pipelines.append(pipeline)
    configs.append(config)

# 启动所有管道
for pipe, cfg in zip(pipelines, configs):
    pipe.start(cfg)

try:
    while True:
        frames_list = []
        
        # 从所有设备获取帧
        for pipe in pipelines:
            frames = pipe.wait_for_frames()
            frames_list.append(frames)
        
        # 处理和显示帧
        display_images = []
        for frames in frames_list:
            depth_frame = frames.get_depth_frame()
            color_frame = frames.get_color_frame()
            
            depth_image = np.asanyarray(depth_frame.get_data())
            color_image = np.asanyarray(color_frame.get_data())
            
            depth_colormap = cv2.applyColorMap(
                cv2.convertScaleAbs(depth_image, alpha=0.03), 
                cv2.COLORMAP_JET
            )
            
            display_images.append(np.hstack((color_image, depth_colormap)))
        
        # 合并所有设备的图像
        combined_image = np.vstack(display_images)
        
        cv2.imshow('Multi-Camera View', combined_image)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

finally:
    # 停止所有管道
    for pipe in pipelines:
        pipe.stop()
    cv2.destroyAllWindows()

性能优化策略

  1. 帧率控制:根据应用需求调整流分辨率和帧率
# 降低分辨率和帧率以提高性能
config.enable_stream(rs.stream.depth, 424, 240, rs.format.z16, 15)
  1. 数据处理优化:使用硬件加速和多线程处理
# 使用OpenCV的CUDA加速功能
if cv2.cuda.getCudaEnabledDeviceCount() > 0:
    depth_image_gpu = cv2.cuda_GpuMat()
    depth_image_gpu.upload(depth_image)
    # 在GPU上进行图像处理
  1. 电源管理:平衡性能与功耗
# 获取设备电源管理选项
dev = pipeline.get_active_profile().get_device()
power_sensor = dev.first_sensor()

# 设置电源模式
power_options = power_sensor.get_option(rs.option.power_line_frequency)
power_sensor.set_option(rs.option.power_line_frequency, 1)  # 50Hz电源模式

常见问题排查

设备连接问题

症状:无法检测到RealSense设备 解决方案

  1. 检查USB连接和供电情况
  2. 安装或更新udev规则:
sudo cp config/99-realsense-libusb.rules /etc/udev/rules.d/
sudo udevadm control --reload-rules && sudo udevadm trigger

性能下降问题

症状:帧率下降或数据延迟 解决方案

  1. 降低分辨率或帧率
  2. 关闭不必要的流
  3. 检查USB3.0端口连接状态

编译错误处理

症状:CMake配置或编译失败 解决方案

  1. 检查依赖项完整性
  2. 清除构建目录并重新配置:
cd build
rm -rf *
cmake .. -DBUILD_PYTHON_BINDINGS=ON
make -j$(nproc)

总结与扩展资源

通过本指南,您已掌握Intel RealSense深度摄像头的Python开发基础,包括环境配置、设备控制、数据采集和高级应用开发。项目提供了丰富的扩展资源:

  • 示例代码库:examples/python/目录包含20+实用示例
  • API文档:完整的Python API参考可在doc/api/python.md查阅
  • 社区支持:通过项目GitHub页面获取最新更新和问题解答

RealSense技术可广泛应用于三维重建、机器人导航、增强现实、工业检测等领域,结合Python生态系统的强大功能,为计算机视觉应用开发提供无限可能。

登录后查看全文
热门项目推荐
相关项目推荐