pythonpython-3.xnumpyreshapeimage-preprocessing

ValueError: cannot reshape array of size 784 into shape (16,16)


While read .mat format data with Python and show as plt:

import scipy.io as spio
import numpy as np
import matplotlib.pyplot as plt

digits = spio.loadmat('./data/digits.mat', squeeze_me=True)
X = digits['X']
plt.imshow(np.reshape(X[5,:],(16,16)), cmap='Greys')
plt.show()

It raises an error: ValueError: cannot reshape array of size 784 into shape (16,16).

How could I reshape it correctly? Thanks.

X's shape:

print(X.shape)

Out:

(10000, 784)

Data's keys:

print(digits.keys())

Out:

dict_keys(['__header__', '__version__', '__globals__', 'Y', 'X'])

Solution

  • Of course, the solution is easier than you think.

    ValueError: cannot reshape array of size 784 into shape (16,16).

    28 x 28 = 784
    

    Therefore, you need to reshape into the format (28,28) rather than (16,16)