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

如何解析AWS Rekognition get_face_search结果中的FaceMatches数据?

解决AWS Rekognition get_face_search()提取FaceMatches数据的TypeError问题

我来帮你搞定这个问题!你遇到的TypeError其实是个常见小坑——AWS Rekognition返回的FaceMatches是列表类型(哪怕只有一个匹配人脸),而不是单个字典,所以你直接用m['FaceMatches']['Face']去索引肯定会报错,因为列表只能用整数下标访问,不能用字符串。

错误原因拆解

你之前的代码:

matches = [m['FaceMatches']['Face']['FaceId'] for m in response['Persons']]

这里的m['FaceMatches']返回的是类似[{'Face': {...}, 'Similarity': ...}]的列表,不是{'Face': ...}这样的字典,所以必须先遍历这个列表里的每个匹配项。

正确的提取方法

我们需要把每个Person的时间戳,和它对应的所有匹配人脸信息(FaceId、Similarity)关联起来,同时还要处理那些没有FaceMatches的Person条目(避免KeyError)。

方法1:可读性优先的循环写法

# 初始化列表存储最终数据
face_match_results = []

for person in response['Persons']:
    # 获取当前Person的时间戳
    current_timestamp = person['Timestamp']
    # 检查当前Person是否存在有效的FaceMatches
    if 'FaceMatches' in person and person['FaceMatches']:
        # 遍历每个匹配的人脸条目
        for face_match in person['FaceMatches']:
            face_id = face_match['Face']['FaceId']
            similarity_score = face_match['Similarity']
            # 将信息打包成字典加入列表
            face_match_results.append({
                'Timestamp': current_timestamp,
                'FaceId': face_id,
                'Similarity': similarity_score
            })

方法2:简洁的列表推导式写法

如果你喜欢更紧凑的代码,也可以用嵌套的列表推导式,效果和上面的循环完全一致:

face_match_results = [
    {
        'Timestamp': p['Timestamp'],
        'FaceId': fm['Face']['FaceId'],
        'Similarity': fm['Similarity']
    }
    for p in response['Persons']
    if 'FaceMatches' in p and p['FaceMatches']
    for fm in p['FaceMatches']
]

结果示例

假设你的response里有一个Person条目包含2个匹配人脸,最终face_match_results会生成类似这样的结构:

[
    {'Timestamp': 0, 'FaceId': 'xxx-1', 'Similarity': 98.5},
    {'Timestamp': 66, 'FaceId': 'xxx-2', 'Similarity': 97.2},
    # ... 其他匹配项
]

这样你就能轻松遍历处理每个匹配人脸的时间戳、FaceID和相似度信息啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:55:02