当前位置:网站首页>Opencv for face recognition

Opencv for face recognition

2022-06-11 07:46:00 Keep_ Trying_ Go

Corresponding libraries need to be downloaded :
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()
# The second parameter represents the resolution of the captured image 
cap=cv2.VideoCapture(0,cv2.CAP_DSHOW)

margin=0.2
# Set the font displayed 
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(' Please face the camera !')
        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()


原网站

版权声明
本文为[Keep_ Trying_ Go]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020518291754.html