目录
1.环境
1.python: 3.6.6 [64bit]
2.python packages:
1). opencv-python==3.4.1.15
2). opencv-contrib-python==4.4.0.42
3). sklearn==0.0
3.python包下载安装出错,可以尝试一下方式:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn <+python包>
4.探测器 Haar级联文件下载:
https://github.com/opencv/opencv/tree/master/data
2.描述
1.文件目录结构:
project:
----image_photograph # 人脸图片文件夹
|----lihua # 名字叫lihua的多张人脸图片
|----xiaoming # 名字叫xiaoming的多张人脸图片
|----zhangfei # 名字叫zhangfei的多张人脸图片
----facefeatures # 存储人脸特征的文件夹
----haarcascade # 人脸探测器的haar级联文件
----main.py # 主程序
2.流程:
(1).获取每一张图片路径,对应id名字(文件夹作为名字)
(2).将每张图片的人脸部分采集出来
(3).id名字进行标签编码处理LabelEncoder
(4).局部二值模式直方图创建人脸识别器
(5).训练人脸识别器
(5).将所有人脸特征与名字信息写入到yml文件中
注意:以后需要用到yml文件时,如果图片名字要与原来一致,还需要原图片名字作为标签解码用
(代码最后return就是名字列表)
3.代码
"""处理类标签编码"""
class LabelEncoder(object):
def __init__(self):
self.le = preprocessing.LabelEncoder()
def encode_labels(self, label_words):
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]
"""采集人脸信息生成yml"""
class FaceFeatures:
def __init__(self, photo_path):
self.face_cascade = cv2.CascadeClassifier('haarcascade\\haarcascade_frontalface_alt.xml')
self.data_transformation = LabelEncoder()
self.photo_path = photo_path
self.information = None
"""获取所有图片路径,存储图片的父文件夹名字"""
def get_images_information(self):
images = []
information = []
for root, dirs, files in os.walk(self.photo_path):
root = root.replace("/", "\\")
for filename in [x for x in files if x.endswith(".jpg")]:
images.append(os.path.join(os.getcwd(), root, filename))
information.append(root.split('\\')[-1])
self.data_transformation.encode_labels(information)
self.information = information
return images, information
"""采集所有人脸信息,名字标签编码处理"""
def get_features(self, images, information):
face_images_info = []
face_name_info = []
for num in range(len(images)):
ret = cv2.imread(images[num], 0)
faces = self.face_cascade.detectMultiScale(ret, 1.1, 2, minSize=(100, 100))
for (x, y, w, h) in faces:
face_images_info.append(ret[y:y + h, x:x + w])
face_name_info.append(self.data_transformation.word_to_num(information[num]))
return face_images_info, face_name_info
"""人脸信息录入yml文件, 返回图片对应的名字"""
def info_enter(self):
recognizer = cv2.face.LBPHFaceRecognizer_create()
images, information = self.get_images_information()
face_images_info, face_name_info = self.get_features(images, information)
recognizer.train(face_images_info, np.array(face_name_info))
recognizer.write("facefeatures/trainer.yml")
return self.information
if __name__ == '__main__':
FaceFeatures(os.path.join(os.getcwd(), "image_photograph")).info_enter()