Skip to main content
 首页 » 编程设计

python之PiCamera Flask,开始和停止预览

2025年04月02日12leader

我正在 Flask 中创建一个小网络界面,以使用 PiCamera python 模块控制 Raspberry Pi 相机。我有一个工作索引页面,它显示来自相机的流。但是,当我通过输入按钮 POST stop_preview() 时,应用程序失败,我无法弄清楚我做错了什么。到目前为止,这是我的一些代码。

这是我的views.py的一部分

from flask import redirect, url_for, session, request, \ 
             render_template, Response 
from simplepam import authenticate 
from app.camera_pi import Camera 
from app import app 
 
 
@app.route('/', methods=['GET', 'POST']) 
@app.route('/index',  methods=['GET', 'POST']) 
def index(): 
    if request.method == 'POST': 
        if request.form['submit']: 
            Camera.StopPreview() 
    elif request.method == 'GET': 
        return render_template("index.html", title="Home") 
 
 
def gen(camera): 
    """Video streaming generator function.""" 
    while True: 
        frame = camera.get_frame() 
        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(): 
    """Video streaming route. Put this in the src attribute of an img tag.""" 
    return Response(gen(Camera()), 
                    mimetype='multipart/x-mixed-replace; boundary=frame') 

这是我的 index.html 模板。

<!DOCTYPE html> 
 
 
 <html> 
      <head> 
      </head> 
      <body> 
        <img id="video_feed" src="{{ url_for('video_feed') }}"> 
        <form method="post"> 
          <p><input type="submit" name="submit" value="StopPreview"></p> 
        </form> 
      </body> 
    </html> 

这是 camera_pi.py 文件(取自 Miguel Grinberg 的 github 存储库 https://github.com/miguelgrinberg/flask-video-streaming)

# The MIT License (MIT) 
# 
# Copyright (c) 2014 Miguel Grinberg 
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy 
# of this software and associated documentation files (the "Software"), to deal 
# in the Software without restriction, including without limitation the rights 
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
# copies of the Software, and to permit persons to whom the Software is 
# furnished to do so, subject to the following conditions: 
# 
# The above copyright notice and this permission notice shall be included in 
# all copies or substantial portions of the Software. 
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
# SOFTWARE. 
 
 
import time 
import io 
import threading 
import picamera 
from app import camera_config 
 
 
class Camera(object): 
    thread = None  # background thread that reads frames from camera 
    frame = None  # current frame is stored here by background thread 
    last_access = 0  # time of last client access to the camera 
    stop_camera = False 
 
    def initialize(self): 
        if Camera.thread is None: 
            # start background frame thread 
            Camera.thread = threading.Thread(target=self._thread) 
            Camera.thread.start() 
 
            # wait until frames start to be available 
            while self.frame is None: 
                time.sleep(0) 
 
    def get_frame(self): 
        Camera.last_access = time.time() 
        self.initialize() 
        return self.frame 
 
    def StopPreview(): 
        Camera.stop_camera = True 
 
    @classmethod 
    def _thread(cls): 
        with picamera.PiCamera() as camera: 
            # camera setup 
            camera.resolution = camera_config.camera_resolution 
 
            # let camera warm up 
            camera.start_preview() 
            time.sleep(2) 
 
            stream = io.BytesIO() 
            for foo in camera.capture_continuous(stream, 'jpeg', 
                                                 use_video_port=True): 
                # store frame 
                stream.seek(0) 
                cls.frame = stream.read() 
 
                # reset stream for next frame 
                stream.seek(0) 
                stream.truncate() 
 
                # if there hasn't been any clients asking for frames in 
                # the last 10 seconds stop the thread 
                if time.time() - cls.last_access > 10: 
                    break 
                elif Camera.stop_camera is True: 
                    break 
        cls.thread = None 

我已经添加了“def StopPreview()”部分,当我从索引页面发布提交按钮时它被调用,但应用程序此时崩溃了。

在此先感谢您提供的任何帮助。

请您参考如下方法:

首先,picamera 的start_preview 和stop_preview 方法只是开始和停止预览,也就是在Pi 自己的显示器上出现的叠加视频。这些方法不会启动或停止相机本身。

要停止相机,您必须让 _thread 方法中的后台线程退出,其方式与 10 秒不活动时间后退出的方式类似。

例如,您可以向对象添加一个 stop_camera 变量,用 False 初始化。在您的停止方法中,您只需将变量翻转为 True 并返回。然后在后台线程中,根据该变量的值在检查 10 秒不活动的条件中添加第二个条件。

希望这对您有所帮助!