How to load images from a directory on the computer in Python

adsbawston picture adsbawston · Apr 21, 2016 · Viewed 63.3k times · Source

Hello I am New to python and I wanted to know how i can load images from a directory on the computer into python variable. I have a set of images in a folder on disk and I want to display these images in a loop.

Answer

The Falvert picture The Falvert · Apr 21, 2016

You can use PIL (Python Imaging Library) http://www.pythonware.com/products/pil/ to load images. Then you can make an script to read images from a directory and load them to python, something like this.

#!/usr/bin/python
from os import listdir
from PIL import Image as PImage

def loadImages(path):
    # return array of images

    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        img = PImage.open(path + image)
        loadedImages.append(img)

    return loadedImages

path = "/path/to/your/images/"

# your images in an array
imgs = loadImages(path)

for img in imgs:
    # you can show every image
    img.show()