2
複数のクライアントからブラウザ経由でウェブカメラにアクセスしたいのですが、私は、次のソースコードを試してみました:ウェブカメラ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
この作品 - スレッドが停止されることはありませんことを除いて...だから、私は、ブラウザをリフレッシュした場合またはストリームにアクセスする他のタブを開くと、スレッド数が増加します。 私はどこで停止機能を呼び出すかわかりません。 誰かが私を助けることができますか?
ベスト、あなたがビデオストリームのスレッド(つまり)を停止するようにフラスコのコード内のロジックを追加する必要が ハンナ