0

I want to read from many sample images, and make 2D numpy array that row "i" corresponds to i'th sample, and column j correspond to j'th pixel of image(all pixels of a 12*13 image is saved by a list of 156 numbers)

import numpy as np
images = np.array([])
for Letter in "ABCDEFGHIJKLMNO":
    im = Image.open("ABCDEFGHIJKLMNO\\16\\"+Letter+".bmp")
    sampleimage = list(im.getdata())
    images = np.append(images,[sampleimage])

however I struggling making 2D numpy array. above "images" array become an (1800,) array insted of (11,156) . I tried many differend ways but none of them working properly or efficient (making 2D python list and then converting to numpy array is not efficient. although even that solution doesn't work).

so my question is, what is the best way of creating a 2D numpy array on the fly?

1
  • np.append is hard to use correctly, and even then is slow. Reread the np.append docs. Without an axis parameter it flattens the inputs, hence your result. Commented Jul 5, 2018 at 16:41

1 Answer 1

1

You are treating the numpy array images like an list. Have a look at numpy.stack. But in my memory the fastest way is to convert each image to an numpy array, aggregate them in a list and then turn the list into an array.

import numpy as np
images = list()
for Letter in "ABCDEFGHIJKLMNO":
    im = Image.open("ABCDEFGHIJKLMNO\\16\\"+Letter+".bmp")
    sampleimage = np.array(im.getdata())
    images.append(sampleimage)
images_array = np.array(images)

In your case the resulting array should have the size [1800,11,156] or [11,156,1800]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.