使用PIL.Image保存带压缩的TIFF图片时触发Too many open files错误
使用PIL保存带压缩TIFF时出现「OSError: [Errno 24] Too many open files」的解决方法
问题背景
在Windows系统(Python 3.10.6、Pillow 9.2.0)下,使用PIL.Image.save()以tiff_lzw或tiff_adobe_deflate格式保存TIFF图片时,循环保存约8187张后会触发OSError: [Errno 24] Too many open files错误。即使使用上下文管理器包裹Image对象、显式调用close()方法,问题依然存在;但改用无压缩(raw)格式则不会出现该错误。
可复现代码:
from PIL import Image import numpy as np fn = "test.tif" compression = "tiff_lzw" for i in range(10000): a = np.array([[0,0],[0,0]], dtype=np.uint8) with Image.fromarray(a) as rawtiff: rawtiff.save(fn, compression = compression) rawtiff.close()
问题原因
Pillow 9.2.0版本在处理带压缩的TIFF保存时存在内部资源泄漏:上下文管理器仅释放了Image对象本身,但压缩处理过程中打开的底层文件句柄未被正确回收,随着循环次数累积,最终触发系统文件句柄上限。
解决方案
1. 手动管理文件句柄
不让Image.save()直接操作文件名,而是手动打开文件对象并传入方法,确保文件句柄被严格关闭:
from PIL import Image import numpy as np fn = "test.tif" compression = "tiff_lzw" for i in range(10000): a = np.array([[0,0],[0,0]], dtype=np.uint8) with Image.fromarray(a) as rawtiff: with open(fn, 'wb') as file_obj: rawtiff.save(file_obj, compression=compression)
2. 强制触发垃圾回收
在每次循环结束后手动调用垃圾回收,强制清理未被自动释放的资源:
from PIL import Image import numpy as np import gc fn = "test.tif" compression = "tiff_lzw" for i in range(10000): a = np.array([[0,0],[0,0]], dtype=np.uint8) with Image.fromarray(a) as rawtiff: rawtiff.save(fn, compression=compression) gc.collect()
3. 升级Pillow版本
该资源泄漏问题已在Pillow后续版本中修复,直接升级到9.5.0及以上版本即可解决:
pip install --upgrade pillow
内容的提问来源于stack exchange,提问作者Enrico88
相关产品推荐
相关产品推荐

