1. Tìm kiếm và truy cập trang dịch vụ của Lambda



2. Cấu hình cho Analyze Function tại trang Create a function
Trong phần đầu tiên, sẽ có 3 mục để tạo trước template của Lambda Function: Author from scratch, Use a blueprint, Container image
Trong phần Basic information:

Trong phần Change default execution role:



3. Cấu hình Code Analyze Function tại phần Code Source
import json
import boto3
import base64
# Khởi tạo client Rekognition để gọi dịch vụ nhận diện ảnh
rekognition = boto3.client('rekognition')
def lambda_handler(event, context):
try:
# Kiểm tra xem request body có tồn tại không
if 'body' not in event or not event['body']:
return {
"statusCode": 400,
"body": json.dumps({"error": "Empty request body"})
}
# Lấy phần body từ sự kiện gửi vào (kiểm tra có phải là base64 không)
body_str = event['body']
if event.get("isBase64Encoded"): # Nếu API Gateway cấu hình truyền base64
body_str = base64.b64decode(event['body']).decode('utf-8')
# Chuyển chuỗi JSON thành dictionary Python
body = json.loads(body_str)
# Lấy dữ liệu ảnh dạng base64 từ trường "image"
image_base64 = body.get('image')
# Nếu không có ảnh thì trả về lỗi
if not image_base64:
return {
"statusCode": 400,
"body": json.dumps({"error": "Missing 'image' in request body"})
}
# Giải mã ảnh từ base64 thành dạng bytes
image_bytes = base64.b64decode(image_base64)
# Gọi AWS Rekognition để nhận diện nhãn trong ảnh
response = rekognition.detect_labels(
Image={'Bytes': image_bytes}, # Truyền ảnh dạng bytes
MaxLabels=10, # Giới hạn tối đa 10 nhãn trả về
MinConfidence=75 # Chỉ lấy nhãn có độ tin cậy từ 75% trở lên
)
# Trả kết quả nhận diện về dưới dạng JSON
return {
"statusCode": 200,
"body": json.dumps({
"labels": response.get('Labels', []),
"message": "Image analyzed successfully"
}),
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*" # Cho phép gọi từ frontend
}
}
except Exception as e:
# Nếu có lỗi thì log ra và trả về mã lỗi 500
print("Error:", str(e))
return {
"statusCode": 500,
"body": json.dumps({"error": str(e)})
}


Bạn đã hoàn thành bước cấu hình Lambda Function cho chức năng Phân tích ảnh bằng cách gọi Client của AWS Rekognition