Python3 OpenCV调用Gstreamer无法打开Flir Hadron相机求助
问题解决:Python+OpenCV+GStreamer无法打开Flir Hadron相机
核心问题分析
你遇到的Cannot open camera错误,主要源于输入GStreamer管线格式不匹配、OpenCV与GStreamer后端的参数冲突,同时输出管线也存在格式不兼容问题。
分步解决方案
1. 修复输入相机管线(camset)
- 移除
cam.set()的分辨率、帧率设置:使用GStreamer后端时,OpenCV的CAP_PROP_FRAME_WIDTH等属性会被管线自身参数覆盖,甚至引发冲突,直接删除这三行即可。 - 转换为OpenCV兼容格式:Flir相机输出UYVY格式,需转成OpenCV默认的BGR格式才能被
appsink正确接收,修改后的管线如下:
camset='v4l2src io-mode=4 device=/dev/video0 do-timestamp=true ! video/x-raw,format=UYVY,width=1920,height=1080,framerate=30/1 ! queue ! nvvidconv ! video/x-raw,format=BGRx ! videoconvert ! video/x-raw,format=BGR ! appsink drop=true sync=false'
新增的video/x-raw,format=BGRx ! videoconvert ! video/x-raw,format=BGR确保输出为OpenCV支持的BGR格式,appsink添加drop=true sync=false提升稳定性。
2. 修复视频保存管线(gst_str)
- 匹配输入帧格式:OpenCV读取的帧是BGR格式,因此
appsrc的格式要改为BGR,而非原有的UYVY。 - 正确调用GStreamer后端:创建
VideoWriter时,需指定cv2.CAP_GSTREAMER作为后端,同时fourcc参数设为0(GStreamer管线已指定编码器,fourcc在此无效)。修改后的管线与代码:
gst_str = 'appsrc ! video/x-raw,format=BGR,width=1920,height=1080,framerate=30/1 ! queue ! nvvidconv ! nvv4l2h265enc maxperf-enable=1 preset-level=4 control-rate=1 bitrate=16000000 ! h265parse ! qtmux ! filesink location=streaming.mp4 sync=false' out = cv2.VideoWriter(gst_str, cv2.CAP_GSTREAMER, 0, fps, (frame_width, frame_height), True)
3. 完整修改后的代码
import cv2 fps = 30 frame_width = 1920 frame_height = 1080 # 修复后的输入管线 camset = 'v4l2src io-mode=4 device=/dev/video0 do-timestamp=true ! video/x-raw,format=UYVY,width=1920,height=1080,framerate=30/1 ! queue ! nvvidconv ! video/x-raw,format=BGRx ! videoconvert ! video/x-raw,format=BGR ! appsink drop=true sync=false' cam = cv2.VideoCapture(camset, cv2.CAP_GSTREAMER) if not cam.isOpened(): print("Cannot open camera. Exiting.") quit() # 修复后的输出管线 gst_str = 'appsrc ! video/x-raw,format=BGR,width=1920,height=1080,framerate=30/1 ! queue ! nvvidconv ! nvv4l2h265enc maxperf-enable=1 preset-level=4 control-rate=1 bitrate=16000000 ! h265parse ! qtmux ! filesink location=streaming.mp4 sync=false' # 正确指定GStreamer后端,fourcc设为0 out = cv2.VideoWriter(gst_str, cv2.CAP_GSTREAMER, 0, fps, (frame_width, frame_height), True) while True: ret, frame = cam.read() if not ret: print("Failed to read frame.") break cv2.imshow('camera', frame) out.write(frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # 资源释放 cam.release() out.release() cv2.destroyAllWindows()
额外注意事项
- 验证OpenCV编译配置:执行
print(cv2.getBuildInformation()),确认输出中GStreamer: YES,确保OpenCV已集成GStreamer。 - 检查设备权限:若命令行可用但Python报错,可尝试
sudo python3 your_script.py测试,或把用户加入video组:sudo usermod -aG video $USER(需重启生效)。
内容的提问来源于stack exchange,提问作者Ihssane Oubari
相关产品推荐
相关产品推荐

