带python的numpy:将3d数组转换为2d

2024-05-17 05:04:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个彩色图像,很自然,这将由python中的一个三维数组表示,比如shape(nxmx3),并称之为img。

我想要一个新的二维数组,称之为“narray”有一个形状(3,nxm),这样数组的每一行分别包含R、G和B通道的“扁平”版本。而且,它应该具有这样的特性:我可以很容易地通过类似于

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

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

谢谢


Tags: 版本imgso数组特性this彩色图像形状
3条回答

如果安装了scikit模块,则可以使用rgb2gray(或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)

您需要使用^{}重新排列维度。现在,n x m x 3将被转换为3 x (n*m),因此将最后一个轴发送到前面,并右移剩余轴的顺序(0,1)。最后,重塑为具有3行。因此,实施将是-

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

假设我们有一个大小为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()

相关问题 更多 >