问题描述
我正在用PIL(Python Imaging Library)编辑图像。在每一步(转换,旋转,调整大小...)都会创建更多图像。 (摘自文档:返回图像的副本旋转给定的度数...)所以我想释放内存。
你知道吗是否以下方法节省内存?
import PIL.Image
image = PIL.Image.open ('Image.jpg')
garbage = image
image = image.convert('RGB')
del垃圾
您不需要创建临时垃圾
引用。
执行此语句的右侧时:
image = image.convert('RGB')
创建一个新的Python对象。
通过将它分配回 image
image
用于表示它的引用计数减为零,并发送到垃圾收集器。
然而,与Python的工作方式无关,我见过PIL问题由于真正的bug而造成内存泄漏。例如,这里讨论使用绘图文本时的问题:
我知道这是一个很老的讨论,但我仍然当我使用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
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:
I know that's a really old discussion, but I still see that come up sometimes when I use PIL!
这篇关于使用PIL时释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!