2016-06-15 8 views
2

Я хочу получить доступ к своим веб-камерам через браузер несколькими клиентами. Я попытался следующий исходный код:Веб-камера Live Streaming с использованием Flask

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 

Это работает - за исключением того, что потоки никогда не остановился .. так что если я обновить свой браузер или открыть дополнительные вкладки, обращенные к потоку, количество потоков будет увеличиваться. Я не знаю, где вызвать функцию остановки. Может кто-нибудь мне помочь?

Бест, Ханна

ответ

0

Вы должны добавить логику в коде Колба, чтобы остановить видеопотока нить (то есть). Логику можно реализовать либо путем добавления веб-обработчика; или путем добавления логики тайм-аута для остановки генератора (функция «gen»).

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