evolved
evolved

Reputation: 2210

Create numpy array consisting of multiple images

I have multiple images (they are of the same size) which I want to put in a numpy array so that the result is a array of dimension (len(img_list), 1).

img_list = [img, img, img]
img.shape, type(img_list), len(img_list)

((1056, 2034, 3), list, 3)

My main problem is that the following happens when I use numpy.array():

a = np.array(img_list, dtype=np.object)
type(a), a.dtype, a.shape, a.ndim

(numpy.ndarray, dtype('O'), (3, 1056, 2034, 3), 4)

Notice the dimensions is four, instead of two as expected.

So far the best method I found to get dimension (len(img_list), 1) is to create an empty array of the desired dimension and then use broadcasting:

a = np.empty((3,1), dtype=np.object)
type(a), a.dtype, a.shape, a

(numpy.ndarray, dtype('O'), (3, 1), array([[None], [None], [None]], dtype=object))

a[:,0] = img_list
type(a), a.dtype, a.shape

(numpy.ndarray, dtype('O'), (3, 1))

This yield the desired dimension.

Is there a numpy function that can do that directly without creating an empty array first?


EDIT

I thought using numpy.hstack or numpy.stack should do the trick but this results in the "wrong" dimension:

a_stacked = np.stack(img_list)
type(a_stacked), a_stacked.dtype, a_stacked.shape, a.ndim

(numpy.ndarray, dtype('uint8'), (3, 1056, 2034, 3), 4)

To clarify: I would like a.ndim == 2 and not a.ndim == 4. In other words, a.shape should be (3,1) and not (3, 1056, 2034, 3).

Upvotes: 0

Views: 542

Answers (1)

Stormwaker
Stormwaker

Reputation: 391

I'm not sure what you want to achieve, but wouldn't numpy.stack() do? That's how I usually create batches of images.

Upvotes: 1

Related Questions