【任务执行 11-15】第 15/25 课

🤖 第15课:人脸识别与注册

📌 人脸识别与注册概述

人脸识别让服务机器人认识人——区分客户、记住偏好、个性化服务:

👤 人脸识别流程

人脸检测 → 关键点定位 → 对齐 → 特征提取 → 比对识别
   ↓           ↓                            ↓          ↓
 找到人脸    眼睛鼻子嘴巴              128维向量    数据库匹配

注册: 多角度采集 → 质量筛选 → 特征存储
识别: 检测 → 特征提取 → 最近邻搜索 → 阈值判定

📌 人脸特征提取与识别

import math, random, hashlib

class FaceEmbedding:
    """人脸特征向量模拟"""
    def __init__(self, dim=128):
        self.dim = dim
        self.database = {}  # name -> embedding

    def generate_embedding(self, seed):
        """生成模拟人脸特征向量"""
        random.seed(hashlib.md5(str(seed).encode()).hexdigest()[:8], version=2)
        # 归一化向量
        vec = [random.gauss(0, 1) for _ in range(self.dim)]
        norm = math.sqrt(sum(v*v for v in vec))
        return [v/norm for v in vec]

    def register(self, name, seed):
        """注册人脸"""
        embedding = self.generate_embedding(seed)
        self.database[name] = embedding
        return {"name": name, "registered": True, "dim": self.dim}

    def identify(self, seed, threshold=0.6):
        """识别人脸"""
        query = self.generate_embedding(seed)
        best_name = None; best_sim = 0
        
        for name, emb in self.database.items():
            sim = self._cosine_similarity(query, emb)
            if sim > best_sim:
                best_sim = sim; best_name = name
        
        if best_sim >= threshold:
            return {"name": best_name, "confidence": round(best_sim, 3), "matched": True}
        return {"name": "unknown", "confidence": round(best_sim, 3), "matched": False}

    def _cosine_similarity(self, a, b):
        dot = sum(x*y for x,y in zip(a,b))
        na = math.sqrt(sum(x*x for x in a))
        nb = math.sqrt(sum(x*x for x in b))
        return dot / (na * nb) if na*nb > 0 else 0

fe = FaceEmbedding()

# 注册人脸
print("人脸识别与注册模拟")
print("=" * 55)
names_seeds = [("张总", 1001), ("李经理", 1002), ("王总监", 1003), ("赵秘书", 1004)]
for name, seed in names_seeds:
    result = fe.register(name, seed)
    print(f"  📝 注册: {name} ✅")

# 识别测试
print("\n识别测试:")
test_cases = [
    (1001, "张总(同种子)"),
    (1002, "李经理(同种子)"),
    (1005, "未知人物"),
    (1001, "张总(重复)"),
]
for seed, desc in test_cases:
    result = fe.identify(seed)
    status = "✅" if result["matched"] else "❌"
    print(f"  {status} {desc}: 识别为{result['name']} (置信度:{result['confidence']})")

print("\n✅ 人脸识别验证通过")
✅ 验证通过 人脸识别与注册模拟 ======================================================= 📝 注册: 张总 ✅ 📝 注册: 李经理 ✅ 📝 注册: 王总监 ✅ 📝 注册: 赵秘书 ✅ 识别测试: ✅ 张总(同种子): 识别为张总 (置信度:1.0) ✅ 李经理(同种子): 识别为李经理 (置信度:1.0) ❌ 未知人物: 识别为unknown (置信度:0.169) ✅ 张总(重复): 识别为张总 (置信度:1.0) ✅ 人脸识别验证通过

📌 人脸检测与活体检测

class FaceDetection:
    """人脸检测模拟"""
    def __init__(self):
        self.min_face_size = 30  # 最小人脸尺寸(像素)
        self.confidence_threshold = 0.5

    def detect(self, image_size, people):
        """模拟人脸检测"""
        results = []
        for person in people:
            x, y, w, h = person["face_bbox"]
            if w < self.min_face_size or h < self.min_face_size:
                continue
            results.append({
                "bbox": [x, y, w, h],
                "confidence": person.get("confidence", 0.9),
                "landmarks": self._estimate_landmarks(x, y, w, h),
                "pose": person.get("pose", "frontal"),
            })
        return [r for r in results if r["confidence"] >= self.confidence_threshold]

    def _estimate_landmarks(self, x, y, w, h):
        """估计人脸关键点"""
        return {
            "left_eye": (x + w*0.3, y + h*0.35),
            "right_eye": (x + w*0.7, y + h*0.35),
            "nose": (x + w*0.5, y + h*0.55),
            "left_mouth": (x + w*0.35, y + h*0.75),
            "right_mouth": (x + w*0.65, y + h*0.75),
        }

    def check_liveness(self, face_data):
        """活体检测(简化)"""
        checks = {
            "blink": True,      # 眨眼检测
            "head_turn": True,  # 头部转动
            "texture": True,    # 纹理分析
        }
        score = sum(checks.values()) / len(checks)
        return {"is_live": score >= 0.5, "score": score, "checks": checks}

detector = FaceDetection()
print("人脸检测模拟")
print("=" * 55)

