假设我有一张彩色图像,自然会用 Python 中的 3 维数组表示,形状为 (n x m x 3) 并将其称为 img。
我想要一个新的二维数组,将其称为“narray”,形状为 (3,nxm),这样该数组的每一行分别包含 R、G 和 B channel 的“展平”版本。此外,它应该具有我可以通过类似的方式轻松重建任何原始 channel 的属性
narray[0,].reshape(img.shape[0:2]) #so this should reconstruct back the R channel.
问题是如何从“img”构建“narray”?简单的 img.reshape(3,-1) 不起作用,因为我不希望元素的顺序。
谢谢
最佳答案
您需要使用 np.transpose
重新排列尺寸。现在,n x m x 3
将被转换为 3 x (n*m)
,因此将最后一个轴放在前面并将其余轴的顺序右移 (0,1)
。最后, reshape 为 3
行。因此,实现将是 -
img.transpose(2,0,1).reshape(3,-1)
sample 运行-
In [16]: img
Out[16]:
array([[[155, 33, 129],
[161, 218, 6]],
[[215, 142, 235],
[143, 249, 164]],
[[221, 71, 229],
[ 56, 91, 120]],
[[236, 4, 177],
[171, 105, 40]]])
In [17]: img.transpose(2,0,1).reshape(3,-1)
Out[17]:
array([[155, 161, 215, 143, 221, 56, 236, 171],
[ 33, 218, 142, 249, 71, 91, 4, 105],
[129, 6, 235, 164, 229, 120, 177, 40]])
关于python - numpy 与 python : convert 3d array to 2d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32838802/