结合DeepSeek实现“明星脸”对比+差异诊断+智能建议,全流程代码实战

✅ 核心功能结构

  1. ✅ 用户上传照片 → 提取人脸关键点
  2. ✅ 明星参考图 → 关键点对比
  3. ✅ JSON 结构差异 → 调用 DeepSeek API(大模型)分析面部差异
  4. ✅ 得出智能分析建议并返回

💡 技术栈

  • Python 后端(Flask)
  • face_recognition 提取关键点
  • diff_analysis.py 差异比对
  • DeepSeek API:调用大模型生成自然语言建议(或者生成结构化推荐)

📦 项目依赖(requirements.txt)

flask
face_recognition
opencv-python
requests
numpy

📁 项目结构建议

face-beauty-deepseek/
├── app.py                   # 主服务入口
├── config.py                # DeepSeek 配置
├── utils/
│   ├── landmark_detector.py
│   ├── diff_analysis.py
│   └── deepseek_client.py  # 调用 LLM 分析差异
├── star_faces/
├── user_uploads/
└── requirements.txt

✨ Step 1:DeepSeek API 配置(config.py)

DEEPSEEK_API_KEY = 'your-deepseek-api-key'
DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'

✨ Step 2:封装 DeepSeek 请求(utils/deepseek_client.py)

import requests
from config import DEEPSEEK_API_KEY, DEEPSEEK_API_URL

def deepseek_generate(prompt):
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }

    body = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "system", "content": "你是一位专业的面部医美医生,根据用户和明星面部关键点差异,生成改进建议"},
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7
    }

    response = requests.post(DEEPSEEK_API_URL, headers=headers, json=body)
    if response.status_code == 200:
        return response.json()["choices"][0]["message"]["content"]
    else:
        raise Exception(f"DeepSeek API error: {response.text}")

🔍 Step 3:面部关键点差异分析(utils/diff_analysis.py)

import numpy as np

def point_diff(p1, p2):
    return {"x": round(p1[0] - p2[0], 2), "y": round(p1[1] - p2[1], 2)}

def compare_landmarks(user_lm, star_lm):
    diff = {}
    for feature in user_lm.keys():
        if feature in star_lm:
            user_pts = np.array(user_lm[feature])
            star_pts = np.array(star_lm[feature])

            if len(user_pts) != len(star_pts):
                continue

            feature_diff = []
            for i in range(len(user_pts)):
                delta = point_diff(user_pts[i], star_pts[i])
                feature_diff.append(delta)

            diff[feature] = feature_diff
    return diff

📌 Step 4:人脸特征提取模块(utils/landmark_detector.py)

import face_recognition

def get_landmarks(image_path):
    image = face_recognition.load_image_file(image_path)
    face_landmarks_list = face_recognition.face_landmarks(image)
    if not face_landmarks_list:
        return None
    return face_landmarks_list[0]  # 默认取第一张脸

🧠 Step 5:主服务逻辑(app.py)

from flask import Flask, request, jsonify
import os
from utils.landmark_detector import get_landmarks
from utils.diff_analysis import compare_landmarks
from utils.deepseek_client import deepseek_generate

app = Flask(__name__)
STAR_FACE_DIR = './star_faces'

@app.route('/analyze', methods=['POST'])
def analyze_face():
    image_file = request.files['user_image']
    user_path = './user_uploads/user.jpg'
    image_file.save(user_path)

    user_lm = get_landmarks(user_path)
    if user_lm is None:
        return jsonify({'error': '用户图像未检测到人脸'}), 400

    for file in os.listdir(STAR_FACE_DIR):
        star_path = os.path.join(STAR_FACE_DIR, file)
        star_lm = get_landmarks(star_path)
        if star_lm is None:
            continue

        diff = compare_landmarks(user_lm, star_lm)

        # 🧠 转换为 Prompt 给 DeepSeek
        prompt = generate_prompt_from_diff(file, diff)
        suggestion = deepseek_generate(prompt)

        return jsonify({
            "star_face": file,
            "landmark_diff": diff,
            "suggestion": suggestion
        })

def generate_prompt_from_diff(star_name, diff):
    prompt = f"我上传了一张自拍,与明星 {star_name} 的脸进行对比,关键点差异如下:\n"
    for part, points in diff.items():
        prompt += f"\n【{part}】差异点:"
        prompt += ', '.join([f"(dx: {p['x']}, dy: {p['y']})" for p in points])
    prompt += "\n请根据这些差异,为我提供面部改善建议,适用于轻医美方式(如玻尿酸、线雕等)"
    return prompt

📬 返回 JSON 示例

{
  "star_face": "yangmi.jpg",
  "landmark_diff": {
    "chin": [{"x": -1.2, "y": 2.1}, ...],
    "nose_bridge": [{"x": 0.3, "y": -1.5}, ...]
  },
  "suggestion": "你的下巴略短,可以通过玻尿酸注射延长面部轮廓..."
}

🚀 启动服务

python app.py
# 默认运行在 http://localhost:5000

🔥 后续进阶方向

  • ✅ 加入前端上传、可视化(React/Vue 组件)

  • ✅ 将 landmark 点映射到 Canvas 可视化

  • ✅ 多明星对比并选最相似者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最爱茄子包

谢谢鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值