Reshape the image matrix in python

13,086

Use 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)
Share:
13,086
Lok
Author by

Lok

Updated on June 04, 2022

Comments

  • Lok
    Lok almost 2 years

    I want first to convert the original image (where the shape and dtype is ((1024, 1024, 3), dtype('uint8'))) into 1D array so that I can enter that 1D array into the training set as one observation.

    Now I want to convert that 1D array into it's original form.

    For converting original image into 1D array I used flatten() function available in numpy. Below is code:

    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)
    

    Now I want to convert the above matrix(result from t.flattern()) into the original matrix(i.e (1024,1024,3) in shape).

    Please tell me what should I do.

    Update: I checked the shape of t.flatten and it comes out to be

    In[86]: p=t.flatten()
    In[87]: p.shape
    Out[86]:(6291456,) 
    

    But 6291456=(1024*1024*3* 2). Now I am confused that from where does this extra term(i.e 2) comes out.

    I also used reshape command but error comes out when I executed the command.

    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