简体   繁体   English

Python PIL:裁剪多个图像会导致冻结和 memory 泄漏

[英]Python PIL: Cropping multiple images leads to freeze up and memory leak

I'm trying to crop multiple images (thousands) with PIL and saving the result to the disk.我正在尝试使用 PIL 裁剪多个图像(数千个)并将结果保存到磁盘。 However, after just cropping a few 100 images and saving them successfully, the program uses 17.5 GB of RAM and takes forever to create the next crop.然而,在仅仅裁剪了 100 张图像并成功保存之后,该程序使用了 17.5 GB 的 RAM,并且需要很长时间才能创建下一个裁剪。 After that, it only outputs two more images with a size of 65535×65535 pixels each (the original images are all 1920x1080) and then the loop is done.之后,它只再输出两张尺寸为 65535×65535 像素的图像(原始图像都是 1920x1080),然后循环完成。

My code:我的代码:

import PIL
from PIL import Image
PIL.Image.MAX_IMAGE_PIXELS = 4294836225

for path in paths:
   with Image.open(path) as img:
      left, top, right, bottom = calculate_crop(...)
      cropped = img.crop((left, top, right, bottom))
      cropped.save(new_path, 'png')
      cropped.close()

No exception is ever fired (I also tried using try/except).没有任何异常被触发(我也尝试过使用 try/except)。 Do I do something wrong here or could this be a bug in the library?我在这里做错了什么或者这可能是图书馆中的错误吗?

Okay according to PIL memory leak github forum the issue is that the handler stops calling the.close() method on the file or at least doesn't do it immediately.好的,根据PIL memory 泄漏 github 论坛问题是处理程序停止调用文件上的.close()方法,或者至少不立即执行。 I would suggest manually opening and closing the file yourself.我建议自己手动打开和关闭文件。 This may only resolve part of the issue however.然而,这可能只能解决部分问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM