user_3.14
user_3.14

Reputation: 61

transpose on 4-d array in numpy

I have a 4d array (python) with a batch of 10000 images with 5 channels in each image. Each image is 25*25 i.e. the 4d array shape is 10000*5*25*25.

I need to transpose the images. The naive way is with nested loops:

            for i in range(np.shape(img)[0]):
                for j in range(np.shape(img)[1]):
                    img[i, j, :, :] = np.transpose(img[i, j, :, :])

but I'm sure that there is a more efficient way to do this. Do you have any idea?

Thanks!

Upvotes: 5

Views: 5287

Answers (1)

MB-F
MB-F

Reputation: 23637

The function numpy.transpose is general enough to handle multi-dimensional arrays. By default it reverses the order of dimensions.

However, it takes an optional axis argument, which explicitly specifies the order in which to rearrange the dimensions. To swap the last two dimensions in a 4D array (i.e. transposing a stack of images):

np.transpose(x, [0, 1, 3, 2])

No loops are required, it simply works on the entire 4D array and is super efficient.

Some more examples:

np.transpose(x, [0, 1, 2, 3])  # leaves the array unchanged
np.transpose(x, [3, 2, 1, 0])  # same as np.transpose(x)
np.transpose(x, [0, 2, 1, 3])  # transpose a stack of images with channel in the last dim

Upvotes: 8

Related Questions