使用opencv训练LBP识别模型

import cv2
import os
import numpy as np


def detect_face(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 


    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
 
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);

    if (len(faces) == 0):
        return None, None
    else:
        (x, y, w, h) = faces[0]

    return gray[y:y+w, x:x+h], faces[0]
def prepare_training_data(data_folder_path):
    dirs = os.listdir(data_folder_path)  #读取存储在路径上的所有文件夹的名称
    faces=[]
    labels=[]
    for dir_name in dirs: #浏览每个目录并阅读其中的图像
        if not dir_name.startswith("s"):
            continue
        label = int(dir_name.replace("s", ""))
        subject_dir_path = data_folder_path + "/" + dir_name
        subject_images_names = os.listdir(subject_dir_path)
        for image_name in subject_images_names:
            if image_name.startswith("."):
                continue
            image_path = subject_dir_path + "/" + image_name
            image = cv2.imread(image_path)
            #face, rect = detect_face(image)
            face, rect = detect_face(image)
                 
            
            #cv2.imshow("Training on image...", face)
            #cv2.waitKey(100)
            
            if face is not None:
                faces.append(face)
                labels.append(label)


    return faces, labels


    
print("正在准备数据")
faces, labels = prepare_training_data("s")
#faces, labels = prepare_training_data("dataset")
print("数据完成,准备训练数据")
 
#print total faces and labels
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))




#create our LBPH face recognizer 
#face_recognizer = cv2.face.createLBPHFaceRecognizer()






recognizer = cv2.face.LBPHFaceRecognizer_create()
#recognizer = cv2.face.EigenFaceRecognizer_create()
#recognizer = cv2.face.FisherFaceRecognizer_create()




 
#or use EigenFaceRecognizer by replacing above line with 
#face_recognizer = cv2.face.createEigenFaceRecognizer()
 
#or use FisherFaceRecognizer by replacing above line with 
#face_recognizer = cv2.face.createFisherFaceRecognizer()


recognizer.train(faces, np.array(labels))
recognizer.write('lihao.yml')   #定义生成文件的名称
print('数据训练完成')

你可能感兴趣的:(人脸识别)