Importing images from a directory (Python) [closed]

…衆ロ難τιáo~ 提交于 2019-12-17 10:52:37

问题


Is there any way to import all the images inside a directory (the directory location is known).
If it helps, 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.


回答1:


I'd start by using 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).




回答2:


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.



来源:https://stackoverflow.com/questions/26392336/importing-images-from-a-directory-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!