#!/usr/bin/python # -*- coding: utf-8 -*- import time import dlib import numpy as np class faceDiscernModel: def __init__(self): # 加载预训练人脸检测CNN模型 self.cnn_face_model = "./model/mmod_human_face_detector.dat" self.cnn_face_detector = dlib.cnn_face_detection_model_v1(self.cnn_face_model) # 加载人脸特征检测模型 self.predictor_path = "./model/shape_predictor_5_face_landmarks.dat" self.predictor = dlib.shape_predictor(self.predictor_path) # 加载人脸特征提取模型 self.featureModel = "./model/dlib_face_recognition_resnet_model_v1.dat" self.feater = dlib.face_recognition_model_v1(self.featureModel) def get_faces_feature(self,imgPath): # 读取人脸图片 img = dlib.load_rgb_image(imgPath) feat = [] # 检测每个人脸的边界框 dets = self.cnn_face_detector(img, 1) # len(dets) 是检测到的人脸数量 for i, d in enumerate(dets): # print("Detection {}: Left: {} Top: {} Right: {} Bottom: {} Confidence: {}".format( # i, d.rect.left(), d.rect.top(), d.rect.right(), d.rect.bottom(), d.confidence)) # 检测 box i 内的人脸关键点 shape = self.predictor(img, d.rect) # 计算特征向量 face_descriptor = self.feater.compute_face_descriptor(img, shape) feat.append(face_descriptor) return feat def Euclidean_distance_test(self,feature_1,feature_2): return np.sqrt(np.sum((np.array(feature_1)-np.array(feature_2))**2)) def face_compare(self,imgPath_1,imgPath_2,assess=0.6): feature_1 = self.get_faces_feature(imgPath_1) feature_2 = self.get_faces_feature(imgPath_2) score = self.Euclidean_distance_test(feature_1=feature_1,feature_2=feature_2) if score > assess: return False elif 0< score < assess: return True else: return False if __name__ == \'__main__\': imgPath_1 = "./faceImage/test.jpg" imgPath_2 = "./faceImage/test1.jpg" faceDiscern = faceDiscernModel() st = time.time() result = faceDiscern.face_compare(imgPath_1,imgPath_2) print(time.time()-st) print(result)
python 封装dlib模型进行人脸识别系统的登录认证
内容版权声明:除非注明,否则皆为本站原创文章。