Python - OCR - pytesseract 用于 PDF

9

我正在尝试运行以下代码:

import cv2
import pytesseract

img = cv2.imread('/Users/user1/Desktop/folder1/pdf1.pdf')
text = pytesseract.image_to_string(img)
print(text)

这给我带来了以下错误:

Traceback (most recent call last):
  File "/Users/user1/PycharmProjects/project1/python_file.py", line 5, in <module>
    text = pytesseract.image_to_string(img)
  File "/Users/user1/PycharmProjects/project1/venv/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 346, in image_to_string
    return {
  File "/Users/user1/PycharmProjects/project1/venv/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 349, in <lambda>
    Output.STRING: lambda: run_and_get_output(*args),
  File "/Users/user1/PycharmProjects/project1/venv/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 249, in run_and_get_output
    with save(image) as (temp_name, input_filename):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py", line 113, in __enter__
    return next(self.gen)
  File "/Users/user1/PycharmProjects/project1/venv/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 172, in save
    image, extension = prepare(image)
  File "/Users/user1/PycharmProjects/project1/venv/lib/python3.8/site-packages/pytesseract/pytesseract.py", line 142, in prepare
    raise TypeError('Unsupported image object')
TypeError: Unsupported image object

我该如何使其适用于PDF文件?
1个回答

27

这对我有用:

import os
from PIL import Image
from pdf2image import convert_from_path
import pytesseract

filePath = '/Users/user1/Desktop/folder1/pdf1.pdf'
doc = convert_from_path(filePath)
path, fileName = os.path.split(filePath)
fileBaseName, fileExtension = os.path.splitext(fileName)

for page_number, page_data in enumerate(doc):
    txt = pytesseract.image_to_string(Image.fromarray(page_data)).encode("utf-8")
    print("Page # {} - {}".format(str(page_number),txt))


3
我收到错误提示:需要一个字节类似对象,而不是 'PpmImageFile'。 - Sheetal Mangesh Pandrekar
11
如果你遇到了“a bytes-like object is required, not 'PpmImageFile'”这个错误,将倒数第二行改为: txt = pytesseract.image_to_string(page_data).encode("utf-8") - jboi
如果出现以下错误 AttributeError: __array_interface__,则首先将 page_data 转换为 np 数组。 - Amarnath

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接