我正在尝试使用Python中的AWS Rekognition检测多个图像的标签。 此过程大约需要3秒钟才能对图像进行标记。有什么方法可以并行标记这些图像吗?
由于我限制使用boto3会话,请尽可能提供代码段。
答案 0 :(得分:0)
您可以做的最好的事情是,不是在本地计算机上运行代码,而是在云中作为函数运行它。使用AWS Lambda,您可以轻松完成此操作。只需添加s3对象上传作为你的lambda的触发器,每当任何图像上传到你的s3桶时,它将触发你的lambda函数,它将 detect_labels ,然后你可以像你那样使用这些标签想要,你甚至可以将它们存储到一个dynamodb表中供以后参考并从该表中获取。
最好的事情是,如果您同时上传多个图像,那么每个图像将被并行执行,因为lambda具有高度可扩展性,您可以同时获得所有结果。
相同的示例代码:
from __future__ import print_function
import boto3
from decimal import Decimal
import json
import urllib
print('Loading function')
rekognition = boto3.client('rekognition')
# --------------- Helper Functions to call Rekognition APIs ------------------
def detect_labels(bucket, key):
response = rekognition.detect_labels(Image={"S3Object": {"Bucket": bucket, "Name": key}})
# Sample code to write response to DynamoDB table 'MyTable' with 'PK' as Primary Key.
# Note: role used for executing this Lambda function should have write access to the table.
#table = boto3.resource('dynamodb').Table('MyTable')
#labels = [{'Confidence': Decimal(str(label_prediction['Confidence'])), 'Name': label_prediction['Name']} for label_prediction in response['Labels']]
#table.put_item(Item={'PK': key, 'Labels': labels})
return response
# --------------- 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 rekognition DetectLabels API to detect labels in S3 object
response = detect_labels(bucket, key)
print(response)
return response
except Exception as e:
print(e)
print("Error processing object {} from bucket {}. ".format(key, bucket) +
"Make sure your object and bucket exist and your bucket is in the same region as this function.")
raise e