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

Charles picture Charles · Oct 15, 2014 · Viewed 160.5k times · Source

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.

Answer

user1269942 picture user1269942 · Oct 15, 2014

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