2015-05-31 60 views
0

我正在處理數百個圖像,通過在特定高度自動切割並依次粘貼大塊圖像。我創建了一個新的Image實例,其中new的尺寸比上一次更大,以便爲新塊創建空間。處理完成後,最終結果將保存到文件中。如何一次又一次地將大塊圖像粘貼到內存中?

我現在的問題是,這種方法是消耗大量的RAM和交換,幾乎凍結我的電腦。有沒有一種方法來實現我的目標,而不消耗大量的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 

回答

0

你是第一個加載CV的圖像,然後也使圖像中的每一行的列表作爲列表,顯然才發現它的寬度,然後你裁剪它,然後你製作一個PIL圖像。

我認爲你可以直接在PIL中完成所有這些,這意味着你只需要在內存中拷貝一份文件,這樣做會更好。

也就是說,它不應該開始交換,除非您有嚴重的巨大圖像,因爲每次將圖像加載到內存中時都應該對每個圖像進行垃圾回收,因此可能會涉及到另一個問題。

相關問題