In this demo, we will:
rekognition-lab-demo-590121
AWSLambdaBasicExecutionRole
RekognitionLabLambdaRole
AmazonS3FullAccess
AmazonRekognitionFullAccess
RekognitionImageAnalyzer
import json
import boto3
import urllib.parse
# Initialize the Rekognition client
rekognition_client = boto3.client('rekognition')
def lambda_handler(event, context):
print("Received event:", json.dumps(event, indent=2))
# Iterate over each record in the event. S3 events are batched in a 'Records' list.
for record in event.get('Records', []):
# Get the bucket name and object key from the S3 event notification
try:
bucket_name = record['s3']['bucket']['name']
# URL decode the object key in case of special characters (e.g., spaces)
object_key = urllib.parse.unquote_plus(record['s3']['object']['key'])
except KeyError as e:
print(f"Error extracting bucket/key from S3 record: {e}")
print("Skipping this record:", json.dumps(record))
continue # Move to the next record
print(f"Analyzing image: s3://{bucket_name}/{object_key}")
try:
# Call Rekognition DetectLabels API
response = rekognition_client.detect_labels(
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': object_key
}
},
MaxLabels=10, # Return up to 10 labels
MinConfidence=75 # Return labels with at least 75% confidence
)
labels = response.get('Labels', [])
print(f"Detected labels for {object_key}:")
if labels:
for label in labels:
print(f"- Label: {label['Name']}, Confidence: {label['Confidence']:.2f}%")
else:
print("No labels detected with the specified confidence.")
except Exception as e:
print(f"Error calling Rekognition or processing image '{object_key}': {e}")
# For production, consider more specific error handling like for 'InvalidS3ObjectException'.
# Depending on requirements, you might want to continue processing other records instead of returning an error.
return {
'statusCode': 500,
'body': json.dumps(f'Error processing image: {str(e)}')
}
# Return a success response after processing all records
return {
'statusCode': 200,
'body': json.dumps('All records processed successfully!')
}
InvokeRekognitionLambdaOnImageUpload
permanently delete
rekognition-lab-demo-590121
RekognitionLabLambdaRole
confirm