如何将Numpy Ndarray转为Bytes适配Amazon Textract的boto3调用
如何用Amazon Textract处理Numpy Ndarray格式的图像
你目前通过boto3调用Amazon Textract处理本地文件的代码可以正常运行:
import boto3 import numpy as np def filename_to_json(self, filename): client = boto3.client('textract') if filename is not None: with open(filename, 'rb') as image: response = client.detect_document_text(Document={'Bytes': image.read()}) return response
你的需求是修改代码,让detect_document_text能够处理存储在变量中的Numpy Ndarray图像,之前尝试numpy.ndarray.tobytes()、base64.b64encode()等方法均未成功。
根据AWS文档说明:
Bytes
经过Base64编码的文档字节 blob。通过字节 blob 提供的文档最大大小为5 MB,文档字节必须为PNG或JPEG格式。
如果使用AWS SDK调用Amazon Textract,传入Bytes字段的图像字节可能无需进行Base64编码。
类型:Base64编码的二进制数据对象
解决方案
问题核心:直接用ndarray.tobytes()得到的是原始像素数据的字节流,并非Textract要求的PNG/JPEG这类编码后的图像格式字节。必须先把Numpy数组转换成标准图像格式的二进制流,再传给Textract。
下面提供两种常用实现方式:
方法1:使用PIL库(Pillow)
先安装依赖:pip install pillow
import boto3 import numpy as np from PIL import Image import io def ndarray_to_json(self, image_array): client = boto3.client('textract') # 处理图像格式转换(RGBA转RGB,灰度图直接使用) if image_array.ndim == 3 and image_array.shape[2] == 4: pil_image = Image.fromarray(image_array).convert('RGB') else: pil_image = Image.fromarray(image_array) # 将PIL图像转为JPEG格式字节流 img_byte_arr = io.BytesIO() pil_image.save(img_byte_arr, format='JPEG') img_byte_arr = img_byte_arr.getvalue() response = client.detect_document_text(Document={'Bytes': img_byte_arr}) return response
方法2:使用OpenCV库
先安装依赖:pip install opencv-python
import boto3 import numpy as np import cv2 def ndarray_to_json(self, image_array): client = boto3.client('textract') # OpenCV默认BGR格式,转为RGB(彩色图像需处理) if image_array.ndim == 3: image_array = cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB) # 将数组编码为JPEG格式字节流 _, img_encoded = cv2.imencode('.jpg', image_array) img_byte_arr = img_encoded.tobytes() response = client.detect_document_text(Document={'Bytes': img_byte_arr}) return response
关键注意事项
- 若数组是0-1范围的浮点型,需先转成0-255的uint8类型:
image_array = (image_array * 255).astype(np.uint8) - 无需手动做Base64编码,boto3会自动处理该步骤
- 支持JPEG/PNG两种格式,可根据需求替换编码格式
内容的提问来源于stack exchange,提问作者ITdreamer
相关产品推荐
相关产品推荐

