使用OpenCV调用RealSense D415相机无法正常保存视频文件
问题分析与修正方案
核心错误点
- RealSense Pipeline 配置顺序错误:你先启动了
pipeline,之后才定义流配置,导致配置完全不生效,相机默认流参数可能和预期不符。 - 重复初始化资源:外层
while True循环内每次都重新创建cv2.VideoCapture(3)和VideoWriter,会不断覆盖视频文件,且重复打开相机造成资源浪费。 - 帧数据未实时更新:内层循环始终写入外层单次获取的
color_image,没有在内层循环中实时获取新的RealSense帧,导致所有写入内容都是同一帧。 - 相机源混淆:你同时调用RealSense Pipeline和
cv2.VideoCapture(3),如果目标是录制D415的画面,完全不需要额外打开USB相机,属于逻辑冗余。 - 资源未释放:无退出逻辑,也未在结束时释放Pipeline、VideoWriter等资源,可能导致视频文件损坏。
修正后的代码
import pyrealsense2 as rs import numpy as np import cv2 from datetime import datetime # 初始化并配置RealSense Pipeline pipeline = rs.pipeline() config = rs.config() # 配置彩色流:640x360分辨率,BGR格式,30fps config.enable_stream(rs.stream.color, 640, 360, rs.format.bgr8, 30) # 启动Pipeline profile = pipeline.start(config) # 获取彩色流的实际尺寸 color_profile = profile.get_stream(rs.stream.color).as_video_stream_profile() frame_width = color_profile.get_intrinsics().width frame_height = color_profile.get_intrinsics().height frame_size = (frame_width, frame_height) # 生成带时间戳的视频文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") video_path = f"{timestamp}_camera.avi" # 初始化视频写入器 fourcc = cv2.VideoWriter_fourcc(*'MJPG') video_writer = cv2.VideoWriter(video_path, fourcc, 10, frame_size) try: while True: # 获取RealSense帧 frames = pipeline.wait_for_frames() color_frame = frames.get_color_frame() if not color_frame: continue # 转换为可处理的numpy数组 color_image = np.asanyarray(color_frame.get_data()) # 写入最新帧到视频文件 video_writer.write(color_image) # 实时显示画面 cv2.imshow("D415 Camera", color_image) # 按Q键退出录制 if cv2.waitKey(1) & 0xFF == ord('q'): break finally: # 释放所有资源,保证视频文件正常保存 pipeline.stop() video_writer.release() cv2.destroyAllWindows()
修正说明
- 调整Pipeline启动顺序:先配置流参数再启动,确保配置生效。
- 资源初始化移至循环外:避免重复创建相机和写入器,防止文件被覆盖。
- 实时更新帧数据:在循环内持续获取新的RealSense帧,保证录制内容是动态画面。
- 移除冗余相机调用:直接使用RealSense的帧作为录制源,简化逻辑。
- 添加退出与资源释放:通过Q键触发退出,在
finally块中释放所有资源,避免文件损坏。 - 时间戳文件名:自动生成带时间的文件名,避免文件覆盖。
内容的提问来源于stack exchange,提问作者Qstudent
相关产品推荐
相关产品推荐

