Release memory when working with PIL

吃可爱长大的小学妹 提交于 2019-12-23 08:57:34

问题


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

回答1:


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!



来源:https://stackoverflow.com/questions/11317847/release-memory-when-working-with-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!