如何重塑图片numpy数组
How to reshape a picture numpy array
我有一张形状为 (640,480,3) 的 RGB 图片
我需要 (3,640*480) 的形状
我用
picture.reshape(3,(picture.shape[0]*picture.shape[1]))
它给出了预期的形状,但里面的数据有误。我需要在一行中的每个通道。
如何制作?
整形不会改变数据的顺序。尝试先序列化空间维度,然后转置:
>>> 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
这里的问题是reshape函数的使用:
文档是:
np.reshape(array,shape)
其中returns数组。您的代码的问题是您列出了错误的元素,这使计算机认为您正在将数字 3 重塑为 shape(640*480)。
这种情况下的正确代码是:
picture = np.reshape(picture,(3,640*480))
我有一张形状为 (640,480,3) 的 RGB 图片
我需要 (3,640*480) 的形状
我用
picture.reshape(3,(picture.shape[0]*picture.shape[1]))
它给出了预期的形状,但里面的数据有误。我需要在一行中的每个通道。
如何制作?
整形不会改变数据的顺序。尝试先序列化空间维度,然后转置:
>>> 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
这里的问题是reshape函数的使用:
文档是:
np.reshape(array,shape)
其中returns数组。您的代码的问题是您列出了错误的元素,这使计算机认为您正在将数字 3 重塑为 shape(640*480)。
这种情况下的正确代码是:
picture = np.reshape(picture,(3,640*480))