使用Flask和Opencv在多个浏览器上同时获取摄像头监控信息

主要代码参考这里

Main部分

该部分主要编写了服务器的路由信息以及视频流的装配信息

#!/usr/bin/env python
from flask import Flask, render_template, Response
from camera_v3 import Camera
import cv2

app = Flask(__name__)

video_camera = None
global_frame = None

@app.route('/')
def index():
    return render_template('index.html')

def gen():
    global video_camera
    global global_frame
    # 如果当前的摄像头为空
    # 则新建一个类
    if video_camera is None:
        video_camera = Camera()
    while True:
        frame = video_camera.get_frame()
        # 如果当前摄像头能够获取到帧
        # 则正常输出帧,并更新global_frame 的信息
        # 如果不能正常输出,则输出global_frame的信息
        if frame is not None:
            global_frame = frame
            yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
        else:
            yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n')


@app.route('/video_feed')
def video_feed():
    return Response(gen(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True, threaded=True)

Camera部分

这部分更简单了,就是使用opencv来读取摄像头的每帧信息,然后转成bytes类型,最后输出的网页端

from time import time
import cv2
import numpy as np


class Camera(object):

    def __init__(self):
        self.cap = cv2.VideoCapture(0) 

    def __del__(self):
        self.cap.release()
    
    def get_frame(self):
        success, image = self.cap.read()
        # 如果成功读取,则正常传输bytes数据
        # 如读取失败,则返回None,即使用上一帧的数据
        if success:
            image = self.cal_flow(image)
            ret, jpeg = cv2.imencode('.jpg', image)
            return jpeg.tobytes()
        else:
            return None

猜你喜欢

转载自blog.csdn.net/ZeroSwift/article/details/115276553