第一步:编码——将人脸表示为128为的向量
def face_encodings(face_image,known_face_locations=None,num_jitters=1)
"""
return:128维人脸编码向量
param face_image:包含人脸图像
param known_face_locations:是否已知人脸位置
param num_jitters:计算编码时,重新采样的次数
"""
raw_landmarks=_raw_face_landmarks(face_image,known_face_locations,model="small")
return [np.array(face_encoder.compute_face_descriptor(face_image,raw_landmark_set,numjitters)) for raw_landmark_set in raw_landmarks]
1.1 初始人脸标记
def _raw_face_landmarks(face_image, face_locations=None, model="large"):
"""
return:
face_locations: 人脸位置是否已知
model: 两种模式,5特征点(small)和68特征点(large)
"""
if face_locations is None:
face_locations=_raw_face_locations(face_image)
else:
face_locations=[_css_to_rect(face_locations) for face_location in face_locations]
pose_predictor=pose_predictor_68_point
if model=="small"
pose_predictor=pose_predictor_5_point
return [pose_predictor(face_image,face_locations) for face_location in face_locations]
有5特征点和68特征点人脸标记模型——训练特征点模型,提取能够区分不同舰船的重要特征点。
predictor_68_point_model=face_recognition_models.pose_predictor_model_location()
pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model)
"""
来自官方文档
dlib.shape_predictor():输出一组定义对象姿态的点位置。这方面的经典例子是人脸姿势预测,即以人脸图像作为输入,并期望识别重要的面部标志点的位置,如嘴角、眼角、鼻尖等。
"""
from pkg_resources import resource_filename
def pose_predictor_model_location():
return resource_filename(_name_,"models/shape_predictor_68_face_landmarks.dat")
def _css_to_rect(css):
"""
param css: 矩形的纯元组表示(上、右、下、左)
"""
return dlib.rectangle(css[3],css[0],css[1],css[2])
1.2 自主训练人脸特征点检测器
第二步:图像匹配
def compare_faces(known_face_encodings, face_encoding_to_check,tolerance=0.6)
"""
param known_face_encodings: 一列已知人脸的编码
param face_encoding_to_check: 需要比对的人脸编码
param tolerance: 两张脸之间距离多远时认为两张脸是同一人的
"""
return list(face_distance(known_face_encodings, face_encoding_to_check)<=tolerance)
定义两张脸之间的距离face_distance(face_encodings, face_to_compare):多维欧氏距离;