本文介绍了numpy 与 python:将 3d 数组转换为 2d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个彩色图像,自然这将在 python 中用一个 3 维数组表示,比如形状 (n x m x 3) 并称之为 img.

Say that I have a color image, and naturally this will be represented by a 3-dimensional array in python, say of shape (n x m x 3) and call it img.

我想要一个新的二维数组,将其命名为narray"以具有形状 (3,nxm),以便该数组的每一行分别包含 R、G 和 B 通道的展平"版本.此外,它应该具有我可以通过类似

I want a new 2-d array, call it "narray" to have a shape (3,nxm), such that each row of this array contains the "flattened" version of R,G,and B channel respectively. Moreover, it should have the property that I can easily reconstruct back any of the original channel by something like

narray[0,].reshape(img.shape[0:2])    #so this should reconstruct back the R channel.

问题是如何从img"构造narray"?简单的 img.reshape(3,-1) 不起作用,因为元素的顺序对我来说是不可取的.

The question is how can I construct the "narray" from "img"? The simple img.reshape(3,-1) does not work as the order of the elements are not desirable for me.

谢谢

推荐答案

您需要使用 np.transpose 重新排列维度.现在,nxmx 3要转换成3 x (n*m),所以把最后一个轴往前移,剩下的轴顺序右移(0,1).最后,重塑为 3 行.因此,实现将是 -

You need to use np.transpose to rearrange dimensions. Now, n x m x 3 is to be converted to 3 x (n*m), so send the last axis to the front and shift right the order of the remaining axes (0,1). Finally , reshape to have 3 rows. Thus, the implementation would be -

img.transpose(2,0,1).reshape(3,-1)

样品运行 -

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]])

这篇关于numpy 与 python:将 3d 数组转换为 2d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:44