pythonarraysnumpyimage-processing

Cannot reshape array of size 1 into shape (1,224,224,3)


I am trying to reshape separate arrays of three components each Y - U - V into a YUV array. The size of this array input 64x64 and then will be resized to 224x224. How should I do it correctly?

This is for my input data before training a CNN network. So, the following is the way I use to do it.

orgY = np.loadtxt(path)
orgU = np.loadtxt(path)
orgV = np.loadtxt(path)

originalYUV = np.dstack((orgY, orgU, orgV))

originalYUV = array(originalYUV).reshape(1, 224, 224, 3)

When I run it, this shows me: ValueError: cannot reshape array of size 1 into shape (1,224,224,3). How should I fix it? I am afraid the code is wrong when I use np.dstack as I even cannot call width = originalYUV.shape[0]


Solution

  • If I understood your question correctly, your individual inputs are of shape (64,64).

    dstacking them gives an array of shape (64, 64, 3).

    You can only reshape to a shape that has the same product of its sizes, but obviously 64*64*3 != 1*244*244*3.

    Maybe try using np.resize((shape),refcheck=False) or even better - do some prior padding for the input channels to have more control.

    I recreated your code in a Python interactive console to exemplify the reason for the error:

    import numpy as np
    
    a = np.array([[1]*64]*64)
    
    a.shape
    Out[6]: (64, 64)
    
    total = np.dstack([a,a,a])
    total.shape
    Out[8]: (64, 64, 3)
    
    # reshaping to a bigger size is expected to fail
    total.reshape((1,224,224,3))
    Traceback (most recent call last):
      File "C:\Users\FlRE_DEATH\anaconda3\envs\py310tg210gpu\lib\site-packages\IPython\core\interactiveshell.py", line 3548, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-9-edc0b775f734>", line 1, in <module>
        total.reshape((1,224,224,3))
    ValueError: cannot reshape array of size 12288 into shape (1,224,224,3)
    
    # reshaping to a smaller size is expected to fail
    a.reshape((20,20))
    Traceback (most recent call last):
      File "C:\Users\FlRE_DEATH\anaconda3\envs\py310tg210gpu\lib\site-packages\IPython\core\interactiveshell.py", line 3548, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-10-574a99b7dcc4>", line 1, in <module>
        a.reshape((20,20))
    ValueError: cannot reshape array of size 4096 into shape (20,20)
    a.reshape((4096,1))
    
    Out[11]: 
    array([[1],
           [1],
           [1],
           ...,
           [1],
           [1],
           [1]])