【发布时间】:2019-01-30 16:44:15
【问题描述】:
我一直致力于使用 Python 3.6.3 和 wand 库设置 PDF 转换为 png 和裁剪脚本。
我试过 Pillow,但它缺少转换部分。我正在尝试提取 alpha 通道,因为我想稍后将图像提供给 OCR,所以我转而尝试this SO answer 中提供的代码。
出现了几个问题:第一个是如果文件很大,我会从终端收到“Killed”消息。第二个是文件看起来相当挑剔,即在命令行中通过 imagemagick 的 convert 或 pdftoppm 正确转换的文件,使用 wand 会引发错误。
不过,我最关心的是第一个,并且非常感谢知识渊博的编码人员的检查。我怀疑它可能来自循环的结构方式:
from wand.image import Image
from wand.color import Color
def convert_pdf(filename, path, resolution=300):
all_pages = Image(filename=path+filename, resolution=resolution)
for i, page in enumerate(all_pages.sequence):
with Image(page) as img:
img.format = 'png'
img.background_color = Color('white')
img.alpha_channel = 'remove'
image_filename = '{}.png'.format(i)
img.save(filename=path+image_filename)
我注意到脚本在进程结束时输出所有文件,而不是一个一个地输出,我猜这可能会给内存带来不必要的负担,并最终导致 SEGFAULT 或类似情况。
感谢您查看我的问题以及任何提示。
【问题讨论】: