Face Recognition OpenCV Python

Cài đặt thư viện cho máy tính của bạn :

- pip install opencv-python
- pip install numpy
- pip install image

Source Code Nhận diện khuôn mặt python : 

File train.py

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


recognizer = cv2.face.LBPHFaceRecognizer_create()
#nếu máy bạn chạy không được dòng lệnh này thì xem ghi chú bên file detector.py

cascadePath = "Classifiers/myface.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
path = 'dataSet'

def get_images_and_labels(path):
     image_paths = [os.path.join(path, f) for f in os.listdir(path)]
     # hình ảnh sẽ chứa khuôn mặt
     images = []
    
     labels = []
     for image_path in image_paths:
         # Đọc hình ảnh và chuyển đổi sang thang độ xám
         image_pil = Image.open(image_path).convert('L')
         # Chuyển đổi định dạng hình ảnh thành mảng numpy
         image = np.array(image_pil, 'uint8')
         
         nbr = int(os.path.split(image_path)[1].split(".")[0].replace("face-", ""))
         
         print (nbr)
         # Phát hiện khuôn mặt trong ảnh
         faces = faceCascade.detectMultiScale(image)
         
         for (x, y, w, h) in faces:
             images.append(image[y: y + h, x: x + w])
             labels.append(nbr)
             cv2.imshow("Adding faces to traning set...", image[y: y + h, x: x + w])
             cv2.waitKey(10)
     
     return images, labels


images, labels = get_images_and_labels(path)
cv2.imshow('test',images[0])
cv2.waitKey(1)

recognizer.train(images, np.array(labels))
recognizer.save('trainer/trainer_KhaiTK.yml')
cv2.destroyAllWindows()




File FaceRecognition.py:

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


fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))


recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')

#ở đây cv2.face.LBPHFaceRecognizer_create() nếu máy bạn chạy không được nên chuyển sang dòng cv2.createLBPHFaceRecognizer()



#recognizer = cv2.createLBPHFaceRecognizer()
#recognizer.load('trainer/trainer.yml')


cascadePath = "Classifiers/face.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
path = 'dataSet'

id = 0
names = ["None", "K_TK"]

cam = cv2.VideoCapture(0)
font =cv2.FONT_HERSHEY_SIMPLEX
while True:
    ret, im =cam.read()
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE)
    for(x,y,w,h) in faces:
        id, confidence  = recognizer.predict(gray[y:y+h,x:x+w])
        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2)

        if(confidence < 100):
            
            id = names[id]
            confidence = "  {0}%".format(round(100 - confidence))
            #print("Khải Tk")
        else:
            id = "Unknown"
            confidence = "  {0}%".format(round(100 - confidence))

            
        cv2.putText(im, str(id), (x + 5, y - 5), font, 1, (255, 255, 255), 2)
        cv2.putText(im, str(confidence), (x + 5, y + h - 5), font, 1, (255, 255, 0), 1)
        
        
    out.write(im)

    cv2.imshow('im',im)
    cv2.waitKey(10)
cap.release()
out.release()
cv2.destroyAllWindows()


- Chúc các bạn thành công !


Kết quả khi xuất ra video:






















Previous Post Next Post