python-3.x - 如何将 PIL.JpegImagePlugin.JpegImageFile 传递给 google vision api?
问题描述
关于使用 pdf2img 将 PDF 文件转换为图像:
from pdf2image import convert_from_path
import io
def read_pdf(filename):
# Store Pdf with convert_from_path function
images = convert_from_path(filename, poppler_path=r'C:\Program Files\poppler-0.68.0\bin',fmt='jpeg')
for i in range(len(images)):
# Save pages as images in the pdf
return images[0]
if __name__ == '__main__':
img = read_pdf('PDF File.pdf')
print(img)
img在 0x16C3B9C3610 处为我提供PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1653x2339。
我想直接将图像传递给 google vision(text_document) api,以便读取图像并提取文本。但是,在运行 google vision api 时,抛出的错误应该是str、bytes 或 os.PathLike 对象,而不是 JpegImageFile
解决方案
使用代码将 JPEG 文件对象转换为内存视图
buffer = io.BytesIO()
images[i].save(buffer, format='JPEG')
desiredObject = buffer.getbuffer()
return desiredObject
在谷歌视觉代码中,通过使用 to_bytes() 将内存视图转换为字节,将内存视图作为字节传递
client = vision.ImageAnnotatorClient()
content = infile.tobytes()
image = vision.Image(content=content)
推荐阅读
- vb.net - 在VB.NET中获取动态组合框的项目和索引
- javascript - JavaScript。点击一个改变颜色,点击另一个恢复,很多元素,怎么做?
- python - numpy 中是否有 NULL/NIL 值?对于 np.uint16 !在-1旁边?
- angular - 角度/弹性布局不适用于角度 9
- python - 如何使用 python 快速运行脚本或文件,而无需手动输入终端
- google-cloud-build - 是否可以在 Google Cloud Build 中动态生成标签?
- javascript - 反应钩子:输入onChange第一个字符不能删除
- kubernetes - 如何使用跑步车 7
- r - 拆分字符串并获取最后一项
- arduino - 如何在 GSM 网络上发起电话会议?