flask+python 实时视频流输出到前台

flask+python 实时视频流输出到前台

二、问题描述:

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

2。将视频流处理并传递给浏览器

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

4。 flash后台进行处理,而不是在前端处理

三、程序

1、后端处理程序

server.py

from flask import Flask, render_template, Response
import cv2
import time

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__)


@app.route('/')  # 主页
def index():
    # jinja2模板,具体格式保存在index.html文件中
    return render_template('index.html')


def gen(camera):
    while True:
        start_t=time.time()
        frame = camera.get_frame()
        #print('{0}'.format(time.time()-start_t))
        # 使用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)

2、前端html

templates/index.html

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

注:在py文件同目录下,新建一个templates,然后新建一个index.html的文件,将上面内容复制进去即可

四、运行结果展示在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_51116518/article/details/126804839
今日推荐