1

I am using numpy and matplotlib to import images in python. I would like to crate a 3d array, such that in the 1th and 2th axis I have pixels values and in the 0th axis I have the image number. So far I got something like this:

from PIL import Image                                                            
import numpy                                                                     
import matplotlib.pyplot as plt                                                  
import glob

imageFolderPath = '/home/B/Pictures/'
imagePath = glob.glob(imageFolderPath+'/*.JPG') 

im_array = numpy.array(Image.open(imagePath[0]).convert('L'), 'f')               
im_array = numpy.expand_dims(im_array, axis=0)                                   

for c in range(1, len(imagePath)):                                               
     im_array_new = numpy.array(Image.open(imagePath[c]).convert('L'), 'f')       
     im_array_new = numpy.expand_dims(im_array_new, axis=0)                       
     im_array = numpy.append(im_array, im_array_new, axis=0)  

this work, but it is someway ugly. I don't like the fact that I have to expand the dimension of a 2d Array and then append them together. Is there a more elegant way to do that in python? Possibly without having to preallocate a huge 3d array (n photos, x dimension, y dimension)

1 Answer 1

4

Instead of a for loop you could make an array out of the list comprehension:

from PIL import Image                                                            
import numpy                                                                     
import glob

imageFolderPath = '/home/B/Pictures/'
imagePath = glob.glob(imageFolderPath + '/*.JPG') 

im_array = numpy.array( [numpy.array(Image.open(img).convert('L'), 'f') for img in imagePath] )
Sign up to request clarification or add additional context in comments.

1 Comment

this is by far more elegant then mine. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.