numpy 与 python:将 3d 数组转换为 2d
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32838802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
numpy with python: convert 3d array to 2d
提问by wudanao
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.
假设我有一个彩色图像,自然这将在 python 中由一个 3 维数组表示,比如形状 (nxmx 3) 并将其称为 img。
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”以具有形状 (3,nxm),以便该数组的每一行分别包含 R、G 和 B 通道的“展平”版本。此外,它应该具有我可以通过类似的方式轻松重建任何原始通道的属性
narray[0,].reshape(img.shape[0:2]) #so this should reconstruct back the R channel.
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.
问题是如何从“img”构造“narray”?简单的 img.reshape(3,-1) 不起作用,因为元素的顺序对我来说是不可取的。
Thanks
谢谢
采纳答案by Divakar
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 -
您需要使用np.transpose
来重新排列尺寸。现在,n x m x 3
要转换为3 x (n*m)
,因此将最后一个轴移到前面并将其余轴的顺序右移(0,1)
。最后,重塑为具有3
行。因此,实施将是 -
img.transpose(2,0,1).reshape(3,-1)
Sample run -
样品运行 -
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]])
回答by yashgarg1232
Let's say we have an array img
of size m x n x 3
to transform into an array new_img
of size 3 x (m*n)
假设我们有一个img
大小的数组m x n x 3
要转换为一个new_img
大小的数组3 x (m*n)
new_img = img.reshape((img.shape[0]*img.shape[1]), img.shape[2])
new_img = new_img.transpose()
回答by Harry
If you have the scikit module installed, then you can use the rgb2grey (or rgb2gray) to make a photo from color to gray (from 3D to 2D)
如果你安装了 scikit 模块,那么你可以使用 rgb2grey(或 rgb2gray)制作一张从彩色到灰色(从 3D 到 2D)的照片
from skimage import io, color
lina_color = io.imread(path+img)
lina_gray = color.rgb2gray(lina_color)
In [33]: lina_color.shape
Out[33]: (1920, 1280, 3)
In [34]: lina_gray.shape
Out[34]: (1920, 1280)