Face recognition based on Python -- code sharing of graduation project

Brief introduction

This code is divided into three parts:

  1. Face input module: input it before recognition. Input it here
  2. Face recognition module: after entering, the recognition is finished
  3. Common function module: take down the common modules in modules 1 and 2 and put them together

Anecdotes outside the code (anecdote)

I typed the code line by line seriously, and the instructor knew it. She thought I could really evaluate an excellent graduation thesis. (the teacher gave me 93 points)
But in the final reply, ah, I was angry.
Those teachers just don't care about the graduation project with the technical content of "face recognition". Whether I use an external database or my own database, no matter how I modify it line by line, no matter how I optimize the logical structure.
In short, when I improved my skills, the defense team thought I copied it. When the technology was low, the defense team said, "so you think you have too little workload, don't you? Huh?"
Me: "???"
Anyway, in a word: you are 8 lines.
——Although the answer is to find problems, they didn't find any technical problems, only the magic index of "too little workload"...
Now when I think of it, hahaha, I can only say that I have a master's degree and strive to study for a doctor. It doesn't matter, it doesn't matter
Oh, oh, add a little more, this is the most interesting:
During the mid-term defense, I used the external face database. The defense team said, you don't have your own face database. Is it of practical value?
When I finally checked, I used my own face database. The defense team said, you don't have an external database. How can you prove that your code works?
Fuck? You're looking for trouble, aren't you? Do you need it? (hahaha)

Code on!!!

1. Face entry

 import common_function as cf
import cv2
import os
import sys
import numpy
MAX = 10  #Set the number of photos saved

def set_save_path(save_path):#Set the path to save the picture
    return save_path
save_path = set_save_path("C:/imgs")

def save():#Main function
        #Get the name of the face to save
        name = get_name()
        #Save picture
        save_pic(save_path,name)
        
def save_pic(filepath,name):        #This code saves 1 person's MAX face
    num_face = 0 # Flag to stop the cycle
    cap = cv2.VideoCapture(0)#Turn on the camera
    print("The camera has been opened, please switch to the camera interface")
    print("When taking more photos (such as more than 100), please make sure that your face is always in the camera")
    while cap.isOpened():
        if  num_face > 0:#After the first person is finished, it's over (only one person at a time)
            print("common"+(str)(MAX)+"A picture,"+"Finished shooting")
            cv2.destroyWindow("take pictures")
            cv2.destroyAllWindows()
            return True
        ret,pic =cap.read()
        cv2.putText(pic,"press 'Enter' to take pictures or 'Esc' to exit",
                    (25,25),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.75,
                    (0,0,255),2)
        cv2.namedWindow("take pictures")#Create photo window
        cv2.imshow("take pictures",pic)
        flag = cv2.waitKey(1)
        gray = pic #Save photos
        #(in fact, you don't need to save it as a grayscale image,
        #   Because it can be read in grayscale image format)
        if flag == 27:#ESC
            cv2.destroyWindow("take prictures")
            cv2.destroyAllWindows()
            print("exit!")
            sys.exit(0)
        elif flag == 13:#ENTER
            num_pic=0    
            while num_pic < MAX:#Capture and save MAX personal face photos
                ret,pic =cap.read()
                gray = pic
                face = cf.face_model_cas.detectMultiScale(gray,#Face detection
                                           scaleFactor = 1.2,
                                           minNeighbors = 3,
                                           minSize = (128,128))                     #Returns [[x,y,w,h]]
                x,y,w,h = face[0]
                image = gray[y : y + h , x : x + w ]#intercept
                cv2.imwrite(filepath+"/"+name+"_"+(str)(num_pic)+".jpg",image)#Save
                #Save a photo + 1
                num_pic+=1              
                #Draw a rectangular box
                face = cf.face_model_cas.detectMultiScale(gray,#return [[x,y,w,h]]
                                           scaleFactor = 1.2,
                                           minNeighbors = 3,
                                           minSize = (128,128))
                x,y,w,h=face[0]
                cv2.rectangle(pic, (x - 10, y - 10), (x + w + 10, y + h + 10), (255,0,0), 2)               
                #Displays how many face images are currently captured
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(pic,'num:%d' % (num_pic),(x + 30, y + 30), font, 1, (255,0,255),4)                
                cv2.imshow("take pictures",pic)
                cv2.waitKey(1)
        else :#If you do not ENTER ESC or ENTER, continue the cycle
            continue
        num_face+=1#End cycle
        
