如何有效地一个接一个地记忆大量的图像?

时间:2015-05-31 07:27:07

标签: python-2.x pillow

我通过在一定高度自动切割并一个接一个地粘贴块来处理数百个图像。我创建了一个Image实例,其new实例的大小比上一次更高,以便为新块创建空间。当游行完成时,最终结果将保存到文件中。

我现在的问题是这种方法消耗了大量的RAM和Swap,几乎冻结了我的电脑。有没有办法实现我的目标而不消耗大量的RAM?到目前为止,这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

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

我认为你可以直接在PIL中完成所有这些操作,这意味着你只需要在内存中复制一份文件,这样做会更好。

也就是说,它不应该开始交换,除非你有非常大的图像,因为一旦你将新图像加载到内存中,每个图像都应该被垃圾收集,所以可能还有另一个问题。