python less than 100 lines of code to complete face recognition

Keywords: Python OpenCV pip xml

1. Preparation environment

  • python 3.5
  • opencv

2. Configuration environment

pip install opencv-python
pip install numpy
pip install opencv-contrib-python

3. Prepare training data

  • 20 photos of Tong Liya, stored under folder 0
  • 20 photos of Dong Xuan, stored under folder 1

4. Prepare test data

  • One photo of Tong Liya, named 0.jpg, saved in the test directory
  • One picture of Dong Xuan, named 1.jpg, saved in the test directory

5. code

import cv2
import os
import numpy as np
#Mapping of tag and person name
Label2Name = ["tongliya", "dongxuan"]
def DetectFace(img):
    #Convert the test image to grayscale image, because opencv face detector needs grayscale image
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #Load the OpenCV face detection classifier Haar, which is located in the python installation directory, for example: D: \ Python 3.5.0 \ lib \ site packages \ CV2 \ data
    Hear_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
    #To detect multi-scale image, the return value is a list of facial region information (x,y, width, height)
    faces = Hear_cascade.detectMultiScale(img_gray, scaleFactor=1.2, minNeighbors=5)
    # If no face is detected, the original image is returned
    if (len(faces) == 0):
        return None, None
    #At present, it is assumed that there is only one face, xy is the coordinate of the upper left corner, wh is the width and height of the rectangle
    (x, y, w, h) = faces[0]
    #Back to the front of the image
    return img_gray[y:y + w, x:x + h], faces[0]
#This function will read all training images, detect faces from each image and return two lists of the same size, namely face information and label
def Train(TrainDataDir):
    # Get directory in data folder
    dirs = os.listdir(TrainDataDir)
    # Define two lists, faces is used to store face data, labels is used to store tags: 0 - Tong Liya, 1 - Dong Xuan
    faces = []
    labels = []
    # Browse each directory and access the images in it
    for dir_name in dirs:
        # Get absolute path of picture
        imgs_path = TrainDataDir + "/" + dir_name
        # Get the absolute path of all pictures
        img_names = os.listdir(imgs_path)
        # Read each picture and detect the face, and store the face information in faces
        for img_name in img_names:
            # Absolute path of single picture
            img_path = imgs_path + "/" + img_name
            # Read image
            img = cv2.imread(img_path)
            # Display image 0.2s
            cv2.imshow("image", img)
            cv2.waitKey(200)
            # Face detection
            face, rect = DetectFace(img)
            # If face cannot be obtained, ignore
            if face is not None:
                #Add face to face list
                faces.append(face)
                #Add appropriate Tags
                labels.append(int(dir_name))
                cv2.waitKey(1)
                cv2.destroyAllWindows()
    #Return value face information and corresponding Tags
    return faces, labels
#Draw a rectangle on the face of the picture
def DrawRectangle(img, rect):
    (x, y, w, h) = rect
    cv2.rectangle(img, (x, y), (x + w, y + h), (128, 128, 0), 2)
#Draw the person name above the given picture rectangle
def DrawText(img, text, x, y):
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
#Recognition image
def Recognize(test_img):
    # Copy pictures, draw rectangles and text on the newly copied pictures
    img_copy = test_img.copy()
    # Face detection
    face, rect = DetectFace(img_copy)
    # Predictive face
    label = face_recognizer.predict(face)
    # Get the name of the corresponding tag returned by the face recognizer
    label_text = Label2Name[label[0]]
    # Draw a rectangle around the detected face
    DrawRectangle(img_copy, rect)
    # Name the forecast
    DrawText(img_copy, label_text, rect[0], rect[1] - 5)
    #Return the predicted image
    return img_copy
#Training
faces, labels = Train("F:\\Codes\\Python\\train_data")
#Create LBPH recognizer and start training
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.train(faces, np.array(labels))
# Read the image to be recognized
test_img1 = cv2.imread("F:\\Codes\\Python\\test\\0.jpg")
test_img2 = cv2.imread("F:\\Codes\\Python\\test\\1.jpg")
# Distinguish
recognize_img1 = Recognize(test_img1)
recognize_img2 = Recognize(test_img2)
#Show two images
cv2.imshow(Label2Name[0], recognize_img1)
cv2.imshow(Label2Name[1], recognize_img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

6. Identification results

 

 

75 original articles published, 89 praised, 150000 visitors+
Private letter follow

Posted by phence on Mon, 03 Feb 2020 09:58:46 -0800