Use Flask and Opencv to simultaneously obtain camera monitoring information on multiple browsers

The main code reference here

Main section

This part mainly compiles the routing information of the server and the assembly information of the video stream

#!/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 section

This part is even simpler, that is, use opencv to read each frame of the camera information, and then convert it to bytes, and finally output the web page.

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

Guess you like

Origin blog.csdn.net/ZeroSwift/article/details/115276553