Python 使用Flask的网络摄像头实时流媒体
我想通过多个客户端通过浏览器访问我的网络摄像头。我尝试了以下源代码: main.py:Python 使用Flask的网络摄像头实时流媒体,python,flask,http-live-streaming,mjpeg,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\stre
#!/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
这是可行的-除了线程从未停止。。因此,如果我刷新浏览器或打开更多访问流的选项卡,线程数量将增加。
我不知道在哪里调用停止函数。。
有人能帮我吗
最好的,
Hanna您必须在Flask代码中添加逻辑以停止视频流线程(即)。逻辑可以通过添加web处理程序来实现;或者通过添加超时逻辑来停止发电机(“代码>发电机”功能)
def gen(camera):
"""Video streaming generator function."""
while True:
if camera.stopped:
break
frame = camera.read()
...