一组Python调Deepface卷积的代码-适合人工智能应用学习

import cv2
from deepface import DeepFace


# -----------------------------
# 1. 图片对比:人脸验证
# -----------------------------
def verify_faces(img1_path, img2_path):
    print(f"\n[1] 正在验证 {img1_path} 和 {img2_path} 是否为同一人...")
    result = DeepFace.verify(img1_path=img1_path, img2_path=img2_path, model_name="ArcFace")
    if result["verified"]:
        print("✅ 验证通过:是同一个人")
    else:
        print("❌ 验证失败:不是同一个人")
    print(f"相似度距离: {result['distance']:.4f}")


# -----------------------------
# 2. 数据库识别:查找最匹配的人脸
# -----------------------------
def find_face_in_db(img_path, db_path):
    print(f"\n[2] 正在从数据库中查找与 {img_path} 最匹配的人脸...")
    try:
        dfs = DeepFace.find(img_path=img_path, db_path=db_path, model_name="ArcFace")
        if len(dfs) > 0:
            print("✅ 匹配结果:")
            print(dfs.head())
        else:
            print("❌ 未找到匹配项")
    except Exception as e:
        print("❌ 错误:", str(e))


# -----------------------------
# 3. 获取表情(替代方法)
# -----------------------------
def detect_emotion(img_path):
    print(f"\n[3] 正在分析 {img_path} 的表情...")
    try:
        results = DeepFace.analyze(
            img_path=img_path,
            actions=["emotion"],
            enforce_detection=False
        )

        if isinstance(results, list):
            result = results[0]

        emotion = result.get("dominant_emotion", "未知")
        scores = result.get("emotion", {})
        max_score = max(scores.values()) if scores else 0

        print(f"😊 表情: {emotion} | 置信度: {max_score:.2f}")
    except Exception as e:
        print("❌ 分析出错:", str(e))


# -----------------------------
# 4. 获取年龄、性别、种族和情绪
# -----------------------------
def analyze_attributes(img_path):
    print(f"\n[4] 正在分析 {img_path} 的属性(年龄、性别、情绪、种族)...")
    try:
        results = DeepFace.analyze(
            img_path=img_path,
            actions=["age", "gender", "emotion", "race"],
            enforce_detection=False
        )

        if isinstance(results, list):
            result = results[0]

        print(f"🧍 年龄: {result['age']}")
        print(f"👩👦 性别: {result['dominant_gender']}")
        print(f"😄 情绪: {result['dominant_emotion']}")
        print(f"🌍 种族: {result['dominant_race']}")

    except Exception as e:
        print("❌ 分析出错:", str(e))


# -----------------------------
# 5. 实时摄像头检测
# -----------------------------
def realtime_analysis():
    print("\n[5] 启动摄像头,开始实时人脸属性分析... (按 'q' 退出)")
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        try:
            # 分析人脸属性
            result = DeepFace.analyze(frame, actions=['age', 'gender', 'emotion'], enforce_detection=False)

            if isinstance(result, list) and len(result) > 0:
                result = result[0]

            age = result.get("age", "未知")
            gender = result.get("dominant_gender", "未知")
            emotion = result.get("dominant_emotion", "未知")

            info = f"Age: {age} | Gender: {gender} | Emotion: {emotion}"
            cv2.putText(frame, info, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)

        except Exception as e:
            print("分析出错:", str(e))

        cv2.imshow('DeepFace Realtime Analysis', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()


# -----------------------------
# 主函数入口
# -----------------------------
if __name__ == "__main__":
    # 示例图片路径(请根据实际情况修改)
    IMG1_PATH = "test_images/img1.jpg"
    IMG2_PATH = "test_images/img2.jpg"
    DB_PATH = "test_images/database/"

    # 执行各项功能(可注释掉不需要的部分)
    verify_faces(IMG1_PATH, IMG2_PATH)
    find_face_in_db(IMG1_PATH, DB_PATH)
    detect_emotion(IMG1_PATH)
    analyze_attributes(IMG1_PATH)
    realtime_analysis()
test_images/
├── img1.jpg
├── img2.jpg
└── database/
    ├── personA/
    │   ├── face1.jpg
    │   └── face2.jpg
    └── personB/
        └── face1.jpg

项目的路径布局准备好,可以走通-------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值