RTSP流可打开但无法使用VideoWriter写入问题求助
解决OpenCV VideoWriter无法打开RTSP流推送到rtsp-simple-server的问题
常见原因及修复方案
1. OpenCV的RTSP推流依赖FFmpeg支持
OpenCV原生VideoWriter对RTSP推流的支持有限,必须确保你的OpenCV是带FFmpeg编译支持的。可以通过以下代码验证:
import cv2 print(cv2.getBuildInformation())
在输出中查找FFmpeg相关条目,确认状态为YES。如果是NO,需要重新编译OpenCV并启用FFmpeg选项。
2. 修正RTSP地址格式与推流参数
rtsp-simple-server接收推流时,需要明确指定传输协议等参数,直接使用rtsp://localhost:8554/stream1可能无法建立连接。建议修改地址并显式指定FFmpeg后端:
rtsp_address = "rtsp://localhost:8554/stream1?rtsp_transport=tcp" # 创建VideoWriter时指定FFmpeg后端 out = cv2.VideoWriter( rtsp_address, cv2.CAP_FFMPEG, fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))) )
3. 匹配摄像头真实参数与编码器
- 不要硬编码帧率和分辨率,直接从摄像头获取真实值:
fps = cap.get(cv2.CAP_PROP_FPS) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) - 尝试更换编码器,比如兼容性更好的
MJPG或需要FFmpeg支持的X264:fourcc = cv2.VideoWriter_fourcc(*"MJPG") # 或者 fourcc = cv2.VideoWriter_fourcc(*"X264")
4. 验证rtsp-simple-server可用性
- 查看rtsp-simple-server的运行日志,确认是否有推流连接的错误提示。
- 用FFmpeg命令直接推流测试,排除OpenCV的问题:
ffmpeg -f v4l2 -i /dev/video0 -c:v libx264 -f rtsp rtsp://localhost:8554/stream1
如果该命令能成功推流,说明问题出在OpenCV的配置上。
修复后的完整代码示例
import cv2 camera_index = 0 rtsp_address = "rtsp://localhost:8554/stream1?rtsp_transport=tcp" cap = cv2.VideoCapture(camera_index) if not cap.isOpened(): print("Failed to open camera") exit() # 获取摄像头真实参数 fps = cap.get(cv2.CAP_PROP_FPS) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 显式指定FFmpeg后端与X264编码器 fourcc = cv2.VideoWriter_fourcc(*"X264") out = cv2.VideoWriter( rtsp_address, cv2.CAP_FFMPEG, fourcc, fps if fps > 0 else 20.0, # 兼容帧率获取失败的情况 (width, height) ) if not out.isOpened(): print("Failed to open RTSP stream") exit() while True: ret, frame = cap.read() if not ret: print("Failed to capture frame") break out.write(frame) cv2.imshow("frame", frame) if cv2.waitKey(1) & 0xFF == ord("q"): break cap.release() out.release() cv2.destroyAllWindows()
内容的提问来源于stack exchange,提问作者tarnished
相关产品推荐
相关产品推荐

