简体   繁体   中英

Webcam Live Streaming using Flask

I want to access my webcams via a browser by multiple clients. I tried the following source code:

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

This works - except that threads are never stopped.. so if I refresh my browser or open further tabs accessing the stream, the number of threads will increase. I don't know where to call the stop function.. Can someone help me?

Best, Hanna

You have to add logic in your Flask code to stop the video stream thread (ie ). The logic can be implemented either by adding a web handler; or by adding a time-out logic to stop the generator (the " gen " function).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM