问题描述
限时送ChatGPT账号..我有下一个问题,我尝试将 base64 中的图像文件发送到 Lambda 函数(用 Python 编写),以调用 Sagemaker Endpoint,这是我的 Lambda 函数:
I have the next problem, I try send image file in base64 to Lambda function(write in Python), for invoke Sagemaker Endpoint, this is my Lambda Function:
import os
import io
import boto3
import json
import base64
# grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
runtime= boto3.client('runtime.sagemaker')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
data = json.loads(json.dumps(event))
payload = data['foto']
img = base64.b64decode(payload)
#body = json.dumps({"instances": img})
try:
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
Body=img)
print(response)
except Exception as e:
print("Inference Error:")
print(e)
return { "img":"ok" }
在 Jupyter 中调用 sagemaker 端点可以很好地使用此代码,
And sagemaker endpoint invoke in Jupyter works fine with this code,
from tensorflow.keras.preprocessing.image import ImageDataGenerator
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory('./data/val', target_size=(224,224))
instance = test_generator[1][0]
print(instance.shape)
array = instance.reshape((1,) + instance.shape)
payload = { 'instances': array.tolist() }
resp = tf_predictor.predict(payload)['predictions']
print(resp)
Lambda 中的错误表示数据类型未知,以及维度中的 CloudWatch 错误.
The error in Lambda says that the data type is unknown, and CloudWatch error in dimensions.
我认为,错误出在 invoke_endpoint 方法的主体中,但我没有找到如何将字节类型转换为包含图像数据的列表.我需要带有 numpy 或其他库的自定义 Lambda 函数?或者没有必要
I think, that the error is in Body of invoke_endpoint method, but i not found how convert bytes type to list with image data. I need custom Lambda Function with numpy, or other library? or isn't necesary
推荐答案
解决方案很简单使用 bytes(img)
将 base64 转换为字节并将 ContentType='image/jpeg'
添加到调用端点.
Solution it simple
Convert base64 to bytes with bytes(img)
and add ContentType='image/jpeg'
to the invoke endpoint.
经过两次小的更改后,您的 Lambda 函数现在应该是这样的:
After two small changes, This is how your Lambda function should look now:
import os
import io
import boto3
import json
import base64
# grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
runtime= boto3.client('runtime.sagemaker')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
data = json.loads(json.dumps(event))
payload = data['foto']
img = base64.b64decode(payload)
payload = bytes(img) # convert base64 to bytes
try:
response = runtime.invoke_endpoint
(
EndpointName=ENDPOINT_NAME,
ContentType='image/jpeg' ,
Body=payload
)
print(response)
except Exception as e:
print("Inference Error:")
print(e)
return {"img": "ok"}
这篇关于AWS Lambda 将图像文件发送到 Amazon Sagemaker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论