2014-11-25 42 views
4

我有以下Python代碼。問題在於內存使用量增長巨大。 鑑於Image.rotate()返回一個新的對象,我會認爲舊的對象不能再有任何引用並被刪除。內存增長雖然被覆蓋了

問題

會發生什麼,我該如何解決這個問題?

代碼

from PIL import Image 
src_im = Image.open("input.png") 
steps = 120 # Works with 3 
angle = 360.0/steps 

rotation = src_im.convert('RGBA') 
for _ in xrange(steps): 
    rotation = rotation.rotate(angle, expand = 1) 

rotation = rotation.crop(rotation.getbbox()).resize(src_im.size) 
rotation.save("out.png") 

這是在Python 2.7.3。 Python 3特定的解決方案是可以接受的。

+2

有趣。我剛剛嘗試過:gc.collect和explicit del,但沒有任何幫助。 – Jiri 2014-11-25 13:36:54

回答

3

的問題是不是內存泄漏,它是expand說法。從枕頭文檔(重點是我的):

expand - 可選擴展標誌。如果爲真,擴大了輸出圖像,使其大到足以容納整個旋轉的圖像

您可以在循環中添加print(rotation.size)大小以查看此內容。輸出:

(852, 646) 
(885, 690) 
(921, 736) 
(959, 784) 
(1000, 834) 
(1043, 886) 
(1089, 940) 
(1138, 996) 
(1190, 1055) 
(1245, 1116) 
(1303, 1180) 
(1364, 1247) 
(1429, 1317) 
(1497, 1390) 
(1568, 1467) 
(1643, 1548) 
(1723, 1632) 
(1807, 1720) 
(1896, 1813) 
(1989, 1910) 
(2087, 2012) 
(2191, 2119) 
(2299, 2231) 
... 

要無邊框切割旋轉圖像,使用expand = 1但隨後立即作物圖像的非阿爾法區域:

for _ in xrange(steps): 
    rotation = rotation.rotate(angle, expand = 1) 
    rotation = rotation.crop(rotation.getbbox()) 
+2

優秀的答案!接受,我將在解決方案編輯與出切斷刃旋轉。 – Unapiedra 2014-11-25 13:46:29