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

树莓派Zero W用Flask推流PiCamera提示资源不足求助

解决方案:树莓派Zero W Flask摄像头推流资源不足问题

1. 调整GPU内存分配

树莓派Zero W默认GPU内存分配通常为64MB,不足以支撑视频模式运行。修改配置提升GPU内存:

  • 执行命令:sudo nano /boot/config.txt
  • 找到gpu_mem配置项,修改为gpu_mem=128(Zero总内存512MB,分配128MB给GPU是合理范围,兼顾系统运行与摄像头需求)
  • 保存退出后重启设备:sudo reboot

2. 降低摄像头参数

640x480@24的分辨率和帧率对Zero W的硬件压力过大,下调参数减少资源占用:

camera.resolution = (320, 240)
camera.framerate = 15

3. 延迟摄像头初始化并自动释放资源

避免全局提前初始化摄像头占用资源,改为在生成器内初始化,并用with语句确保资源自动释放:
修改后的完整代码示例:

from flask import Flask, render_template, Response
import picamera
import time

app = Flask(__name__)

def gen():
    with picamera.PiCamera() as camera:
        camera.resolution = (320, 240)
        camera.framerate = 15
        time.sleep(2)  # 给摄像头足够预热时间
        while True:
            frame = camera.capture(format='jpeg', use_video_port=True)
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0')

4. 关闭Flask Debug模式

debug=True会启动额外的监控进程,占用宝贵的内存资源,改为debug=False运行可减少资源消耗。

5. 切换到Picamera2库

旧版picamera已停止维护,Picamera2对低资源设备优化更好,适配新系统:

  • 安装Picamera2:sudo apt install python3-picamera2 python3-pil
  • 简化版示例代码:
from flask import Flask, Response
from picamera2 import Picamera2
from PIL import Image
import io
import time

app = Flask(__name__)

def gen():
    picam2 = Picamera2()
    picam2.configure(picam2.create_video_configuration(main={"size": (320, 240), "format": "RGB888"}))
    picam2.start()
    time.sleep(2)
    while True:
        frame = picam2.capture_array()
        img = Image.fromarray(frame)
        buf = io.BytesIO()
        img.save(buf, format='JPEG')
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + buf.getvalue() + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return "<html><body><img src='/video_feed'></body></html>"

if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:53:09