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

如何获取numpy数组中的最小值以输出人脸识别的前3/前5匹配结果

问题原因
  • 你使用的list.append()是列表的原地修改方法,没有返回值,因此top3 = face_names.append(top_3_matches)得到的top3永远是None,自然无法输出预期内容
  • 你获取的top_3_matches只是排序后的索引值,没有对应到人名、匹配距离这些实际可用的信息,单纯存储索引没有实际意义
可行解决方案

你可以按照以下逻辑修改代码,支持自定义取前N个匹配结果,同时保留原有的容差校验逻辑:

def classify_face(im):
    faces = encoding
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())

    img = cv2.imread(im, 1)
    img = cv2.resize(img, (600, 600), fx=0.5, fy=0.5)

    face_locations = face_recognition.face_locations(img, number_of_times_to_upsample=2, model="cnn")
    unknown_face_encodings = face_recognition.face_encodings(img, face_locations, num_jitters=100)

    face_names = []
    # 可自定义要取的前N个匹配结果,改为5就是取前5
    TOP_N = 3
    # 匹配容差阈值,和原有逻辑保持一致
    TOLERANCE = 0.6

    for face_encoding in unknown_face_encodings:
        # 计算所有已知人脸和当前人脸的匹配距离,距离越小匹配度越高
        face_distances = face_recognition.face_distance(faces_encoded, face_encoding)
        # 拿到按距离从小到大排序的前N个索引
        sorted_match_indices = np.argsort(face_distances)[:TOP_N]
        
        current_face_result = []
        for idx in sorted_match_indices:
            # 仅保留符合容差的匹配结果
            if face_distances[idx] < TOLERANCE:
                current_face_result.append(
                    (known_face_names[idx], round(face_distances[idx], 4))
                )
        
        # 没有符合容差的结果时标记为Unknown
        if not current_face_result:
            current_face_result.append(("Unknown", None))
        
        face_names.append(current_face_result)
        # 打印当前人脸的匹配结果
        print("=== 当前检测到的人脸匹配结果 ===")
        for name, dist in current_face_result:
            if dist:
                print(f"- 姓名:{name},匹配距离:{dist}")
            else:
                print(f"- {name}")

修改后你可以直接通过调整TOP_N的数值切换取前3还是前5的匹配结果,输出的结果会按匹配度从高到低排序,同时会显示对应的匹配距离方便你判断匹配可信度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:09:01