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

79.4k views Asked by At

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.

4

There are 4 answers

1
The Falvert On BEST ANSWER

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()
0
saurabh kumar On

You can use glob and imageio python packages to achieve the same. Below is code in python 3:

import glob
import imageio

for image_path in glob.glob("<your image directory path>\\*.png"):
    im = imageio.imread(image_path)
    print (im.shape)
    print (im.dtype)
0
Vishnuvardhan Janapati On

If you have images in your google drive, and want to load, resize and save the images, then the following code works well.

import os, sys
from os import listdir

from PIL import Image
from google.colab import drive
import matplotlib.pyplot as plt
drive.mount('/content/gdrive')

# need to enter password to access your google drive

from google.colab import files
main_dir = "/content/gdrive/My Drive/Panda/"
files = listdir(main_dir)
# you can change file extension below to read other image types
images_list = [i for i in files if i.endswith('.jpg')] ## output file names only

for idx,image in enumerate(images_list):
  print(idx)
  img = Image.open(main_dir + image)
  #print(img.size)
  #plt.imshow(img)
  img = img.resize((480, 600))
  img.save(main_dir + image)
0
Holomorphic Guy On

pip install ThreadedFileLoader
You can use ThreadedFileLoader module. It uses threading to load images.

from ThreadedFileLoader.ThreadedFileLoader import *

instance = ThreadedImageLoader("path_to_folder/*.jpg")
instance.start_loading()
images = instance.loaded_objects
print(len(images))
print(images[0].shape)