3

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.

adsbawston
  • 55
  • 1
  • 1
  • 5

4 Answers4

11

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()
The Falvert
  • 173
  • 1
  • 5
  • The library [Pillow](https://pillow.readthedocs.io/en/stable/installation.html) should now be used. See also https://stackoverflow.com/a/39985729/6281925. – ksyrium May 08 '23 at 10:05
1

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

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)
saurabh kumar
  • 506
  • 4
  • 13
0

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)
Vishnuvardhan Janapati
  • 3,088
  • 1
  • 16
  • 25