简介:本文详细介绍了Python环境下人脸对比与人脸对齐的实现方法,包括关键技术、常用库及代码示例,帮助开发者快速掌握人脸识别中的核心环节。
在计算机视觉领域,人脸识别技术因其广泛的应用场景(如身份验证、安防监控、人机交互等)备受关注。其中,人脸对比(验证两张人脸是否属于同一人)和人脸对齐(将人脸图像调整到标准姿态)是核心环节。本文将基于Python,深入探讨这两种技术的实现方法、常用库及代码示例,为开发者提供实用指南。
人脸对齐旨在消除人脸姿态、表情和尺度差异,将人脸关键点(如眼睛、鼻尖、嘴角)对齐到预设的标准位置。这一步骤对后续的人脸对比至关重要,因为未经对齐的人脸图像可能因角度或表情差异导致特征提取不准确。
import dlibimport cv2import numpy as np# 加载预训练的关键点检测模型predictor_path = "shape_predictor_68_face_landmarks.dat"predictor = dlib.shape_predictor(predictor_path)detector = dlib.get_frontal_face_detector()def align_face(image_path, output_size=(160, 160)):# 读取图像img = cv2.imread(image_path)gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 检测人脸faces = detector(gray, 1)if len(faces) == 0:return None# 获取第一个检测到的人脸的关键点face = faces[0]landmarks = predictor(gray, face)# 提取左眼、右眼和鼻尖的关键点left_eye = np.array([(landmarks.part(i).x, landmarks.part(i).y) for i in range(36, 42)])right_eye = np.array([(landmarks.part(i).x, landmarks.part(i).y) for i in range(42, 48)])nose_tip = (landmarks.part(30).x, landmarks.part(30).y)# 计算两眼中心点left_eye_center = np.mean(left_eye, axis=0)right_eye_center = np.mean(right_eye, axis=0)eye_center = (left_eye_center + right_eye_center) / 2# 计算旋转角度(使两眼水平)dx = right_eye_center[0] - left_eye_center[0]dy = right_eye_center[1] - left_eye_center[1]angle = np.degrees(np.arctan2(dy, dx))# 计算仿射变换矩阵M = cv2.getRotationMatrix2D(eye_center, angle, 1.0)# 应用旋转rotated_img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))# 裁剪并调整大小h, w = output_sizex = eye_center[0] - w // 2y = eye_center[1] - h // 2aligned_img = rotated_img[y:y+h, x:x+w]# 确保输出尺寸一致if aligned_img.shape[0] != h or aligned_img.shape[1] != w:aligned_img = cv2.resize(aligned_img, (w, h))return aligned_img# 使用示例aligned_img = align_face("input.jpg")if aligned_img is not None:cv2.imwrite("aligned_output.jpg", aligned_img)
shape_predictor_68_face_landmarks.dat)。人脸对比通过计算两张人脸图像的相似度得分,判断是否属于同一人。其核心是特征提取(将人脸转换为数值向量)和相似度计算(如余弦相似度、欧氏距离)。
import cv2import numpy as npfrom tensorflow.keras.models import load_modelfrom scipy.spatial.distance import cosine# 加载预训练的FaceNet模型(需自行下载)model_path = "facenet_keras.h5"facenet = load_model(model_path)def extract_face_embedding(face_img):# 调整大小并归一化face_img = cv2.resize(face_img, (160, 160))face_img = face_img.astype("float32")mean, std = face_img.mean(), face_img.std()face_img = (face_img - mean) / stdface_img = np.expand_dims(face_img, axis=0)# 提取特征向量embedding = facenet.predict(face_img)[0]return embeddingdef compare_faces(face_img1, face_img2, threshold=0.5):# 提取特征向量embedding1 = extract_face_embedding(face_img1)embedding2 = extract_face_embedding(face_img2)# 计算余弦相似度distance = cosine(embedding1, embedding2)similarity = 1 - distance# 判断是否为同一人is_same = similarity > thresholdreturn is_same, similarity# 使用示例(需先对齐人脸)face1 = cv2.imread("face1_aligned.jpg")face2 = cv2.imread("face2_aligned.jpg")is_same, similarity = compare_faces(face1, face2)print(f"Is same person? {is_same}, Similarity score: {similarity:.4f}")
Python环境下的人脸对齐与对比技术已高度成熟,结合Dlib、OpenCV和深度学习模型,开发者可快速构建高效的人脸识别系统。未来方向包括:
通过本文的代码示例和技术解析,开发者可快速上手人脸对齐与对比的实现,为安防、金融、零售等领域提供核心技术支持。