简体   繁体   English

在 Pillow 中打开和加载图像时出现“打开的文件太多”错误

[英]“Too many open files” error when opening and loading images in Pillow

When running the following code:运行以下代码时:

KEEP=[]
for file in glob.glob("./KEEP/thing*.[tT][iI][fF]"):
    m = pattern.search(file)
    filename=m.group(1)
    keep=Image.open(file)
    keep.load()
    KEEP.append(keep)
    KEEP_NAMES.append(filename)
    keep.close()

over more than a thousand files, I get the error message:超过一千个文件,我收到错误消息:

Traceback (most recent call last):
  File "/hom/yannis/texmf/python/remove-harakat.py", line 123, in <module>
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2237, in open
IOError: [Errno 24] Too many open files: './KEEP/thing1118_26.TIF'

I don't understand why this is happening, since I'm load()ing and then close()ing all files, why should they remain open?我不明白为什么会发生这种情况,因为我正在加载()然后关闭()所有文件,为什么它们应该保持打开状态? Is there a solution to this problem, other than reducing the number of files (which is not an option for me)?除了减少文件数量(这对我来说不是一个选择)之外,是否有解决此问题的方法? Some way to close them after their contents have been read in memory?在内存中读取内容后关闭它们的某种方法?

This may be a bug with the Image.load method - see Pillow issue #1144 .这可能是Image.load方法的错误 - 请参阅Pillow issue #1144 I ran into the same too many open files error - see #1237 .我遇到了同样的too many open files错误 - 请参阅#1237

My work-around was to load the image into a temp object, make a copy, and then explicitly close the temp.我的解决方法是将图像加载到临时对象中,进行复制,然后明确关闭临时对象。 For your code it would look something like this:对于您的代码,它看起来像这样:

KEEP=[]
for file in glob.glob("./KEEP/thing*.[tT][iI][fF]"):
    m = pattern.search(file)
    filename = m.group(1)
    temp = Image.open(file)
    keep = temp.copy()
    KEEP.append(keep)
    KEEP_NAMES.append(filename)
    temp.close()

I also ran into this issue and resolved the issue with a slightly different approach.我也遇到了这个问题,并用稍微不同的方法解决了这个问题。

This workaround uses copy.deepcopy() , which is based on similar logic of @indirectlylit's solution but avoids creating of temp .此解决方法使用copy.deepcopy() ,它基于copy.deepcopy()解决方案的类似逻辑,但避免创建temp See code snippet below请参阅下面的代码片段

import copy

KEEP=[]
for file in glob.glob("./KEEP/thing*.[tT][iI][fF]"):
    m = pattern.search(file)
    filename = m.group(1)
    keep = copy.deepcopy(Image.open(file))
    KEEP.append(keep)
    KEEP_NAMES.append(filename)

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

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