Search code examples
imagepython-2.7loading-image

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


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.


Solution

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