如何重塑图片numpy数组的形状

问题描述 投票:0回答:1

我有一张RGB图片,形状是(640,480,3)

我需要一个形状为(3,640*480)

我用的是

picture.reshape(3,(picture.shape[0]*picture.shape[1]))

它给出了预期的形状,但里面的数据是错误的。我需要每个通道都是单行的。

如何制作?

python numpy dataframe matrix reshape
1个回答
0
投票

重塑形状不会改变数据的顺序。请尝试先将空间维度序列化,然后再进行转置。

>>> by_channel = picture.reshape(-1, 3).transpose()  # or .T for short
>>> by_channel.shape  # Correct shape?
(3, 311040)
>>> np.all(by_channel[0] == picture[..., 0].ravel())  # Correct data?
True

试试先序列化空间维度,然后再转置: .transpose() 操作是自己的反,所以要把它变换回来,只需做。

>>> _picture = by_channel.T.reshape(picture.shape)
>>> np.all(_picture == picture)
True

0
投票

这里的问题是重塑函数的使用。

文件是:

np.reshape(array,shape)

返回数组。你的代码的问题是你把元素列错了,这让计算机认为你是把数字3重塑成shape(640*480)。

这种情况下,正确的代码是:。

picture = np.reshape(picture,(3,640*480))
© www.soinside.com 2019 - 2024. All rights reserved.