我正在使用pytesseract对图像进行OCR。我有3-4页长的pdf报表.我需要一种方法来将它们转换为多个..jpg/..png图像,并对这些图像逐个转换为OCR。到目前为止,我正在将单个页面转换为图像,然后运行
text=str(pytesseract.image_to_string(Image.open("imagename.jpg"),lang='eng'))
之后,我使用regex提取信息并创建一个dataframe。所有页面的regex逻辑都是相同的。可以理解的是,如果我可以在一个循环中读取图像文件,这个过程就可以对任何以相同格式出现的pdf进行自动化处理。
发布于 2020-06-17 14:09:41
PyMuPDF将是循环遍历图像文件的另一种选择。以下是如何实现这一目标:
import fitz
from PIL import Image
import pytesseract
input_file = 'path/to/your/pdf/file'
pdf_file = input_file
fullText = ""
doc = fitz.open(pdf_file) # open pdf files using fitz bindings
### ---- If you need to scale a scanned image --- ###
zoom = 1.2 # scale your pdf file by 120%
mat = fitz.Matrix(zoom, zoom)
noOfPages = doc.pageCount
for pageNo in range(noOfPages):
page = doc.loadPage(pageNo) # number of pages
pix = page.getPixmap(matrix = mat) # if you need to scale a scanned image
output = '/path/to/save/image/files' + str(pageNo) + '.jpg'
pix.writePNG(output) # skip this if you don't need to render a page
text = str(((pytesseract.image_to_string(Image.open(output)))))
fullText += text
fullText = fullText.splitlines() # or do something here to extract information using regex
这是非常方便取决于你想如何处理pdf文件。有关PyMuPDF的更详细信息,这些链接可能会有所帮助:PyMuPDF教程和用于PyMuPDF的git
希望这能有所帮助。
使用编辑的另一种更简单的方法是,如果您有一个干净的PDF文件格式,那么直接解释返回转换的文本,在page = doc.loadPage(pageNo)
完成以下操作后就足够了:
blocks = page.getText("blocks")
blocks.sort(key=lambda block: block[3]) # sort by 'y1' values
for block in blocks:
print(block[4]) # print the lines of this block
免责声明:以上使用blocks
的想法来自于回购维护人员。更详细的信息可以在这里找到:关于git的几个问题
发布于 2020-06-17 13:09:02
对我来说,下面的作品
from wand.api import library
from wand.image import Image
with Image(filename=r"imagepath.pdf", resolution=300) as img:
library.MagickResetIterator(img.wand)
for idx in range(library.MagickGetNumberImages(img.wand)):
library.MagickSetIteratorIndex(img.wand, idx)
img.save(filename="output.tiff")
现在的问题是,如果我提取为
text=str(pytesseract.image_to_string(Image.open("test.tiff"),lang='eng'))
它只会在第一页
https://stackoverflow.com/questions/62429161
复制相似问题