def get_name():#Read saved name
    print("Please enter a saved name(English only,Otherwise, something will go wrong)")
    name = input()
    cv2.namedWindow("take pictures")
    return name
    
if __name__ == '__main__':
    try:
        #Call the save function to save the picture
        save()
        #Call the training module and train the picture
        cf.train(cf.set_fp(save_path),
                    cf.set_yml_path("C:/feature_victor/train.yml"))
    except(IndexError):
        print("IndexError!!!")
        print("The face does not completely enter the camera, please run again")
    except(BaseException):
        print("An exception occurred")

If there is anything you don't understand, you'd better check it yourself first. You will gain a lot after understanding it.
But if you really don't understand, please leave a message!

2. Face recognition

import cv2
import os
import numpy
import common_function as cf
import sys
import save
fp = "C:/imgs/"#Picture address
yml_path ="C:/feature_victor/train.yml"#Training file address

labels_name = cf.get_name(fp) 
labels_number = cf.get_number(fp,labels_name) 
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read(yml_path)

def get_num_of_name():#Get the number of people
    name_num_array = []
    len_of_name = len(labels_name)
    j = 0
    while j < len_of_name:
        count = 0
        for i in labels_number:
            if i == j:
                count +=1
            elif i > j:
                break
        j+=1
        name_num_array.append(count)
    return  name_num_array
def add_img(add_name,save_img):#New database
    if add_name in labels_name:
        count=0
        for name in labels_name:
            count+=1
            if name == add_name:
                cv2.imwrite(fp+"/"+add_name+"_"+(str)(get_num_of_name()[count-1])+".jpg",save_img)
    else:
        cv2.imwrite(fp+"/"+add_name+"_0.jpg",save_img)
        
def face_recog():#Main function
        shoot_img = cf.catch_pic()
        gray = cf.bgr2gray(shoot_img)
        gray = cv2.equalizeHist(gray)
        face = cf.face_model_cas.detectMultiScale(gray,
                                                  scaleFactor = 1.2,
                                                   minNeighbors = 3,
                                                   minSize = (128,128))
        face = face[0]
        print("Find face")
        x,y,w,h = face
        shoot_img = shoot_img[y  : y + h ,x  : x + w ]
        gray = cv2.equalizeHist(cf.bgr2gray(shoot_img))
        label,confidence= recognizer.predict(gray)
        print("name = ",labels_name[label])
        print("confidence = ",confidence,"(Smaller means more similar)")
        #optimization
        print("Is this identification correct? y/n/q")
        while 1 :
            flag = input()
            if flag == "y":
                add_img(labels_name[label],shoot_img)
                break
            elif flag == "n":
                print("Please enter the name of the person identified this time:")
                add_name = input()
                add_img(add_name,shoot_img)
                break
            elif flag == "q":
                sys.exit(0)
            else:
                print("The letter you entered is incorrect. Please re-enter it:y/n")
        cf.train(fp,yml_path)
        
if __name__ == "__main__":#For testing
    try:
        face_recog()
    except(IndexError):
        print("The face does not completely enter the camera, please run again")
        print("The exception type is: IndexError!")
    except(BaseException):
        print("An exception occurred")
        print("The exception type is: BaseException!")

3. Common function module

import cv2
import numpy
import os
import sys
path="C://Users//dongdong//AppData//Roaming//Python//Python39//site-packages//cv2//data//haarcascade_frontalface_alt.xml"
face_model_cas=cv2.CascadeClassifier(path)

