“变换"Numpy Array:移动维度 [英] "Transform" Numpy Arrray: Move Dimension
问题描述
我正在创建数组 a:
import numpy as np
a = np.zeros((3, 10, 10), np.uint8)
a[1,5,5] = 255
中心有一个红点,其中RGB是第一维.然后我使用 matplotlib 绘制它:
with a red dot in the center, where the RGB is the first dimension. Then I plot it using matplotlib:
import matplotlib.pyplot as plt
plt.imshow(a)
但这当然不起作用,因为 imshow 需要一个维度为 (10, 10, 3) 的数组,而我正在向它提供一个维度为 (3, 10, 10) 的数组.我怎么能翻转"数组,使 RGB 是第三维,而不是第一维?
But of course this doesn't work because imshow expects an array with dimensions (10, 10, 3) and I am feeding it an array with dimensions (3, 10, 10). How could I 'flip' the array so that the RGB is the third dimension, instead of the first?
推荐答案
你需要的是swapaxes
.
import numpy as np
a = np.zeros((3, 10, 10), np.uint8)
print(a.shape) #(3,10,10)
print(np.swapaxes(a,0,2).shape) #(10,10,3)
请参阅文档.
np.swapaxes(a,0,2)
等于 np.transpose(a, (2,1,0))
.
还有一个选项是 np.transpose(a, (1,2 0))
.
与往常一样,转置矩阵可以有两个版本,它们产生相似的结果,但具有不同的 3 维旋转对称性.
As always, transpose matrix can have two versions which produce similar result but with different 3-dimensional rotational symmetry.
这取决于镜像矩阵是否影响你的结果,你应该仔细测试它是否有区别.
It depends on if the mirror matrix affect your result, you should carefully test if it makes difference.
这篇关于“变换"Numpy Array:移动维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!