ZAR
ZAR

Reputation: 2736

Numpy reshape image data into batches

I'm having a Numpy shape issue. I have a batch of 128x128x3 images and I am trying to reshape my list to be of shape batch_size x 128 x 128 x 3.

Let's walk through what I have so far.

We have a batch of 3 lists that include the image and some other meta data. Visually:

my_data

|row|raw_image|meta_data1|meta_data2| 
-------------------------------------
|1  |128x128x3|8685      |'here'    |
-------------------------------------
|2  |128x128x3|8402      |'there'   |
-------------------------------------
|3  |128x128x3|5498      |'where'   |

print(my_data.shape) #(3,4)

We only want to grab the raw_image data:

image_data = my_data[:, 1]
print(image_data.shape) #(3,)
print(image_data[0].shape) #(128,128,3)

I would think that image_data would already be in 3x128x128x3, however I am getting errors, such as:

ValueError: Error when checking: expected input_1 to have 4 dimensions, but got array with shape (384, 128, 3)

or

ValueError: Error when checking: expected input_1 to have 4 dimensions, but got array with shape (3, 1)

I've tried reshaping, like so:

np.reshape(image_data, (3, 128, 128, 3))

But get the following error:

ValueError: cannot reshape array of size 3 into shape (3,128,128,3)

So, how should I proceed? I've tried combinations with vstack, reshape, extend dim, removing a dim...

Upvotes: 1

Views: 3125

Answers (1)

akuiper
akuiper

Reputation: 214927

The image_data is an array of objects, you can merge them using np.stack(image_data); This should stack all images inside image_data by the first axis and create the 4d array as you need.

Upvotes: 2

Related Questions