ImageMagick和PyPDF2在一起使用时崩溃Python

2024-03-29 09:37:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大约20-25页的PDF文件。此工具的目的是将PDF文件拆分为页面(使用PyPdf2),将每个PDF页面保存在目录中(使用PyPdf2),将PDF页面转换为图像(使用ImageMagick),然后使用tesseract(使用PIL和PyOCR)对其执行OCR以提取数据。该工具最终将成为一个通过tkinter的GUI,这样用户可以通过点击按钮多次执行相同的操作。在整个繁重的测试过程中,我注意到,如果整个过程重复6-7次左右,tool/python脚本就会崩溃,在Windows上显示没有响应。我已经进行了一些调试,但不幸的是没有抛出错误。内存和CPU都很好,所以没有问题。我观察到,在到达tesseract部分之前,PyPDF2和ImageMagick在一起运行时出现故障,从而缩小了问题的范围。通过将问题简化为以下Python代码,我得以复制该问题:

from wand.image import Image as Img
from PIL import Image as PIL
import pyocr
import pyocr.builders
import io, sys, os 
from PyPDF2 import PdfFileWriter, PdfFileReader


def splitPDF (pdfPath):
    #Read the PDF file that needs to be parsed.
    pdfNumPages =0
    with open(pdfPath, "rb") as pdfFile:
        inputpdf = PdfFileReader(pdfFile)

        #Iterate on every page of the PDF.
        for i in range(inputpdf.numPages):
            #Create the PDF Writer Object
            output = PdfFileWriter()
            output.addPage(inputpdf.getPage(i))
            with open("tempPdf%s.pdf" %i, "wb") as outputStream:
                output.write(outputStream)

        #Get the number of pages that have been split.
        pdfNumPages = inputpdf.numPages

    return pdfNumPages

pdfPath = "Test.pdf"
for i in range(1,20):
    print ("Run %s\n--------" %i)
    #Split the PDF into Pages & Get PDF number of pages.
    pdfNumPages = splitPDF (pdfPath)
    print(pdfNumPages)
    for i in range(pdfNumPages):
        #Convert the split pdf page to image to run tesseract on it.
        with Img(filename="tempPdf%s.pdf" %i, resolution=300) as pdfImg:
            print("Processing Page %s" %i) 

我使用了with语句来正确处理文件的打开和关闭,因此应该没有内存泄漏。我试过分别运行分割部分和图像转换部分,单独运行时效果很好。然而,当这些代码组合在一起时,它将在迭代大约5-6次后失败。我使用了try和exception块,但是没有捕获错误。而且我使用的是所有库的最新版本。任何帮助或指导都将不胜感激。你知道吗

谢谢你。你知道吗


Tags: 文件thetofromimportpilpdfas
1条回答
网友
1楼 · 发布于 2024-03-29 09:37:14

为了将来的参考,这个问题是由于32位版本的ImageMagick中提到的一个评论(感谢emcconville)。卸载Python和ImageMagick 32位版本并安装这两个64位版本修复了问题。希望这有帮助。你知道吗

相关问题 更多 >