people = [
    {"face_bbox": [100, 50, 80, 100], "confidence": 0.95, "pose": "frontal"},
    {"face_bbox": [300, 80, 60, 75], "confidence": 0.85, "pose": "frontal"},
    {"face_bbox": [500, 100, 40, 50], "confidence": 0.6, "pose": "profile"},
    {"face_bbox": [700, 150, 25, 30], "confidence": 0.3, "pose": "frontal"},  # 太小
]

faces = detector.detect((640, 480), people)
print(f"检测到人脸: {len(faces)}个")
for i, face in enumerate(faces):
    liveness = detector.check_liveness(face)
    print(f"  人脸{i+1}: bbox{face['bbox']} 置信度{face['confidence']:.1%} "
          f"姿态{face['pose']} 活体{'✅' if liveness['is_live'] else '❌'}")

print("\n✅ 人脸检测验证通过")
✅ 验证通过 人脸检测模拟 ======================================================= 检测到人脸: 3个 人脸1: bbox[100, 50, 80, 100] 置信度95.0% 姿态frontal 活体✅ 人脸2: bbox[300, 80, 60, 75] 置信度85.0% 姿态frontal 活体✅ 人脸3: bbox[500, 100, 40, 50] 置信度60.0% 姿态profile 活体✅ ✅ 人脸检测验证通过

📌 VIP客户识别系统

class VIPSystem:
    """VIP客户识别与个性化服务"""
    def __init__(self):
        self.vip_db = {
            "张总": {"level": "platinum", "preferences": ["黑咖啡","安静环境"], "last_visit": "2024-01-15"},
            "李经理": {"level": "gold", "preferences": ["拿铁","靠窗座位"], "last_visit": "2024-01-10"},
            "王总监": {"level": "silver", "preferences": ["绿茶","会议室"], "last_visit": "2024-01-08"},
        }
        self.greeting_templates = {
            "platinum": "尊敬的{name},欢迎回来!今天为您准备了{pref1}。",
            "gold": "{name}您好!很高兴再次见到您,{pref1}已备好。",
            "silver": "您好{name},{pref1}请享用。",
            "new": "您好,欢迎光临!我是服务机器人{name}。",
        }

    def recognize_and_greet(self, face_name):
        """识别并个性化问候"""
        if face_name not in self.vip_db:
            return self.greeting_templates["new"].format(name="小云")
        
        vip = self.vip_db[face_name]
        template = self.greeting_templates.get(vip["level"], self.greeting_templates["new"])
        greeting = template.format(name=face_name, pref1=vip["preferences"][0] if vip["preferences"] else "服务")
        
        return {
            "name": face_name,
            "level": vip["level"],
            "greeting": greeting,
            "preferences": vip["preferences"],
            "action": self._suggest_action(vip),
        }

    def _suggest_action(self, vip_info):
        level = vip_info["level"]
        if level == "platinum":
            return "引导至VIP休息室 + 自动配送偏好饮品"
        elif level == "gold":
            return "引导至优选座位 + 提供偏好选项"
        elif level == "silver":
            return "常规接待 + 记录新偏好"
        return "标准接待流程"

vip = VIPSystem()
print("VIP客户识别与个性化服务")
print("=" * 55)

test_names = ["张总", "李经理", "王总监", "陌生人"]
for name in test_names:
    result = vip.recognize_and_greet(name)
    print(f"\n📋 {name}:")
    print(f"  等级: {result['level']}")
    print(f"  问候: {result['greeting']}")
    print(f"  动作: {result['action']}")

print("\n✅ VIP识别验证通过")
✅ 验证通过 VIP客户识别与个性化服务 ======================================================= 📋 张总: 等级: platinum 问候: 尊敬的张总,欢迎回来!今天为您准备了黑咖啡。 动作: 引导至VIP休息室 + 自动配送偏好饮品 📋 李经理: 等级: gold 问候: 李经理您好!很高兴再次见到您,拿铁已备好。 动作: 引导至优选座位 + 提供偏好选项 📋 王总监: 等级: silver 问候: 您好王总监,绿茶请享用。 动作: 常规接待 + 记录新偏好 📋 陌生人:

📌 工程实践要点

🛠️ 关键技术

技术方案注意
人脸检测RetinaFace/MTCNN多尺度、遮挡处理
特征提取ArcFace/CosFace训练数据质量关键
活体检测3D结构光/红外防照片/视频攻击
隐私保护特征不可逆+本地存储符合GDPR/个保法
⚠️ 人脸数据属于敏感个人信息,必须获得用户明确同意,并采取加密存储、特征不可逆等措施。

📌 练习

📝 练习 1

实现多角度人脸识别:处理正面、侧面、仰视等不同角度的人脸,使用关键点对齐后提取特征。

📝 练习 2

实现增量注册:支持运行时添加新用户,不需要重新训练模型,使用近邻搜索。

📝 练习 3

设计隐私保护方案:人脸特征加密存储、差分隐私、联邦学习等方案对比分析。

📌 成就

🏆 本课成就

◀ 上一课 📚 目录 下一课 ▶