在Python中重新塑造图像矩阵

3

我希望首先将原始图像(其形状和数据类型为((1024, 1024, 3), dtype('uint8')))转换为1D数组,以便我可以将该1D数组作为一个观察结果输入到训练集中。

现在我想将该1D数组转换回其原始形式。

为了将原始图像转换为1D数组,我使用了numpy中可用的flatten()函数。以下是代码:

In[80]: t = misc.imread('b.png') #to read the image

In[81]: t.shape, t.dtype
Out[81]: ((1024, 1024, 3), dtype('uint8'))

#To convert the above image into 1D array

In[82]: t.flatten()
Out[82]: array([  5,  40, 121, ..., 130, 110,  89], dtype=uint8)

现在我想将上面的矩阵(来自t.flatten()的结果)转换回原始矩阵(即形状为(1024,1024,3))。
请告诉我应该怎么做。
更新: 我检查了t.flatten的形状,发现它是:
In[86]: p=t.flatten()
In[87]: p.shape
Out[86]:(6291456,) 

但是6291456=(1024*1024*3*2)。现在我很困惑这个额外项(即2)从哪里来。

我也使用了reshape命令,但当我执行该命令时会出错。

l=p.reshape(1024,1024,3)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-89-b1ab41666df7> in <module>()
----> 1 l=p.reshape(1024,1024,3)

ValueError: total size of new array must be unchanged

只需使用所需的形状进行“reshape”操作? - Divakar
@Divaker 我用了它,但是它显示一些模糊的错误。 - Lok
我无法复现给定初始形状的数组中 p.shape 变为 (6291456,) 的情况。 - akilat90
@akilat90 如果你按照我所做的来操作,我相信你也能得到相同的结果。 - Lok
1个回答

3
使用reshape函数。
In [93]: a = np.zeros((10,10,3))
In [94]: a.shape
Out[94]: (10, 10, 3)

In [95]: b = a.flatten()
In [96]: b.shape
Out[96]: (300,)

In [97]: c = b.reshape(10,10,3)
In [98]: c.shape
Out[98]: (10, 10, 3)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接