从目录导入图像 (Python)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26392336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Importing images from a directory (Python)
提问by Charles
Is there any way to import all the images inside a directory (the directory location is known).
I have already found a way of finding out the length of the directory.
What I'm not sure about is how I can import the images (using PIL/Pillow) into either a list or a dictionary.
有什么方法可以导入目录中的所有图像(目录位置已知)。
我已经找到了一种找出目录长度的方法。
我不确定的是如何将图像(使用 PIL/Pillow)导入到列表或字典中。
采纳答案by user1269942
I'd start by using glob:
我首先使用 glob:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)
then do what you need to do with your list of images (image_list).
然后对图像列表 (image_list) 执行您需要执行的操作。
回答by Tony Suffolk 66
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f))
This should work - not tested.
这应该有效 - 未测试。

