3

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.

4
  • 1
    Have you looked into: numpy.swapaxes docs.scipy.org/doc/numpy/reference/generated/… . It should be doable by two axes transpositions. Commented Feb 14, 2017 at 18:15
  • 3
    Actually np.transpose(data, (0,3,1,2)) should do what you want. Commented Feb 14, 2017 at 18:17
  • @Learningisamess you should write as an answer.. Commented Feb 14, 2017 at 18:22
  • Today I decided to gave up fighting with Numpy and its notion of shape and table. I prefer to avoid to contact directly with it (:-) whenever possible. Sometimes, a simple program became mess when I have to .data or pass in numpy format. Panda knows it better than me, then I talk with him and to_numpy!. Commented Jun 7, 2020 at 4:46

1 Answer 1

6

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. It helped!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.