Using python load images from directory and reshape

24,894

Solution 1

Assuming that you have scipy installed and assuming that with "reshape" you actually mean "resize", the following code should load all images from the directory /foo/bar, resize them to 64x64 and add them to the list images:

import os
from scipy import ndimage, misc

images = []
for root, dirnames, filenames in os.walk("/foo/bar"):
    for filename in filenames:
        if re.search("\.(jpg|jpeg|png|bmp|tiff)$", filename):
            filepath = os.path.join(root, filename)
            image = ndimage.imread(filepath, mode="RGB")
            image_resized = misc.imresize(image, (64, 64))
            images.append(image_resized)

If you need a numpy array (to call reshape) then just add images = np.array(images) at the end (with import numpy as np at the start).

Solution 2

  1. Use os.walk() to traverse the directory for images.
  2. Load images using Pillow
  3. Use Image.getdata to get a list of values
  4. Pass that list to numpy.reshape

There's a lot I skipped over. You might have to use a different method than getdata from Pillow but you didn't give a lot of context.

Share:
24,894
verdery
Author by

verdery

Updated on July 09, 2022

Comments

  • verdery
    verdery almost 2 years

    I want to load same images from directory and reshape them using reshape function using python.

    How can i do this?