需要下载相应的库:
pip install cmake
pip install dlib
import os
import cv2
import dlib
import numpy as np
from keras.models import load_model
detector=dlib.get_frontal_face_detector()
#第二个参数表示捕获的图像分辨率
cap=cv2.VideoCapture(0,cv2.CAP_DSHOW)
margin=0.2
#设置显示的字体
font=cv2.FONT_HERSHEY_SIMPLEX
model=load_model('./models/recognition.h5')
labels={0:'cabbage',1:'car',2:'dog',3:'mobilePhone',4:'person'}
while True:
OK,frame=cap.read()
if OK==False:
print('请面对摄像头!')
break
img_h,img_w,_=np.shape(frame)
detected=detector(frame)
faces=[]
preprocess_images=[]
if len(detected)>0:
for i,locate in enumerate(detected):
x1,y1,x2,y2,w,h=locate.left(),locate.top(),locate.right()+1,locate.bottom()+1,locate.width(),locate.height()
xw1=max(int(x1-margin*w),0)
yw1=max(int(y1-margin*h),0)
xw2=min(int(x2+margin*w),img_w-1)
yw2=min(int(y2+margin*h),img_h-1)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
face=frame[yw1:yw2+1,xw1:xw2+1,:]
face=cv2.resize(face,(128,128))
face=face.astype('float')/255.0
face=np.expand_dims(face,axis=0)
preprocess_images.append(face)
for i,d in enumerate(detected):
preds=model.predict(preprocess_images[i])[0]
face_labels=labels[preds.argmax()]
cv2.putText(frame,face_labels,(d.left(),d.top()-10),font,1.2,(255,0,0),3)
cv2.imshow('face',frame)
if cv2.waitKey(1)&0xFF==27:
break
cap.release()
cv2.destroyAllWindows()