首页 文章

在python中重塑图像矩阵

提问于
浏览
1

我想首先将原始图像(其中形状和dtype是 ((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.flattern() 的结果)转换成原始矩阵(即形状为 (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

1 回答

  • 0

    使用 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)
    

相关问题