树莓派4外接罗技USB相机运行picamera代码报错求助
树莓派外接USB相机报错解决方案
问题说明
树莓派4 Model B外接罗技USB相机,参照教程运行基于picamera库的Python代码时,出现picamera.exc.PiCameraMMALError和picamera.exc.PiCameraError报错。已通过sudo raspi-config启用相机功能,但问题仍未解决。
运行代码
from picamera import PiCamera import time print("= = = = = == = = = ") camera = PiCamera() camera.start_preview() time.sleep(2) camera.capture("test.jpg")
报错信息
mmal: mmal_vc_component_create: failed to create component 'vc.ril.camera' (1:ENOMEM) mmal: mmal_component_create_core: could not create component 'vc.ril.camera' (1) Traceback (most recent call last): File "/usr/lib/python3/dist-packages/picamera/camera.py", line 456, in _init_camera self._camera = mo.MMALCamera() File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 2279, in __init__ super(MMALCamera, self).__init__() File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 631, in __init__ mmal_check( File "/usr/lib/python3/dist-packages/picamera/exc.py", line 184, in mmal_check raise PiCameraMMALError(status, prefix) picamera.exc.PiCameraMMALError: Failed to create MMAL component b'vc.ril.camera': Out of memory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/joy/Desktop/camera.py", line 6, in <module> camera = PiCamera() File "/usr/lib/python3/dist-packages/picamera/camera.py", line 431, in __init__ self._init_camera(camera_num, stereo_mode, stereo_decimate) File "/usr/lib/python3/dist-packages/picamera/camera.py", line 459, in _init_camera raise PiCameraError( picamera.exc.PiCameraError: Camera is not enabled. Try running 'sudo raspi-config' and ensure that the camera has been enabled.
核心原因
picamera库是专门为树莓派官方CSI接口相机开发的,依赖树莓派的MMAL硬件加速框架,不支持外接USB相机。报错提示的内存不足是框架无法识别USB相机导致的误导性信息,实际问题是库与设备不兼容。
解决方法
方法1:使用命令行工具fswebcam(简单快速)
- 先安装工具:
sudo apt update && sudo apt install fswebcam - 执行拍照命令(分辨率可自行调整):
fswebcam -r 1280x720 --no-banner test.jpg
方法2:使用Python的OpenCV库(适合编程场景)
- 安装OpenCV依赖:
sudo apt update && sudo apt install python3-opencv - 替换为以下兼容USB相机的Python代码:
import cv2 import time # 打开第一个USB相机(参数0对应系统识别的第一个USB视频设备) cap = cv2.VideoCapture(0) # 等待相机完成初始化 time.sleep(2) # 捕获图像 ret, frame = cap.read() if ret: cv2.imwrite("test.jpg", frame) print("照片已保存为test.jpg") else: print("无法捕获图像,请检查相机连接") # 释放相机资源 cap.release()
内容的提问来源于stack exchange,提问作者j ton
相关产品推荐
相关产品推荐

