Getting error: Cannot reshape array of size 122304 into shape (52,28,28)

akrama81 picture akrama81 · Jul 31, 2017 · Viewed 77.6k times · Source

I'm trying to reshape a numpy array as:

data3 = data3.reshape((data3.shape[0], 28, 28))

where data3 is:

[[54 68 66 ..., 83 72 58]
 [63 63 63 ..., 51 51 51]
 [41 45 80 ..., 44 46 81]
 ..., 
 [58 60 61 ..., 75 75 81]
 [56 58 59 ..., 72 75 80]
 [ 4  4  4 ...,  8  8  8]]

data3.shape is (52, 2352 )

But I keep getting the following error:

ValueError: cannot reshape array of size 122304 into shape (52,28,28)
Exception TypeError: TypeError("'NoneType' object is not callable",) in <function _remove at 0x10b6477d0> ignored

What is happening and how to fix this error?

UPDATE:

I'm doing this to obtain data3 that is being used above:

def image_to_feature_vector(image, size=(28, 28)):

    return cv2.resize(image, size).flatten()

data3 = np.array([image_to_feature_vector(cv2.imread(imagePath)) for imagePath in imagePaths])  

imagePaths contains paths to all the images in my dataset. I actually want to convert the data3 to a flat list of 784-dim vectors, however the

image_to_feature_vector 

function converts it to a 3072-dim vector!!

Answer

Kaushik Nayak picture Kaushik Nayak · Jul 31, 2017

You can reshape the numpy matrix arrays such that before(a x b x c..n) = after(a x b x c..n). i.e the total elements in the matrix should be same as before, In your case, you can transform it such that transformed data3 has shape (156, 28, 28) or simply :-

import numpy as np

data3 = np.arange(122304).reshape(52, 2352 )

data3 = data3.reshape((data3.shape[0]*3, 28, 28))

print(data3.shape)

Output is of the form

[[[     0      1      2 ...,     25     26     27]
  [    28     29     30 ...,     53     54     55]
  [    56     57     58 ...,     81     82     83]
  ..., 
  [   700    701    702 ...,    725    726    727]
  [   728    729    730 ...,    753    754    755]
  [   756    757    758 ...,    781    782    783]]
  ...,
[122248 122249 122250 ..., 122273 122274 122275]
  [122276 122277 122278 ..., 122301 122302 122303]]]