局部二值模式直方图(LBPH)建立人脸识别系统。在数据集中,可以看到分歧的人。构建一个能将每小我从其他人中区分出来的系统。
1、起首建立一个Python文件,并导入库文件:
import os
import cv2 import numpy as np from sklearn import preprocessing
2、界说一个类来处置与类标签编码相关的所有使命:
# 将单词转换当作数字的编码方式
def encode_labels(self, label_words): self.le = preprocessing.LabelEncoder() self.le.fit(label_words)
# 将单词转换当作数字的方式:
def word_to_num(self, label_word): return int(self.le.transform([label_word])[0])
# 将数字转换当作单词
def num_to_word(self, label_num): return self.le.inverse_transform([label_num])[0]
3、界说一个方式,用于输入文件夹中提取图像和标签:
def get_images_and_labels(input_path): label_words = [] # 对输入文件夹做递归迭代并追加文件 for root, dirs, files in os.walk(input_path): for filename in (x for x in files if x.endswith('.jpg')): filepath = os.path.join(root, filename) label_words.append(filepath.split('\\')[-2]) # 初始化变量 images = [] le = LabelEncoder() le.encode_labels(label_words) labels = [] # 解析输入目次 for root, dirs, files in os.walk(input_path): for filename in (x for x in files if x.endswith('.jpg')): filepath = os.path.join(root, filename) # 将当前图像读取当作灰度格局 image = cv2.imread(filepath, 0) # 从文件夹路径中提取标签 name = filepath.split('\\')[-2] # 做人脸检测 faces = faceCascade.detectMultiScale(image, 1.1, 2, minSize=(100, 100)) # 轮回处置每一张脸
# 提取ROI属性值,并将这些值和标签编码器返回: for (x, y, w, h) in faces: images.append(image[y:y + h, x:x + w]) labels.append(le.word_to_num(name)) return images, labels, le
4、界说main函数,并界说人脸级联文件的路径:
if __name__ == '__main__': cascade_path = "cascade_files/haarcascade_frontalface_alt.xml" path_train = 'faces_dataset/train' path_test = 'faces_dataset/test'
# 加载人脸级联文件
faceCascade = cv2.CascadeClassifier(cascade_path)
# 生当作局部二值模式直方图人脸识别器对象:
recognizer = cv2.face.createLBPHFaceRecognizer()
5、为输入路径提取图像、标签和标签编码器,并续联人脸识别器:
# 从练习数据集中提取图像、标签和标签编码器 images, labels, le = get_images_and_labels(path_train) # 练习人脸识别器 print("\nTraining...") recognizer.train(images, np.array(labels))
6、用未知数据测试人脸识别器:
print('\nPerforming prediction on test images...')
stop_flag = False
for root, dirs, files in os.walk(path_test):
for filename in (x for x in files if x.endswith('.jpg')):
filepath = os.path.join(root, filename)
# 读取图像
predict_image = cv2.imread(filepath, 0)
# 检测人脸
faces = faceCascade.detectMultiScale(predict_image, 1.1, 2, minSize=(100, 100))
7、提取ROI属性值,并将这些值和标签编码器返回:
# 轮回处置每一张脸
for (x, y, w, h) in faces:
# 展望输出
predicted_index, conf = recognizer.predict( predict_image[y:y + h, x:x + w])
# 将标签转换为单词
predicted_person = le.num_to_word(predicted_index)
# 输出图像中叠加文字 并显示图像
cv2.putText(predict_image, 'Prediction:' +\
predicted_person, (10,60),cv2.FONT_HER SHEY_SIMPLEX, 2, (255, 255, 255), 6)
cv2.imshow("Recognizing face", predict_image)
c=cv2.waitKey(0)
if c==27: stop_flag=True break
if stop_flag:
break
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!