Sarthak
Sarthak

Reputation: 1168

Reshape array in numpy

I have a numpy array of size 5000x32x32x3. The number 5000 is the number of images and each image is 32x32 in width and height and has 3 color channels.

Now I would like to create a numpy array of shape 5000x3x32x32 in a way that the data is preserved. What I mean by preserving data is :

  1. There should be 5000 data points in the resulting array
  2. The 2nd dimension (3) of the array correctly determines the color channel i.e all the elements whose 2nd dimension is 0 belong to red channel, whose 2nd dimension is 1 belong to green channel,whose 2nd dimension is 2 belong to blue channel.

Simply reshaping the by np.reshape(data,(5000,3,32,32)) would not work as it would not preserve the channels but just reshape the data into the desired shape.

Upvotes: 3

Views: 3077

Answers (1)

Learning is a mess
Learning is a mess

Reputation: 8277

I think you are looking for a permutation of the axes, numpy.transpose can get this job done:

data = np.transpose( data, (0, 3, 1, 2))

Upvotes: 6

Related Questions