我目前正在尝试使用网络摄像头使用Python设置面部识别程序。我已经在Python中设置了用于面部识别的代码,并且可以工作,但是我想通过Flask在HTML上流式传输视频(具有面部识别功能)。
当前,使用OpenCV面部识别显示流的代码为:
faces.py
import numpy as np
import cv2
import pickle
face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt2.xml')
eye_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_smile.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("./recognizers/face-trainner.yml")
labels = {"person_name": 1}
with open("pickles/face-labels.pickle", 'rb') as f:
og_labels = pickle.load(f)
labels = {v:k for k,v in og_labels.items()}
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)
for (x, y, w, h) in faces:
#print(x,y,w,h)
roi_gray = gray[y:y+h, x:x+w] #(ycord_start, ycord_end)
roi_color = frame[y:y+h, x:x+w]
# recognize? deep learned model predict keras tensorflow pytorch scikit learn
id_, conf = recognizer.predict(roi_gray)
if conf>=4 and conf <= 85:
#print(5: #id_)
#print(labels[id_])
font = cv2.FONT_HERSHEY_SIMPLEX
name = labels[id_]
color = (255, 255, 255)
stroke = 2
cv2.putText(frame, name, (x,y), font, 1, color, stroke, cv2.LINE_AA)
img_item = "8.png"
cv2.imwrite(img_item, roi_color)
color = (255, 0, 0) #BGR 0-255
stroke = 2
end_cord_x = x + w
end_cord_y = y + h
cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke)
#subitems = smile_cascade.detectMultiScale(roi_gray)
#for (ex,ey,ew,eh) in subitems:
# cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
这是我的Flask代码: stream.py
#!/usr/bin/env python
from flask import Flask, render_template, Response
import cv2
import sys
import numpy
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen():
i=1
while i<10:
yield (b'--frame\r\n'
b'Content-Type: text/plain\r\n\r\n'+str(i)+b'\r\n')
i+=1
def get_frame():
camera_port=0
ramp_frames=100
camera=cv2.VideoCapture(camera_port) #this makes a web cam object
i=1
while True:
retval, im = camera.read()
imgencode=cv2.imencode('.jpg',im)[1]
stringData=imgencode.tostring()
yield (b'--frame\r\n'
b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n')
i+=1
del(camera)
@app.route('/calc')
def calc():
return Response(get_frame(),mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='localhost', debug=True, threaded=True)
我的目标是在我的flask程序上流式传输我的OpenCV面部识别程序(运行stream.py后可以在HTML中显示)。