下载地址:https://www.pan38.com/share.php?code=pvvmX 提取码:8888
安装依赖:pip install flask opencv-python dlib numpy pillow
下载shape_predictor_68.dat人脸关键点检测模型
运行Flask服务:python app.py
访问http://localhost:5000/static/index.html 上传照片即可生成眨眼动画
完整系统包含三个核心模块:后端服务处理图像、前端界面交互、核心动画算法。系统支持实时人脸检测和关键点定位,通过薄板样条变换实现自然的眼部变形效果。
from flask import Flask, request, jsonify
import cv2
import numpy as np
import dlib
import base64
from io import BytesIO
from PIL import Image
app = Flask(name)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68.dat")
@app.route('/animate', methods=['POST'])
def animate_face():
img_data = request.json['image']
img_bytes = base64.b64decode(img_data.split(',')[1])
img = np.array(Image.open(BytesIO(img_bytes)))
# 人脸检测和关键点定位
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
faces = detector(gray)
if len(faces) == 0:
return jsonify({"error": "No face detected"})
landmarks = predictor(gray, faces[0])
points = [(p.x, p.y) for p in landmarks.parts()]
# 生成动画帧
frames = []
for i in range(5): # 生成5帧眨眼动画
frame = img.copy()
if i in [2,3]: # 中间帧眨眼
frame = apply_blink(frame, points)
frames.append(frame)
# 转换为base64响应
buffered = BytesIO()
frames[0].save(buffered, format="GIF", save_all=True,
append_images=frames[1:], duration=100, loop=0)
return jsonify({
"gif": "data:image/gif;base64," +
base64.b64encode(buffered.getvalue()).decode()
})
<!DOCTYPE html>
numpy as np
def apply_blink(img, landmarks):
# 眼睛关键点索引 (DLIB 68点模型)
left_eye = landmarks[36:42]
right_eye = landmarks[42:48]
# 创建变形遮罩
mask = np.zeros(img.shape[:2], dtype=np.uint8)
cv2.fillPoly(mask, [np.array(left_eye)], 255)
cv2.fillPoly(mask, [np.array(right_eye)], 255)
# 计算变形后的关键点
modified = landmarks.copy()
modified[37:40] = modified[37:40] + [0, 5] # 上眼睑下移
modified[43:46] = modified[43:46] + [0, 5]
# 应用薄板样条变换
warped = cv2.warpAffine(img,
cv2.estimateAffinePartial2D(
np.float32(landmarks),
np.float32(modified)
)[0],
img.shape[:2][::-1]
)
return cv2.seamlessClone(warped, img, mask, (0,0), cv2.NORMAL_CLONE)