欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

OpenCV进行人脸识别

时间:2023-08-21

需要下载相应的库:
pip install cmake
pip install dlib

import osimport cv2import dlibimport numpy as npfrom keras.models import load_modeldetector=dlib.get_frontal_face_detector()#第二个参数表示捕获的图像分辨率cap=cv2.VideoCapture(0,cv2.CAP_DSHOW)margin=0.2#设置显示的字体font=cv2.FONT_HERSHEY_SIMPLEXmodel=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: breakcap.release()cv2.destroyAllWindows()

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。