简体   繁体   English

numpy中的4-d数组转置

[英]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. 我有一个4d数组(python),每批图像中有一组10000个图像,每个图像有5个通道。 Each image is 25*25 ie the 4d array shape is 10000*5*25*25. 每个图像是25 * 25,即4d阵列形状是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! 谢谢!

The function numpy.transpose is general enough to handle multi-dimensional arrays. 函数numpy.transpose足以处理多维数组。 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. 但是,它采用可选的axis参数,该参数明确指定重新排列维度的顺序。 To swap the last two dimensions in a 4D array (ie transposing a stack of images): 要交换4D阵列中的最后两个维度(即转置一堆图像):

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

No loops are required, it simply works on the entire 4D array and is super efficient. 不需要循环,它只适用于整个4D阵列,并且非常高效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM