网络摄像头直播使用Flask

时间:2016-06-15 14:04:16

标签: python flask http-live-streaming mjpeg

我想通过多个客户端的浏览器访问我的网络摄像头。我尝试了以下源代码:

main.py:

#!/usr/bin/env python
from flask import Flask, render_template, Response

# emulated camera
from webcamvideostream import WebcamVideoStream

import cv2

app = Flask(__name__, template_folder='C:\coding\streamingserver\templates')

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('streaming.html')


def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.read()
        ret, jpeg = cv2.imencode('.jpg', frame)

        # print("after get_frame")
        if jpeg is not None:
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n')
        else:
            print("frame is none")



@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(WebcamVideoStream().start()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5010, debug=True, threaded=True)

webcamvideostream.py:

# import the necessary packages
from threading import Thread
import cv2

class WebcamVideoStream:

    def __init__(self, src=0):
        # initialize the video camera stream and read the first frame
        # from the stream
        print("init")
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()

        # initialize the variable used to indicate if the thread should
        # be stopped
        self.stopped = False


    def start(self):
        print("start thread")
        # start the thread to read frames from the video stream
        t = Thread(target=self.update, args=())
        t.daemon = True
        t.start()
        return self

    def update(self):
        print("read")
        # keep looping infinitely until the thread is stopped
        while True:
            # if the thread indicator variable is set, stop the thread
            if self.stopped:
                return


            # otherwise, read the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        # return the frame most recently read
        return self.frame

    def stop(self):
        # indicate that the thread should be stopped
        self.stopped = True

这是有效的 - 除了线程永远不会停止..因此,如果我刷新浏览器或打开访问流的更多选项卡,线程数将增加。 我不知道在哪里叫停止功能.. 有人能帮助我吗?

最佳, 汉娜

1 个答案:

答案 0 :(得分:0)

您必须在Flask代码中添加逻辑以停止视频流线程(即)。逻辑可以通过添加Web处理程序来实现;或者通过添加超时逻辑来停止生成器(“gen”功能)。

def gen(camera):
"""Video streaming generator function."""
while True:
    if camera.stopped:
         break
    frame = camera.read()
    ...