我在
folder
中有一些图像。我想将所有这些图像存储到一个列表中。图太多了,看完就想关掉图了
我尝试使用
pathlib
这样做:
from pathlib import Path
from PIL import Image
import numpy as np
path = Path(<path-to-folder>)
list_of_images = []
for img_path in path.iterdir():
with Image.open(img_path) as img:
list_of_images.append(img)
但是后来我尝试用这张图片展示或做任何事情并得到这个:
list_of_images[0].show()
导致错误:
AttributeError: 'NoneType' object has no attribute 'seek'
并尝试像这样转换为 numpy 数组:
np.array(list_of_images[0])
返回此:
array(<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x512 at 0x20E01990250>,
dtype=object)
我怎样才能正确地做到这一点?
上面的
with statement
将在嵌套代码块意味着列表中的对象有一些内存地址但实际上数据已经从那里消失后自动关闭文件,因此您可以使用deep copy
方法创建一个PIL.Image.copy
。
from pathlib import Path
from PIL import Image
import numpy as np
path = Path(<path-to-folder>)
list_of_images = []
for img_path in path.iterdir():
with Image.open(img_path) as img:
print(img)
list_of_images.append(img.copy())
或者您可以执行此操作,读取所有图像对象并进行操作,然后正确关闭这些文件。
from pathlib import Path
from PIL import Image
import numpy as np
path = Path(<path-to-folder>)
img_path = [img_path for img_path in path.iterdir()]
list_of_images = []
for img_path in path.iterdir():
list_of_images.append(Image.open(img_path))
# Do something with the images
# ...
list_of_images[0].show()
# Close the images
for image in list_of_images:
image.close()
或者,如果我们调用
convert
函数将此图像对象转换为 RGB(它们可能已经是),它也可以帮助我们解决您的问题,因为 PIL.Image.convert
函数也会返回该对象的副本,即使在上下文结束后您也拥有该对象的副本物体
list_of_images.append(img.convert('RGB'))
在此输入代码