#Take a picture and return
def catch_pic():
    cap = cv2.VideoCapture(0)
    print("The camera has been opened, please switch to the camera interface")
    while cap.isOpened():
        ret, frame = cap.read(5)
        cv2.namedWindow("face recognition")#Create photo window
        cv2.putText(frame,"press 'Enter' to take pictures or 'Esc' to exit",
                    (25,25),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.75,
                    (0,0,255),2)
        faces = face_model_cas.detectMultiScale(frame,#return [[x,y,w,h]]
                                               scaleFactor = 1.2,
                                               minNeighbors = 3,
                                               minSize = (128,128))
        for face in faces:
            #x,y,w,h=face[0]
            x,y,w,h=face
            cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), (255,0,0), 2)
            #cv2.rectangle(frame, (x , y ), (x + w , y + h), (0,255,0), 2)               
            cv2.imshow('face recognition', frame)
            flag = cv2.waitKey(1)
            if flag == 27:#Press ESC to push out    
                print('The system failed to obtain photos, end the identification system')
                print("Will throw BaseException abnormal~")
                cap.release()
                cv2.destroyAllWindows()
                sys.exit(0)
            elif flag == 13:#Press enter to take pictures
                print('The system has obtained photos and is ready for processing')
                cap.release()
                cv2.destroyAllWindows()          
                return frame
                
#Convert picture from BGR to RGB
def bgr2rgb(img):
    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
#Convert the picture from BGR to grayscale (grayscale ≠ black and white)
def bgr2gray(img):
    return cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#--------------------------------------------------------------------------------
face_imgs = []
labels_name = []
labels_number = []  #name ->number,1 for 1

def set_fp(fp_set):#Set the path to save the yml file
    fp = fp_set
    return  fp
    
def get_imgpaths(filepath):#Get the file address of jpg pictures and remove the addresses of other types of files or folders
    imgpaths = []
    imgpaths_temp =  [os.path.join(filepath,f) for f in os.listdir(filepath)]
    for imgpath in imgpaths_temp:
        if  imgpath.endswith(".jpg"):
            imgpaths.append(imgpath)
    return imgpaths
    
def get_name(filepath):#Gets the name and returns the saved array
    imgpaths = get_imgpaths(filepath)
    name_temp = []
    for imgpath in imgpaths:
        if  imgpath.endswith(".jpg"):  #If the path has files other than. jpg, skip
            name = os.path.split(imgpath)[1].split(".")[0].split("_")[0]
            #print(name)
            if name not in name_temp:
                name_temp.append(name)
        else:
            continue
    return name_temp
    
def get_number(filepath,labels_name):#Different people are saved in the array with different integers for training
    imgpaths =  get_imgpaths(filepath)
    number_temp = []
    name_number = 0
    for label_name in labels_name:
        for imgpath in imgpaths:
            name = os.path.split(imgpath)[1].split(".")[0].split("_")[0]
            if name == label_name :
                number_temp.append(name_number)
        name_number+=1
    return number_temp
    
def get_img(filepath):#Get the picture and save it as an array of pictures
    img_temp = []
    imgpaths =  get_imgpaths(filepath)
    for imgpath in imgpaths:
        #Histogram equalization processing is added
        #Histogram equalization itself already has brightness equalization
        img_temp.append(cv2.equalizeHist(cv2.imread(imgpath,cv2.IMREAD_GRAYSCALE)))
    return img_temp
    
def set_yml_path(yml_path):#Set the save path of the training file
    return yml_path
    
def train(filepath,yml_path):#Main function
    labels_name = get_name(filepath) #right
    labels_number = get_number(filepath,labels_name) #right
    face_imgs = get_img(filepath)   #right
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.train(face_imgs, numpy.array(labels_number))
    recognizer.write(yml_path)
    print("Training complete!")
    print("Training files have been successfully saved in:"+yml_path)
    
if __name__ == "__main__":#For testing
    train(set_fp("C:/imgs"),set_yml_path("C:/feature_victor/train.yml"))

Keywords: Python AI face recognition

Added by littlevisuals on Sat, 02 Oct 2021 05:03:09 +0300