如何使用python将图像中的面部保存到AWS Rekognition上的集合中

时间:2018-05-02 17:13:17

标签: python collections amazon-rekognition

我创建了一个集合名称,现在我想将图像添加到集合中,这样我就可以像compare_faces一样运行它们。问题是,当我运行像detect_faces这样的函数时,我不知道如何保存到我创建的特定集合。 AWS文档未显示将CollectionId添加到任何这些函数的语法,以便将我检测到的面部保存到集合中,以便稍后将其用于比较目的。

1 个答案:

答案 0 :(得分:1)

这是您将带有元数据的图像上传到s3的方式,每张图片应该只包含一个面,其中一个名称作为元数据提供

import boto3

s3 = boto3.resource('s3')

# Get list of objects for indexing
images=[('image01.jpeg','Albert Einstein'),
      ('image02.jpeg','Candy'),
      ('image03.jpeg','Armstrong'),
      ('image04.jpeg','Ram'),
      ('image05.jpeg','Peter'),
      ('image06.jpeg','Shashank')
      ]

# Iterate through list to upload objects to S3   
    for image in images:
    file = open(image[0],'rb')
    object = s3.Object('rekognition-pictures','index/'+ image[0])
    ret = object.put(Body=file,
                    Metadata={'FullName':image[1]}
                    )

现在你必须使用lambda函数进行索引,它将完成你的工作并将面存储到你的rekognition集合中,并为dynamodb表中的每个面存储一个名称,这两个你可以在以后使用其他api&#时引用它们39;比较面孔

from __future__ import print_function

import boto3
from decimal import Decimal
import json
import urllib

print('Loading function')

dynamodb = boto3.client('dynamodb')
s3 = boto3.client('s3')
rekognition = boto3.client('rekognition')


# --------------- Helper Functions ------------------

def index_faces(bucket, key):

    response = rekognition.index_faces(
        Image={"S3Object":
            {"Bucket": bucket,
            "Name": key}},
            CollectionId="family_collection")
    return response

def update_index(tableName,faceId, fullName):
    response = dynamodb.put_item(
        TableName=tableName,
        Item={
            'RekognitionId': {'S': faceId},
            'FullName': {'S': fullName}
            }
        ) 

# --------------- Main handler ------------------

def lambda_handler(event, context):

    # Get the object from the event
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(
        event['Records'][0]['s3']['object']['key'].encode('utf8'))

    try:

        # Calls Amazon Rekognition IndexFaces API to detect faces in S3 object 
        # to index faces into specified collection

        response = index_faces(bucket, key)

        # Commit faceId and full name object metadata to DynamoDB

        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            faceId = response['FaceRecords'][0]['Face']['FaceId']

            ret = s3.head_object(Bucket=bucket,Key=key)
            personFullName = ret['Metadata']['fullname']

            update_index('family_collection',faceId,personFullName)

        # Print response to console
        print(response)

        return response
    except Exception as e:
        print(e)
        print("Error processing object {} from bucket {}. ".format(key, bucket))
       raise e