树莓派4上OpenCV调用摄像头返回(False,None)问题求助
问题
树莓派4上使用Raspberry Pi Camera Module 3,运行OpenCV代码时,cap.read()返回(False, None)。摄像头能通过控制台的libcamera正常拍照和录像,OpenCV 4.5.1编译信息显示FFmpeg已启用,排查内核后问题依旧。
测试代码
import numpy as np import cv2 as cv cap = cv.VideoCapture(cv.CAP_V4L) cap.set(cv.CAP_PROP_FRAME_WIDTH,640) cap.set(cv.CAP_PROP_FRAME_HEIGHT,480) cap.set(cv.CAP_PROP_FPS,40) if not cap.isOpened(): print("Cannot open camera") exit() while cap.isOpened(): # Capture frame-by-frame ret, frame = cap.read() # if frame is read correctly ret is True if not ret: print(frame) print("Problems reading frames") break
OpenCV编译信息
General configuration for OpenCV 4.5.1 ===================================== Version control: unknown Extra modules: Location (extra): /build/opencv-EaEjAq/opencv-4.5.1+dfsg/contrib/modules Version control (extra): unknown Platform: Timestamp: 2021-06-16T12:09:47Z Host: Linux 4.9.0-0.bpo.6-armmp armv7l CMake: 3.18.4 CMake generator: Ninja CMake build tool: /usr/bin/ninja Configuration: Release CPU/HW features: Baseline: requested: DETECT C/C++: Built as dynamic libs?: YES C++ standard: 11 C++ Compiler: /usr/bin/c++ (ver 10.2.1) C++ flags (Release): -g -O2 -ffile-prefix-map=/build/opencv-EaEjAq/opencv-4.5.1+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O2 -ffile-prefix-map=/build/opencv-EaEjAq/opencv-4.5.1+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG C++ flags (Debug): -g -O2 -ffile-prefix-map=/build/opencv-EaEjAq/opencv-4.5.1+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wsuggest-override -Wno-delete-non-virtual-dtor -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -DDEBUG -D_DEBUG C Compiler: /usr/bin/cc C flags (Release): -g -O2 -ffile-prefix-map=/build/opencv-EaEjAq/opencv-4.5.1+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -fvisibility=hidden -g -O2 -ffile-prefix-map=/build/opencv-EaEjAq/opencv-4.5.1+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG C flags (Debug): -g -O2 -ffile-prefix-map=/build/opencv-EaEjAq/opencv-4.5.1+dfsg=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fsigned-char -W -Wall -Werror=return-type -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wuninitialized -Wno-comment -Wimplicit-fallthrough=3 -Wno-strict-overflow -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fdata-sections -fvisibility=hidden -g -DDEBUG -D_DEBUG Linker flags (Release): -Wl,-z,relro -Wl,-z,now -Wl,--gc-sections -Wl,--as-needed -Wl,-z,relro -Wl,-z,now Linker flags (Debug): -Wl,-z,relro -Wl,-z,now -Wl,--gc-sections -Wl,--as-needed ccache: NO Precompiled headers: NO Extra dependencies: dl m pthread rt 3rdparty dependencies: OpenCV modules: To be built: alphamat aruco bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy hdf hfs highgui img_hash imgcodecs imgproc intensity_transform java line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking video videoio videostab viz ximgproc xobjdetect xphoto Disabled: world Disabled by dependency: sfm Unavailable: cnn_3dobj cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv gapi julia matlab ovis python2 ts Applications: apps Documentation: doxygen python javadoc Non-free algorithms: NO GUI: GTK+: YES (ver 3.24.24) GThread : YES (ver 2.66.8) GtkGlExt: NO OpenGL support: NO VTK support: YES (ver 9.0.1) Media I/O: ZLib: /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.11) JPEG: /usr/lib/arm-linux-gnueabihf/libjpeg.so (ver 62) WEBP: /usr/lib/arm-linux-gnueabihf/libwebp.so (ver encoder: 0x020e) PNG: /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.6.37) TIFF: /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 / 4.2.0) JPEG 2000: OpenJPEG (ver 2.4.0) OpenEXR: /usr/lib/arm-linux-gnueabihf/libImath-2_5.so /usr/lib/arm-linux-gnueabihf/libIlmImf-2_5.so /usr/lib/arm-linux-gnueabihf/libIex-2_5.so /usr/lib/arm-linux-gnueabihf/libHalf-2_5.so /usr/lib/arm-linux-gnueabihf/libIlmThread-2_5.so (ver 2_5) GDAL: YES (/usr/lib/libgdal.so) GDCM: YES (3.0.8) HDR: YES SUNRASTER: YES PXM: YES PFM: YES Video I/O: DC1394: YES (2.2.6) FFMPEG: YES avcodec: YES (58.91.100) avformat: YES (58.45.100) avutil: YES (56.51.100) swscale: YES (5.7.100) avresample: NO GStreamer: YES (1.18.4) PvAPI: NO v4l/v4l2: YES (linux/videodev2.h) gPhoto2: YES Parallel framework: TBB (ver 2020.3 interface 11103) Trace: YES (built-in) Other third-party libraries: Lapack: NO Eigen: YES (ver 3.3.9) Custom HAL: NO Protobuf: /usr/lib/arm-linux-gnueabihf/libprotobuf.so (3.12.4) OpenCL: YES (no extra features) Include path: /usr/include/CL Link libraries: Dynamic load Python 3: Interpreter: /usr/bin/python3 (ver 3.9.2) Libraries: /usr/lib/arm-linux-gnueabihf/libpython3.9.so (ver 3.9.2) numpy: /usr/lib/python3/dist-packages/numpy/core/include (ver 1.19.5) install path: lib/python3.9/dist-packages Python (for build): /usr/bin/python3 Java: ant: /usr/bin/ant (ver 1.10.9) JNI: /usr/lib/jvm/default-java/include /usr/lib/jvm/default-java/include/linux /usr/lib/jvm/default-java/include Java wrappers: YES Java tests: NO Install to: /usr -----------------------------------------------------------------
解决建议
指定V4L2设备路径并调整后端参数:直接指定摄像头设备路径,同时添加
CAP_V4L2后端标识,替换原初始化代码:cap = cv.VideoCapture(0, cv.CAP_V4L2) # 或者指定完整路径 cap = cv.VideoCapture('/dev/video0', cv.CAP_V4L2)部分情况下,树莓派的摄像头可能映射到
/dev/video10等路径,可通过ls /dev/video*命令查看所有视频设备。使用GStreamer后端替代V4L:从编译信息看OpenCV已启用GStreamer,尝试用GStreamer管道初始化摄像头,适配Raspberry Pi Camera Module 3的格式:
gst_pipeline = 'v4l2src device=/dev/video0 ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! appsink' cap = cv.VideoCapture(gst_pipeline, cv.CAP_GSTREAMER)注意将帧率调整为摄像头实际支持的参数,可通过
libcamera-still --list-cameras查看摄像头支持的分辨率和帧率。检查并调整分辨率与帧率匹配:Raspberry Pi Camera Module 3可能不支持640x480@40fps的组合,先尝试降低帧率到30,或者使用摄像头原生支持的分辨率(比如1280x720),设置参数前先打印当前实际生效的参数:
cap = cv.VideoCapture(0, cv.CAP_V4L2) print("实际宽度:", cap.get(cv.CAP_PROP_FRAME_WIDTH)) print("实际高度:", cap.get(cv.CAP_PROP_FRAME_HEIGHT)) print("实际帧率:", cap.get(cv.CAP_PROP_FPS))验证V4L2设备可用性:通过
v4l2-ctl --list-formats-ext命令查看摄像头支持的所有格式、分辨率和帧率,确保OpenCV设置的参数在列表内。如果没有v4l2-ctl,先安装sudo apt install v4l-utils。检查权限问题:确保当前用户属于
video组,执行sudo usermod -aG video $USER,然后重新登录生效。重新编译OpenCV时添加树莓派摄像头支持:如果上述方法无效,重新编译OpenCV时需添加针对树莓派的编译选项,比如:
cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D WITH_V4L=ON \ -D WITH_GSTREAMER=ON \ -D WITH_LIBV4L=ON \ -D BUILD_opencv_python3=ON \ -D OPENCV_ENABLE_NONFREE=OFF \ -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules \ ..编译前确保安装了所有依赖:
sudo apt install build-essential cmake git libjpeg-dev libpng-dev libtiff-dev libv4l-dev libxvidcore-dev libx264-dev libgtk-3-dev libatlas-base-dev gfortran python3-dev
内容的提问来源于stack exchange,提问作者Magolves

