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
- Use
os.walk()
to traverse the directory for images. - Load images using Pillow
- Use Image.getdata to get a list of values
- 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.
Author by
verdery
Updated on July 09, 2022Comments
-
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?