You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派4(Bookworm系统)OpenCV调用Pi Camera无法接收帧问题

树莓派Bookworm系统OpenCV无法识别Pi Camera v1的解决方法

问题描述

使用搭载Raspberry Pi OS Bookworm(VERSION="12")的Raspberry Pi 4,搭配Raspberry Pi Camera Rev1.3,运行OpenCV视频采集代码时出现Can't receive frame错误,无法访问Pi Camera;但切换为USB摄像头时代码可正常运行。

测试代码

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    # if frame is read correctly ret is True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # Our operations on the frame come here
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

已尝试操作

  • 代码搭配USB摄像头可正常运行
  • 在/boot/config.txt或/boot/firmware/config.txt中添加dtoverlay=ov5647配置
  • 更换同型号全新摄像头,排除硬件及连接故障
  • 终端执行libcamera-hello命令可正常启动摄像头
  • 网页测试仅能检测到USB摄像头,无法识别Pi Camera v1

解决方案

方案1:使用GStreamer管道调用libcamera

Bookworm默认采用libcamera栈,Pi Camera不会直接生成/dev/video节点,需通过GStreamer桥接。修改代码中摄像头初始化部分:

import numpy as np
import cv2 as cv

# 适配Pi Camera v1(ov5647)的GStreamer管道,可自行调整分辨率/帧率
cap = cv.VideoCapture(
    'libcamerasrc ! video/x-raw,width=640,height=480,framerate=30/1 ! videoconvert ! appsink',
    cv.CAP_GSTREAMER
)

if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    ret, frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    cv.imshow('frame', gray)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()

注:通过sudo apt install python3-opencv安装的OpenCV已包含GStreamer支持,无需自行编译。

方案2:启用V4L2兼容节点

让libcamera模拟传统V4L2设备节点,步骤如下:

  1. 编辑/boot/firmware/config.txt,添加以下配置(若已有重复项可覆盖):
    dtoverlay=vc4-kms-v3d,cma-512
    start_x=1
    gpu_mem=128
    
  2. 重启树莓派后,执行命令启动摄像头并生成V4L2节点:
    libcamera-vid -n -t 0 --inline
    
  3. 此时系统会创建/dev/video0节点,原OpenCV代码可直接使用cv.VideoCapture(0)访问Pi Camera。

原因说明

Raspberry Pi OS Bookworm弃用了传统的MMAL摄像头框架,默认采用libcamera栈,Pi Camera不再直接暴露为V4L2设备节点。OpenCV默认的VideoCapture(0)只会查找V4L2节点,因此无法识别Pi Camera。通过上述两种方式,可实现OpenCV与libcamera栈的兼容。

内容的提问来源于stack exchange,提问作者Sameer Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:12:46