我结合使用 python 和 PyPDF2 编写了一个脚本, PIL和 pytesseract从 the scanned pages 的第一页中提取文本的 pdf文件。但是,当我尝试使用以下脚本从 first scanned page 中获取内容时从那个pdf文件,当到达包含 img = Image.open(pdfReader.getPage(0)).convert('L') 的行时抛出以下错误.
到目前为止我尝试过的脚本:
import PyPDF2
import pytesseract
from PIL import Image
pdfFileObj = open(r'C:\Users\WCS\Desktop\Scan project\Scanned.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
img = Image.open(pdfReader.getPage(0)).convert('L')
imagetext = pytesseract.image_to_string(img)
print(imagetext)
pdfFileObj.close()
我遇到的错误:
Traceback (most recent call last):
File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\SO.py", line 8, in <module>
img = Image.open(pdfReader.getPage(0)).convert('L')
File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 2554, in open
fp = io.BytesIO(fp.read())
AttributeError: 'PageObject' object has no attribute 'read'
我怎样才能让它成功?
请您参考如下方法:
需要先把pdf转成图片再做
Python: Extract a page from a pdf as a jpeg
import PyPDF2
import pytesseract
from PIL import Image
from pdf2image import convert_from_path
pdfFileObj = r'C:\Users\WCS\Desktop\Scan project\Scanned.pdf'
pages = convert_from_path(pdfFileObj, 500)
page = pages[0]
page.save('out.png')
img = Image.open('out.png').convert('L')
imagetext = pytesseract.image_to_string(img)
print(imagetext)
pdfFileObj.close()
