如何用Python将图片检测到的人脸存入指定AWS Rekognition集合
解决思路:用
index_faces替代detect_faces完成人脸入库 我来帮你理清这个问题——AWS Rekognition的detect_faces确实只是用来检测图片中的人脸属性(比如年龄、表情),并不负责将人脸特征存入集合。要完成把人脸添加到指定集合的操作,你需要用专门的index_faces API,这才是集合人脸索引的正确姿势。
步骤1:初始化Rekognition客户端
确保你已经配置好AWS凭证(环境变量、~/.aws/credentials文件或IAM角色),然后初始化客户端:
import boto3 # 替换为你的AWS区域,比如us-east-1 rekognition = boto3.client('rekognition', region_name='你的区域')
步骤2:将本地图片中的人脸存入集合
如果你的图片保存在本地,直接读取二进制数据传入index_faces即可:
collection_id = "你已创建的集合名称" image_path = "./test_face.jpg" # 替换为你的本地图片路径 # 读取图片二进制数据 with open(image_path, 'rb') as image_file: image_bytes = image_file.read() # 调用index_faces将人脸存入集合 response = rekognition.index_faces( CollectionId=collection_id, Image={'Bytes': image_bytes}, ExternalImageId="user_001", # 可选:自定义图片标识,比如用户ID DetectionAttributes=['DEFAULT'] # 可选:返回人脸属性(年龄、表情等) ) # 查看存入的人脸信息,FaceId是后续比对的关键标识 print("已存入集合的人脸详情:") for face_record in response['FaceRecords']: face_id = face_record['Face']['FaceId'] print(f"人脸ID: {face_id}") print(f"外部标识: {face_record['Face']['ExternalImageId']}\n")
步骤3:将S3存储的图片人脸存入集合
如果图片存在AWS S3桶中,直接指定S3对象参数即可:
response = rekognition.index_faces( CollectionId=collection_id, Image={'S3Object': {'Bucket': '你的S3桶名', 'Name': '图片在桶中的路径'}}, ExternalImageId="user_002" )
进阶:只存入指定的单张人脸(配合detect_faces)
如果图片中有多个人脸,只想存入其中某一个,可以先用detect_faces获取目标人脸的BoundingBox,再在index_faces中指定该区域:
# 先检测图片中的所有人脸 detect_response = rekognition.detect_faces( Image={'Bytes': image_bytes}, Attributes=['DEFAULT'] ) # 假设选择第一个检测到的人脸 target_face = detect_response['FaceDetails'][0] bounding_box = target_face['BoundingBox'] # 只将指定区域的人脸存入集合 index_response = rekognition.index_faces( CollectionId=collection_id, Image={'Bytes': image_bytes}, ExternalImageId="target_user", BoundingBox=bounding_box # 指定要索引的人脸区域 )
后续比对:利用集合完成人脸匹配
存入集合后,你就可以使用compare_faces或search_faces_by_image完成比对需求了。比如用图片搜索集合中的相似人脸:
search_response = rekognition.search_faces_by_image( CollectionId=collection_id, Image={'Bytes': source_image_bytes}, MaxFaces=5 # 返回最多5个匹配结果 ) # 查看匹配结果 for match in search_response['FaceMatches']: print(f"匹配人脸ID: {match['Face']['FaceId']}") print(f"相似度: {match['Similarity']}%\n")
内容的提问来源于stack exchange,提问作者ckdf14
相关产品推荐
相关产品推荐

