python 2.x -如何有效地粘贴图像块一个接一个的内存



我正在处理几百张图像,在一定高度自动剪切它们,然后一个接一个地粘贴块。我用new创建了一个新的Image实例,它的大小比上次要大,以便为新块腾出空间。当处理完成后,最终结果被保存到一个文件中。

我现在的问题是这种方法消耗了大量的RAM和Swap,几乎冻结了我的计算机。有没有一种方法可以在不消耗大量内存的情况下实现我的目标?到目前为止,这是我的代码:

import SimpleCV as cv
import argparse
import PIL
from os.path import join, abspath
parser = argparse.ArgumentParser(
    description=("Process many images and paste the chunks into a final image"))
# ...code removed for brevity...
argv = parser.parse_args()
rango_inicio = int(argv.rango.split(":")[0])
rango_fin = int(argv.rango.split(":")[1])
img = None
for pag in xrange(rango_inicio, rango_fin + 1):
    numero = format(pag, '0' + argv.relleno)
    pagina = join(
        argv.dir_entrada, argv.prefijo + numero + '.' + argv.extension)
    pagina = abspath(pagina)
    print(pagina)
    imagen = cv.Image(pagina)
    fs = sorted(imagen.findLines(), key=lambda f: f.width())[-1]
    if fs.width() >= 598:
        cropped = imagen.crop(0, fs.y, imagen.width, imagen.height)
        if not img:
            img = PIL.Image.new("RGB", (cropped.width, cropped.height))
            croppedraw = cropped.getPIL()
            img.paste(croppedraw, (0, 0))
        else:
            croppedraw = cropped.getPIL()
            imgtmp = img.copy()
            img = PIL.Image.new(
                "RGB", (imgtmp.size[0], imgtmp.size[1] + cropped.height))
            img.paste(imgtmp, (0, 0))
            img.paste(croppedraw, (0, imgtmp.size[1]))
# and save the final image

您首先在CV中加载图像,然后还将图像中的每一行作为列表制作列表,显然只是为了找到它的宽度,然后您裁剪它,然后您从中制作PIL图像。

我认为您可以直接在PIL中完成所有这些,这意味着您只需要内存中的文件副本,使其更好。

也就是说,它无论如何都不应该开始交换,除非您有非常大的图像,因为一旦将新图像加载到内存中,每个图像都应该被垃圾收集,因此可能会涉及到另一个问题。

最新更新