当前位置:网站首页>Face detection, training and recognition based on OpenCV

Face detection, training and recognition based on OpenCV

2022-06-09 03:53:00 Mike Zhou, exclusive musician of Netease

be based on OpenCV Face detection 、 Training 、 distinguish

The system uses Harr Cascade detection and LPBH Face detection and training 、 distinguish


import cv2
#import time

cam = cv2.VideoCapture(0)


classifier = cv2.CascadeClassifier('./cascade/haarcascade_frontalface_alt2.xml')

# For each person, enter one numeric face id
face_input_id = input('\n enter user id end press <return> ==> ')

while(True):

    img = cv2.flip(cam.read()[1],1)
# img = cv2.flip(img, -1) # flip video image vertically
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(32, 32))
    if len(faces):
        x,y,w,h = faces[0]
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)  
# if time.time()-save_time > 0.2:
# cv2.imwrite("dataset/" + str(face_input_id) +"."+str(count)+ ".jpg", gray[y:y+h,x:x+w])
# count += 1
# save_time = time.time()
    
    cv2.imshow('image', img)

    if cv2.waitKey(10) == 27:   #  adopt esc Press the key to exit the camera 
        if len(faces):
            cv2.imwrite("dataset/" + str(face_input_id) + ".jpg", gray[y:y+h,x:x+w])
        else:
            print(" Failed to intercept face ")
        break
# elif count >= 50: # Take 30 face sample and stop video
# break


cam.release()
cv2.destroyAllWindows()




import cv2
import numpy as np
from PIL import Image
import os

# Path for face image database
path = 'dataset'

recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("./cascade/haarcascade_frontalface_alt2.xml")

# function to get the images and label data
def getImagesAndLabels(path):

    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []
    if len(imagePaths):
        for imagePath in imagePaths:
            PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
            img_numpy = np.array(PIL_img,'uint8')
            face_training_id = int(os.path.split(imagePath)[-1].split(".")[0])   
            faceSamples.append(img_numpy)
            ids.append(face_training_id)

    return faceSamples,ids

print (" Training ")
faces,ids = getImagesAndLabels(path)
if faces == [] or ids == []:
    print("None")
else:
    recognizer.train(faces, np.array(ids))
    
    # Save the model into trainer/trainer.yml
    recognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
    
    # Print the numer of faces trained and end program
    print(" common "+str(len(np.unique(ids)))+" Data ")


import cv2
import time


recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "./cascade/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

font = cv2.FONT_HERSHEY_SIMPLEX

face_output_id = 0
face_1st_flag=0

# names related to ids: example ==> Marcelo: id=1, etc
names = ['None', 'yangxu', 'zhoulaoshi', 'liuqian', 'hekun', ] 

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)

while True:

    img = cv2.flip(cam.read()[1],1)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(32, 32))
    if len(faces):
        for(x,y,w,h) in faces:
            cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
            face_output_id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
            real_confidence = int(100-confidence)
            if (real_confidence > 50):
                face_name = str(names[face_output_id])
                face_confidence = str(real_confidence)+"%"
                if face_1st_flag == 0:
                    face_1st_flag = 1
                    face_1st_id = face_output_id
                    face_1st_time = time.time()
                else:
                    if 2.1 > time.time() - face_1st_time > 2.0 :
                        if face_output_id == face_1st_id:
                            print(" Recognition success : "+str(face_output_id)+" "+face_name)
                        face_1st_flag = 0
                    if time.time() - face_1st_time > 2.1:
                        print(" Please keep stable ")
                        face_1st_flag = 0

            else:
                face_name = "Unknown"
                face_confidence = str(real_confidence)+"%"

            cv2.putText(img, str(face_name), (x+5,y-5), font, 1, (255,255,255), 2)
            cv2.putText(img, str(face_confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  

    cv2.imshow('camera',img) 

    if cv2.waitKey(10) == 27:
        break


cam.release()
cv2.destroyAllWindows()

原网站

版权声明
本文为[Mike Zhou, exclusive musician of Netease]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090344170187.html