以下是一个使用AWS Lambda返回OCR结果的代码示例:
import json
import boto3
def lambda_handler(event, context):
# 从事件中获取要处理的图像文件名
image_file = event['image_file']
# 创建AWS服务客户端
rekognition_client = boto3.client('rekognition')
# 调用AWS Rekognition服务进行OCR处理
response = rekognition_client.detect_text(
Image={
'S3Object': {
'Bucket': 'your-bucket-name',
'Name': image_file
}
}
)
# 从响应中提取OCR结果
ocr_results = []
for text_detection in response['TextDetections']:
if text_detection['Type'] == 'LINE':
ocr_results.append(text_detection['DetectedText'])
# 构建响应对象
response_object = {
'statusCode': 200,
'body': json.dumps(ocr_results)
}
return response_object
请注意,上述代码假设你已经将图像文件上传到了AWS S3存储桶中,并且已经创建了一个AWS Lambda函数,并将触发器配置为接收图像文件名作为事件输入。
在代码中,首先从事件中获取要处理的图像文件名。然后,创建AWS Rekognition服务的客户端,并使用detect_text
方法调用OCR处理。接下来,从响应中提取OCR结果,并构建一个包含结果的响应对象。最后,将响应对象返回,以便通过API Gateway或其他方式将结果返回给调用方。
请注意,你需要将代码中的your-bucket-name
替换为你的S3存储桶名称,并确保已正确配置AWS Lambda函数的权限以访问该存储桶。