Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Release memory when working with PIL

I'm editing an image with PIL (Python Imaging Library). On each step (convert, rotate, resize ...) there are more images created. (An excerpt from the documentation: "Returns a copy of an image rotated the given number of degrees ...") So I want to release memory.

Do you know whether the following approach saves memory?

import PIL.Image

image = PIL.Image.open('Image.jpg')
garbage = image
image = image.convert('RGB')
del garbage
like image 891
rynd Avatar asked Jul 03 '12 19:07

rynd


1 Answers

You don't need to make the temporary garbage reference.

When the right-hand side of this statement is executed:

image = image.convert('RGB')

a new Python object is created.

By assigning it back to image the old object that image used to represent has its reference count reduced to zero, and is sent to the garbage collector.

However, not related to how Python works, I have seen PIL issues where because of genuine bugs memory leaks have formed. For instance here's a discussion of issues when using Draw text:

PIL Draw Text Memory Leak

I know that's a really old discussion, but I still see that come up sometimes when I use PIL!

like image 108
K. Brafford Avatar answered Sep 19 '22 00:09

K. Brafford