使用dilb实现人脸检测、识别
使用dlib实现人脸检测与识别需要先下载以下两个文件:
以下是检测代码:
import dlib import numpy as np import cv2 detector = dlib.get_frontal_face_detector() # 加载正脸检测器,使用dlib sp = dlib.shape_predictor("dlibModel/shape_predictor_68_face_landmarks.dat") # 加载人脸关键点检测模型 facerec = dlib.face_recognition_model_v1("dlibModel/dlib_face_recognition_resnet_model_v1.dat") # 加载人脸识别模型 images_file = "11.jpg" if __name__ == '__main__': image = cv2.imread(images_file) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) rects = detector(gray, 1) # 返回人脸,(灰度图,采样次数) tzs = [] for (i, rect) in enumerate(rects): shape68 = sp(image, rect) # 返回68个特征点 face_descriptor = facerec.compute_face_descriptor(image, shape68) # 计算人脸的128维的向量 tz = np.array(face_descriptor) # 人脸特征值 tzs.append(tz) for p in shape68.parts(): cv2.circle(image, (p.x, p.y), 2, (0, 0, 255), 1) cv2.rectangle(image, (rect.left(), rect.top()), (rect.right(), rect.bottom()), (0, 255, 0), 2) print(tzs) cv2.imshow("Output", image) cv2.waitKey(-1)
原图
效果图
打印的特征值:
[array([-0.14579333, 0.06563152, 0.09314926, -0.17351562, -0.08750948, -0.03944254, -0.05778341, -0.16003576, 0.18947695, -0.20229495, 0.22666875, -0.09615702, -0.15724032, -0.00979816, -0.02177811, 0.23944741, -0.21378906, -0.12338841, -0.04015261, 0.00419115, 0.07516268, 0.08075333, 0.01858632, 0.07583004, -0.1436058 , -0.33890599, -0.10919157, -0.05613485, -0.01440384, -0.0421476 , -0.02769968, 0.02456936, -0.19791584, -0.02495837, -0.01396229, 0.15883508, -0.05608664, -0.16127518, 0.14932884, -0.0153573 , -0.27676189, 0.08176911, 0.04226109, 0.19125782, 0.18729328, -0.03498868, 0.0062949 , -0.20621458, 0.1477259 , -0.20221941, -0.01363696, 0.06110315, -0.06132922, 0.05342007, 0.01454075, -0.15085547, 0.06046266, 0.14739415, -0.21987613, -0.03639037, 0.08528309, -0.04437468, 0.03675304, -0.10165367, 0.14875233, 0.156369 , -0.08553442, -0.22346984, 0.11466061, -0.14528711, -0.05263588, 0.10216871, -0.15159039, -0.19255549, -0.29263291, -0.04936468, 0.33185786, 0.09766599, -0.13290709, 0.03094622, -0.01321913, -0.01007816, 0.14334042, 0.12662645, 0.04984599, 0.00495763, -0.08788066, 0.05117153, 0.25504613, -0.03899687, -0.01541797, 0.24360959, -0.00281113, 0.03764223, 0.02046303, 0.08831443, -0.15270098, 0.07429178, -0.16997421, -0.00883572, 0.01246334, 0.02862958, -0.01707144, 0.16006561, -0.15909354, 0.23000078, -0.02357504, -0.0060425 , -0.02578063, -0.03944276, -0.05486409, 0.01571657, 0.15119481, -0.14951093, 0.16744466, 0.17089023, 0.05214873, 0.14098236, 0.10236948, 0.05116107, -0.08004355, 0.01013784, -0.29215148, 0.0257933 , 0.08701295, -0.02425266, 0.13502946, 0.02853448])]
进行识别时,将已有特征值与检测出的特征值两者之间计算欧式距离,设定阈值,大于阈值的不是同一人,小于阈值的为同一人
dist_ = numpy.linalg.norm(i - d_test)
numpy提供了linalg.norm方法来计算欧式距离,通常阈值设定在0.35即可