老物搬运。
画面比在Linux桌面运行的流畅很多,也许是Opencv的cv2.imshow()会不断产生新窗口导致的卡顿,因为我关不掉窗口,它会一直产生新的。

Camera.py

#coding=utf-8
import cv2
class Camera():
    def __init__(self,Camera_id):
        self.video = cv2.VideoCapture(Camera_id)
        self.face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
    def __del__(self):
        self.video.release()
    def get_img(self):
        success,image = self.video.read()
        gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
        faces = self.face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x,y,w,h) in faces:
            cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
        ret,jpeg = cv2.imencode('.jpg', image) #将image对象转为jpeg格式
        return jpeg.tobytes() #转字节

main.py

from flask import Flask,Response
from Camera import Camera
app = Flask(__name__)
@app.route('/')
def index():
    return '<h3 style="text-align:center"><img src="/video" width="60%"></h3>'

def Video_stream(camera):
    while True:
        img = camera.get_img()
        yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + img + b'\r\n\r\n') #生成器

@app.route('/video')
def video():
    return Response(Video_stream(Camera(0)), mimetype='multipart/x-mixed-replace; boundary=frame') #合成响应,返回一个自定义标头和图片数据

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=80)

标签: Python, Flask, OpenCV

添加新评论