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

树莓派4相机资源占用报错:如何释放被占用的相机设备?

树莓派4相机被占用问题的解决方法及代码修正

一、释放被占用的相机资源

1. 定位占用相机的进程

执行以下命令查找正在使用相机设备的进程:

lsof /dev/video0

(若连接多个相机,设备名可能为video1,可根据实际情况调整)

也可以筛选相机相关进程:

ps aux | grep camera

2. 强制终止占用进程

从输出中找到目标进程的PID(进程ID),执行命令强制终止:

kill -9 <PID>

将<PID>替换为实际进程编号。

3. 禁用自动占用相机的系统服务

树莓派部分默认服务会自动占用相机,可停止并禁用:

# 停止相机应用服务
sudo systemctl stop camera-app
# 禁止开机自动启动
sudo systemctl disable camera-app

4. 重置相机驱动(极端情况)

若上述方法无效,可重新加载相机驱动:

sudo rmmod bcm2835_v4l2
sudo modprobe bcm2835_v4l2

或直接重启树莓派:

sudo reboot

二、修正你的Python代码错误

原代码存在变量名不一致、API使用错误等问题,即使释放相机也无法正常运行,修正后的代码如下:

import io 
from picamera2 import Picamera2
from flask import Flask, Response
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput

app = Flask(__name__)

def gen_frames():
    picam2 = Picamera2()
    # 配置相机分辨率与输出格式
    config = picam2.create_video_configuration(main={"size": (640, 480)}, lores={"size": (640, 480)}, display="lores")
    picam2.configure(config)
    
    stream = io.BytesIO()
    encoder = JpegEncoder()
    output = FileOutput(stream)
    
    picam2.start_recording(encoder, output)
    try:
        while True:
            stream.seek(0)
            yield b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + stream.read() + b'\r\n'
            stream.seek(0)
            stream.truncate()
    finally:
        picam2.stop_recording()

@app.route("/v")
def videofeed():
    return Response(gen_frames(), mimetype="multipart/x-mixed-replace; boundary=frame")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, threaded=True)

关键修正说明:

  • 统一相机实例变量名,避免kamera与camera混用的错误
  • 使用Picamera2官方推荐的视频录制流程,配置JPEG编码器与流输出
  • 优化流的读写逻辑,确保每一帧数据正确生成

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:22:51