下载地址:https://www.pan38.com/share.php?code=pvvmX 提取码:8888
完整的人脸动态特征识别与图像生成系统的实现方案,包含约200行核心代码。系统使用OpenCV和Dlib库实现基础功能,可以通过扩展深度学习模型进一步提升性能
一、技术背景
活体检测是人脸识别系统中的关键环节,主要防范照片、视频等欺骗手段。本系统实现以下核心功能:
实时检测眨眼、张嘴等面部动作
生成带动态效果的合成人脸图像
支持头部姿态估计(摇头检测)
二、核心代码实现
import cv2
import dlib
import numpy as np
from scipy.spatial import distance as dist
from imutils import face_utils
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import random
初始化面部检测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
关键点索引常量
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
(jStart, jEnd) = face_utils.FACIAL_LANDMARKS_IDXS["jaw"]
(mStart, mEnd) = face_utils.FACIAL_LANDMARKS_IDXS["mouth"]
def eye_aspect_ratio(eye):
# 计算眼睛纵横比(EAR)
A = dist.euclidean(eye[1], eye[5])
B = dist.euclidean(eye[2], eye[4])
C = dist.euclidean(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
AI 代码解读
def mouth_aspect_ratio(mouth):
# 计算嘴巴纵横比(MAR)
A = dist.euclidean(mouth[13], mouth[19])
B = dist.euclidean(mouth[14], mouth[18])
C = dist.euclidean(mouth[15], mouth[17])
D = dist.euclidean(mouth[12], mouth[16])
mar = (A + B + C) / (3.0 * D)
return mar
AI 代码解读
活体检测主函数
def live_detection(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
for rect in rects:
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
# 提取左右眼坐标
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
ear = (leftEAR + rightEAR) / 2.0
# 提取嘴巴坐标
mouth = shape[mStart:mEnd]
mar = mouth_aspect_ratio(mouth)
# 检测眨眼
if ear < 0.21:
cv2.putText(frame, "BLINK DETECTED!", (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# 检测张嘴
if mar > 0.79:
cv2.putText(frame, "MOUTH OPENED!", (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
return frame
AI 代码解读
动态图像生成函数
def generate_animated_face(image_path):
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
if len(rects) == 0:
return None
rect = rects[0]
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
# 创建动画帧序列
frames = []
for i in range(10):
temp_img = image.copy()
# 模拟眨眼效果
if i < 5:
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
cv2.drawContours(temp_img, [leftEye], -1, (0, 0, 0), -1)
cv2.drawContours(temp_img, [rightEye], -1, (0, 0, 0), -1)
# 模拟张嘴效果
if i > 5:
mouth = shape[mStart:mEnd]
mouthHull = cv2.convexHull(mouth)
cv2.drawContours(temp_img, [mouthHull], -1, (0, 0, 0), -1)
frames.append(temp_img)
return frames
AI 代码解读
头部姿态估计
def head_pose_estimation(image):
# 3D模型点
model_points = np.array([
(0.0, 0.0, 0.0), # 鼻尖
(0.0, -330.0, -65.0), # 下巴
(-225.0, 170.0, -135.0), # 左眼左角
(225.0, 170.0, -135.0), # 右眼右角
(-150.0, -150.0, -125.0), # 左嘴角
(150.0, -150.0, -125.0) # 右嘴角
])
# 2D图像点
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0)
if len(rects) == 0:
return None
rect = rects[0]
shape = predictor(gray, rect)
shape = face_utils.shape_to_np(shape)
image_points = np.array([
shape[30], # 鼻尖
shape[8], # 下巴
shape[36], # 左眼左角
shape[45], # 右眼右角
shape[48], # 左嘴角
shape[54] # 右嘴角
], dtype="double")
# 相机参数
size = image.shape
focal_length = size[1]
center = (size[1]/2, size[0]/2)
camera_matrix = np.array(
[[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]], dtype = "double"
)
dist_coeffs = np.zeros((4,1)) # 假设没有镜头畸变
(success, rotation_vector, translation_vector) = cv2.solvePnP(
model_points, image_points, camera_matrix, dist_coeffs)
# 绘制头部姿态
(nose_end_point2D, jacobian) = cv2.projectPoints(
np.array([(0.0, 0.0, 1000.0)]),
rotation_vector,
translation_vector,
camera_matrix,
dist_coeffs)
p1 = (int(image_points[0][0]), int(image_points[0][1]))
p2 = (int(nose_end_point2D[0][0][0]), int(nose_end_point2D[0][0][1]))
cv2.line(image, p1, p2, (255,0,0), 2)
return image
AI 代码解读
主程序
if name == "main":
# 示例用法
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
frame = live_detection(frame)
cv2.imshow("Live Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
AI 代码解读
三、系统部署说明
依赖安装:
pip istall opencv-python dlib imutils numpy scipy matplotlib pillow
需要下载预训练模型:
shape_predictor_68_face_landmarks.dat
功能扩展建议:
添加深度学习模型提高检测精度
实现更复杂的动画效果
增加3D人脸重建功能