Importing images from a directory (Python) to list or dictionary

PythonPython Imaging-Library

Python Problem Overview


I am trying to import all the images inside a directory (the directory location is known).

path = /home/user/mydirectory

I already know 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, so they can be properly manipulated.

Python Solutions


Solution 1 - Python

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).

Solution 2 - Python

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)))
   

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharlesView Question on Stackoverflow
Solution 1 - Pythonuser1269942View Answer on Stackoverflow
Solution 2 - PythonTony Suffolk 66View Answer on Stackoverflow