【问题标题】:'list' object has no attribute 'read' facing this error in pdf2image'list' 对象没有属性 'read' 在 pdf2image 中面临此错误
【发布时间】:2020-07-16 04:21:55
【问题描述】:

我有这个代码

tex=pytesseract.image_to_string(Image.open(pdf2image.convert_from_path(PDF_PATH)),lang='mar')

我想做这样的事情

tex=pytesseract.image_to_string(Image.open(image_path),lang='mar')

代码

from PIL import Image
import pytesseract
import cv2
#import cv
import os
import pdf2image
import time
#from pikepdf import Pdf,PdfImage,Name
#defpdftopil()
PDF_PATH=r'C:\Users\Downloads\ViewPDF (1)_one_page.pdf'
img=pdf2image.convert_from_path(PDF_PATH)
tex=pytesseract.image_to_string(Image.open(pdf2image.convert_from_path(PDF_PATH)),lang='mar')
print(tex)
cv2.nameWindow("Input image")
cv2.imshow("input Image",img)
cv2.waitKey(0)
cv2.destroyWindow("Test")
cv2.destroyWindow("Main")

错误

Traceback (most recent call last):
  File "D:\System\p\Python\lib\site-packages\PIL\Image.py", line 2882, in open
    fp.seek(0)
AttributeError: 'list' object has no attribute 'seek'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\ocr.py", line 12, in <module>
    tex=pytesseract.image_to_string(Image.open(pdf2image.convert_from_path(PDF_PATH)),lang='mar')
  File "D:\System\p\Python\lib\site-packages\PIL\Image.py", line 2884, in open
    fp = io.BytesIO(fp.read())
AttributeError: 'list' object has no attribute 'read'

【问题讨论】:

  • pdf2image.convert_from_path 返回一个list,其中包含文档每一页的图像对象。期望的行为是什么,您是要遍历每张图像还是只取第一个?
  • 在这是一个可行的问题之前,您还有一些分析工作要做。请提供预期的 [最小的、可重现的示例](stackoverflow.com/help/minimal-reproducible-example)。显示中间结果与您的预期不同的地方。特别是,跟踪fp——您显然希望它是一个列表,但您的代码为其分配了一个列表。这种差异是如何产生的?
  • 你试图在一行中做太多事情。将错误行分成不同的部分,然后您应该能够检测出导致错误的确切命令。

标签: python image pdf processing


【解决方案1】:

线,

    pdf2image.convert_from_path(PDF_PATH)

返回一个图像列表,每个页面一个。 pdf2image 项目描述 (https://pypi.org/project/pdf2image/) 指出:

    images = convert_from_path('/home/belval/example.pdf')

其中 images 将是代表 PDF 文档每一页的 PIL Image 列表。

解决方案

PIL 函数 Image.open() 需要图像,而不是列表。因此,您可以做以下两件事之一:

  1. 遍历 convert_from_path() 方法返回的列表,并将每个列表项(读取:每个图像)传递给 pytesseract.image_to_string()
  2. 如果您确定您的 pdf 仅包含一页,只需访问 convert_from_path() 方法返回的列表的第一个索引

【讨论】:

    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多