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

请求指导:将face_recognition存储的人脸模型转换为对应人脸图像

从人脸特征向量获取对应人脸图像的解决方案

注意:128维人脸嵌入向量是不可逆的,无法直接从向量还原出原始人脸图像——这是特征提取过程中的降维操作,已经丢失了图像的像素细节信息。正确的解决思路是在训练阶段同步建立特征向量与对应人脸图像的关联,而非事后从向量逆向生成图像。

一、修正训练阶段的数据存储逻辑

训练时不要仅存储128维特征向量,而是构建包含人员信息、特征向量、人脸图像关联的字典,再用pickle保存:

  • 核心存储结构:每个人员条目包含姓名、128维特征向量、原始人脸图像的路径(推荐存路径,比直接存图像数据更节省空间)
  • 示例代码:
import pickle
import face_recognition
import os

# 初始化训练数据字典
face_records = {}

# 遍历训练图片目录(目录结构:train_faces/[人员姓名]/[人脸图片])
train_root = "./train_faces"
for person_name in os.listdir(train_root):
    person_dir = os.path.join(train_root, person_name)
    if not os.path.isdir(person_dir):
        continue
    # 取该人员的第一张有效人脸图像作为代表(可根据需求存储多图)
    for img_filename in os.listdir(person_dir):
        img_path = os.path.join(person_dir, img_filename)
        img = face_recognition.load_image_file(img_path)
        face_encodings = face_recognition.face_encodings(img)
        if face_encodings:
            face_records[person_name] = {
                "encoding": face_encodings[0],
                "face_img_path": img_path
            }
            break  # 完成该人员的信息存储,进入下一个人员

# 保存训练数据到文件
with open("trained_face_data.pkl", "wb") as f:
    pickle.dump(face_records, f)

二、识别阶段获取对应人脸图像

加载训练好的字典,识别到匹配人员后直接读取关联的人脸图像:

import pickle
import face_recognition
import cv2

# 加载训练数据
with open("trained_face_data.pkl", "rb") as f:
    face_records = pickle.load(f)

# 处理待识别图像
test_image = face_recognition.load_image_file("./test_face.jpg")
test_encodings = face_recognition.face_encodings(test_image)

for test_encoding in test_encodings:
    matched_name = None
    # 匹配人脸特征
    for name, record in face_records.items():
        matches = face_recognition.compare_faces([record["encoding"]], test_encoding)
        if matches[0]:
            matched_name = name
            break
    # 获取并显示对应人脸图像
    if matched_name:
        face_img_path = face_records[matched_name]["face_img_path"]
        face_img = cv2.imread(face_img_path)
        cv2.imshow(f"Matched: {matched_name}", face_img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

三、特殊情况处理

如果之前已经仅存储了特征向量、未关联图像,没有办法从现有特征向量还原人脸图像,只能重新执行训练流程,同步存储图像关联信息。若需直接存储图像数据而非路径,可将face_img_path替换为face_img_data,直接存储img数组(会显著增大pickle文件体积)。

内容的提问来源于stack exchange,提问作者Roshan Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:35:42