python - numpy 与 python : convert 3d array to 2d

标签 python arrays numpy image-processing computer-vision

假设我有一张彩色图像,自然会用 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/

相关文章:

python - 为什么在 Python 中从自身 (x - x) 中减去一个值?

python - 在 PyQT5 中创建自定义小部件

javascript - 用 `for` 循环替换 `forEach` 循环

JavaScript 仅通过 messageid 将对象创建为数组

python - 检查某些内容是否不在多个列表中 - 如何使其更优雅

python - 如何为 2D 直方图选择自定义 bin 大小?

python - 每个值多个键

python - 无法使用 requests.post 登录网站 - 指定 URL

python - Django Rest Framework 中 CreateAPIView 的权限

numpy - 在pytorch中将索引选定张量添加到另一个具有重叠索引的张量