【问题标题】:PiCamera Flask, start and stop previewPiCamera Flask,开始和停止预览
【发布时间】:2016-06-12 18:26:47
【问题描述】:

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

这是我的观点的一部分。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 repo 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.exc.PiCameraMMALError:无法启用相机组件:资源不足(内存除外)
  • 在烧瓶中尝试另一个网络摄像头流式传输。它以替代方法实现。 github.com/36rahu/webcam_streaming_flask

标签: python flask raspberry-pi


【解决方案1】:

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

要停止摄像头,您必须让方法 _thread 中的后台线程退出,其方式类似于在 10 秒不活动后退出。

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

希望这会有所帮助!

【讨论】:

  • 嗨米格尔,感谢您的回复。我已经修改了上面的 camera_pi.py,现在按照您的建议包含了一个 stop_camera 变量,但是现在我收到了一个回溯错误,其中指出:ValueError:查看函数没有返回响应。此外,虽然这会停止相机,但我也希望能够在不刷新整个页面的情况下重新加载预览,停止和启动相机是实现这一目标的最佳方式,还是我能够停止并启动预览不知何故?
  • view function did not return a response 错误无关。你所有的 Flask 路由都必须返回一个响应,即使它是一个空字符串。您在其中一条路线中遗漏了这一点,我猜您添加的路线是为了停止相机。要重新启动相机,只需添加另一个启动新后台线程的路由。
  • 嗨 Miguel,我仍在努力解决这个问题。请您提供一些代码示例吗?
  • @RyanKowalewski 我没有任何现成的东西,我有的是我在博客文章和 GitHub 存储库中写的东西。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
相关资源
最近更新 更多