You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何导出DeepFace模型至磁盘?优化实时人脸匹配启动速度

解决方案:DeepFace模型导出与实时人脸匹配优化

一、正确导出DeepFace模型到磁盘

直接用model.save("vgg_face_model.h5")失败,是因为VGG-Face模型包含自定义层,H5格式无法完整保存这类模型。改用TensorFlow的SavedModel格式即可:

from deepface import DeepFace
import tensorflow as tf

# 加载模型
model = DeepFace.build_model("VGG-Face")

# 用SavedModel格式保存(推荐)
model.save("vgg_face_model")  # 无需后缀,会生成一个文件夹

# 后续加载模型的方式
loaded_model = tf.keras.models.load_model("vgg_face_model")
# 告诉DeepFace使用加载后的模型
DeepFace.build_model = lambda _: loaded_model  # 覆盖默认的build_model方法

如果仍要保存为H5格式,需要额外处理自定义层的序列化,但SavedModel是更可靠的方案,建议优先使用。

二、实时人脸匹配的优化方案

除了预保存模型,还有以下方法可大幅降低启动延迟和运行耗时:

1. 预提取目标人脸的特征

DeepFace.verify每次都会重新提取目标照片的特征,预提取后直接在循环中比对帧特征,避免重复计算:

import cv2
from deepface import DeepFace
import numpy as np

# 预提取目标人脸特征
target_embedding = DeepFace.represent(img_path="manas2.jpg", model_name="VGG-Face", enforce_detection=False)[0]['embedding']
target_embedding = np.array(target_embedding)

stream_url = "http://192.168.77.141:8080/video"
cap = cv2.VideoCapture(stream_url)

if not cap.isOpened():
    print("Error: Could not open video stream.")
    exit()

# 预加载模型(可结合上面的模型保存加载逻辑)
DeepFace.build_model("VGG-Face")

while True:
    ret, frame = cap.read()
    if not ret:
        print("Error: Could not read frame.")
        break

    try:
        # 只提取当前帧的人脸特征
        frame_embeddings = DeepFace.represent(img_path=frame, model_name="VGG-Face", enforce_detection=False)
        if frame_embeddings:
            frame_embedding = np.array(frame_embeddings[0]['embedding'])
            # 计算余弦相似度(DeepFace默认用该指标判断匹配)
            similarity = np.dot(target_embedding, frame_embedding) / (np.linalg.norm(target_embedding) * np.linalg.norm(frame_embedding))
            # 设定匹配阈值(DeepFace默认阈值约0.65,可根据模型调整)
            if similarity > 0.65:
                print("Matched !!")
                break
            else:
                print("Not matched")
    except ValueError as e:
        print(f"Face verification failed: {e}")

    cv2.imshow('Phone Camera Stream', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

2. 使用更轻量的模型

VGG-Face属于较重的模型,启动和推理耗时都高。换成DeepFace支持的轻量模型,比如OpenFace或MobileNet,能大幅提速:

# 替换模型名称即可
target_embedding = DeepFace.represent(img_path="manas2.jpg", model_name="OpenFace", enforce_detection=False)[0]['embedding']

3. 降低检测频率

不需要每一帧都做匹配,比如每5帧检测一次,减少计算量:

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

    frame_count += 1
    if frame_count % 5 != 0:  # 每5帧执行一次匹配逻辑
        cv2.imshow('Phone Camera Stream', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        continue

    # 此处执行匹配逻辑
    # ...

4. 启用模型缓存(DeepFace自带)

DeepFace默认会把下载的模型缓存到用户目录(如~/.deepface/weights/),第一次加载后后续启动会自动读取缓存,无需手动保存。如果启动慢是因为每次重新下载模型,检查缓存目录的读写权限是否正常。

内容的提问来源于stack exchange,提问作者Manas Bisht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:03:13