乐趣区

关于flask:flaskpython-实时视频流输出到前台

问题形容:

1。调用摄像头获取视频流

2。将视频流解决并传递给浏览器

3。不是录制后处理,而是边录制边解决,边传递

4。flash 后盾进行解决,而不是在前端解决

问题解决:

办法起源:外汇名词解释 https://www.fx61.com/definitions

server.py

from flask import Flask, render_template, Responseimport cv2 class VideoCamera(object):    def __init__(self):        # 通过 opencv 获取实时视频流        self.video = cv2.VideoCapture(0)         def __del__(self):        self.video.release()        def get_frame(self):        success, image = self.video.read()        # 在这里解决视频帧        cv2.putText(image, "hello",(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(0, 255, 0))        # 因为 opencv 读取的图片并非 jpeg 格局,因而要用 motion JPEG 模式须要先将图片转码成 jpg 格局图片        ret, jpeg = cv2.imencode('.jpg', image)        return jpeg.tobytes() app = Flask(__name__,static_folder='./static') @app.route('/')  # 主页 def index():    # jinja2 模板,具体格局保留在 index.html 文件中    return render_template('index.html') def gen(camera):    while True:        frame = camera.get_frame()        # 应用 generator 函数输入视频流,每次申请输入的 content 类型是 image/jpeg        yield (b'--frame\r\n'               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @app.route('/video_feed')  # 这个地址返回视频流响应 def video_feed():    return Response(gen(VideoCamera()),                    mimetype='multipart/x-mixed-replace; boundary=frame')    if __name__ == '__main__':    app.run(host='0.0.0.0', debug=True, port=5000)  

index.html

<html>  <head>    <title>Video Streaming Demonstration</title>  </head>  <body>    <h1>Video Streaming Demonstration</h1>    <img src="{{url_for('video_feed') }}">  </body></html>

运行:python server.py
而后就能够在浏览器中看到解决后的视频流了。

退出移动版