Python 如何通过Boto3向Lambda发送图像字节?
是否可以使用Boto3通过Lambda发送图像字节?字节将被发送到Lambda函数,该函数随后将图像转发给Rekognition。我尝试过这个,但没有成功:Python 如何通过Boto3向Lambda发送图像字节?,python,amazon-web-services,aws-lambda,boto3,Python,Amazon Web Services,Aws Lambda,Boto3,是否可以使用Boto3通过Lambda发送图像字节?字节将被发送到Lambda函数,该函数随后将图像转发给Rekognition。我尝试过这个,但没有成功: with open(image_name) as image_source: image_bytes = image_source.read() context = base64.b64encode(b'{"custom":{ \ "image_name":"'+imagename+'", \ "image_byt
with open(image_name) as image_source:
image_bytes = image_source.read()
context = base64.b64encode(b'{"custom":{ \
"image_name":"'+imagename+'", \
"image_bytes" : "'+image_bytes+'"}}').decode('utf-8')
response = lambda_fn.invoke(
ClientContext=context,
FunctionName='recognize-face-in-image'
)
这是Lambda函数代码:
import boto3
import base64
import json
def lambda_handler(event, context):
print("Lambda triggered...")
rek = boto3.client('rekognition')
context_dict = context.client_context.custom
image_bytes = context_dict["image_bytes"]
rekresp = rek.detect_faces(Image={'Bytes': image_bytes},Attributes=['ALL'])
if not rekresp['FaceDetails']:
print "No face"
else:
print "Got face"
当我运行它时,这是Cloudwatch中显示的Lambda函数错误:
调用DetectFaces时发生错误(ValidationException)
操作:1检测到验证错误:值
“image.bytes”处的“java.nio.HeapByteBuffer[pos=0 lim=0 cap=0]”失败
要满足约束:成员的长度必须大于或等于
to 1:ClientError回溯(最近一次调用last):文件
“var/task/lambda_function.py”,lambda_处理程序rekresp中的第17行=
detect_faces(Image={'Bytes':Image_Bytes},Attributes=['ALL'])文件
“/var/runtime/botocore/client.py”,api调用返回中的第314行
self.\u make\u api\u调用(操作名称,kwargs)文件
“/var/runtime/botocore/client.py”,第612行,在make\u api\u call raise中
错误\u类(已解析的\u响应、操作\u名称)ClientError:错误
调用DetectFaces操作时发生(ValidationException):
检测到1个验证错误:值“java.nio.HeapByteBuffer[pos=0”
“image.bytes”处的lim=0 cap=0]“未能满足约束:成员
长度必须大于或等于1
发件人:
虽然这是JavaScript而不是Python,但它应该给出如何编码
context
ClientContext
并不是向Lambda函数发送批量数据的正确方法。相反,应使用有效载荷
此外,图像将是二进制数据,需要在rb
模式下打开,不能在JSON中携带
import base64
import json
import boto3
with open(image_name, 'rb') as image_source:
image_bytes = image_source.read()
response = boto3.client('lambda').invoke(
FunctionName='recognize-face-in-image',
Payload=json.dumps({
'image_name': image_name,
'image_bytes': base64.b85encode(image_bytes).decode('utf-8'),
}),
)
Lambda函数应该是这样的:
import base64
def handler(event, context):
image_bytes = base64.b85decode(event['image_bytes'])
...
谢谢你的回答。然而,我的问题仅限于“图像字节”。我发送字符串数据没有问题
import base64
def handler(event, context):
image_bytes = base64.b85decode(event['image_bytes'])
...