首页 > 解决方案 > 如何将 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

标签: python-3.xgoogle-vision

解决方案


使用代码将 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)

推荐阅读