首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当ImageMagick和PyPDF2一起使用时,Python会崩溃

当ImageMagick和PyPDF2一起使用时,Python会崩溃
EN

Stack Overflow用户
提问于 2019-02-04 00:33:56
回答 1查看 141关注 0票数 0

我有一个PDF文件由大约20-25页组成。这个工具的目的是将PDF文件分割成页面(使用PyPdf2),将每个PDF页面保存在一个目录中(使用PyPdf2),将PDF页面转换为图像(使用ImageMagick),然后使用tesseract (使用PIL和PyOCR)对它们执行一些光学字符识别以提取数据。该工具最终将是通过tkinter的GUI,因此用户可以通过单击按钮多次执行相同的操作。在我的大量测试中,我注意到如果整个过程重复大约6-7次,工具/python脚本就会崩溃,并在Windows上显示无响应。我已经执行了一些调试,但不幸的是没有抛出错误。内存和CPU都很好,所以也没有问题。我能够缩小问题的范围,因为我观察到,在到达tesseract部分之前,当PyPDF2和ImageMagick一起运行时,它们都失败了。我能够通过将其简化为以下Python代码来复制该问题:

代码语言:javascript
复制
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块,但没有捕获到错误。另外,我使用的是所有库的最新版本。任何帮助或指导我们都将不胜感激。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-07 19:00:46

对于将来的参考,这个问题是由于其中一条评论中提到的32位版本的ImageMagick造成的(多亏了emcconville)。卸载Python和ImageMagick 32位版本并安装这两个64位版本修复了该问题。希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54505052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档