如何将本地 .JPG 文件转换为 Base64 以与 Boto3 和 Detect_Text 一起使用?

M W*_*Waz 5 python amazon-web-services boto3 amazon-rekognition

相关代码:

import boto3
from PIL import Image
import base64

client = boto3.client('rekognition')

filename = r'C:\Users\H-63\Pictures\scantests\Rekognition test.JPG'

with open(filename, 'rb') as image_file:
    image = image_file.read()

image = base64.b64encode(image).decode('UTF-8')

response = client.detect_text(
    Image={'Bytes': image
        })
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,出现错误:

An error occurred (InvalidImageFormatException) when calling the DetectText operation: Request has Invalid image format
Run Code Online (Sandbox Code Playgroud)

如何让我的图像成为检测文本的正确格式?文档说它必须是 base64 编码。

kic*_*hik 7

我不确定为什么文档甚至提到 base64,但该函数需要字节。所以只需使用:

with open(filename, 'rb') as image_file:
  image = image_file.read()
  client.detect_text(Image={'Bytes': image})
Run Code Online (Sandbox Code Playgroud)