0

Hello there I'm trying to convert the MNIST dataset to greyscale with python but I can not do it right.

code:

(x_train, y_train), (x_test, y_test) = mnist.load_data() 
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)

When I enter the above I get this error:

TypeError: Invalid shape (28, 28, 1) for image data

What am I doing wrong?

Hayden Eastwood
  • 928
  • 2
  • 10
  • 20
  • The reshape method would not 'aggregate' the data. See if this helps: https://stackoverflow.com/questions/41971663/use-numpy-to-convert-rgb-pixel-array-into-grayscale – HasnainMamdani Mar 18 '20 at 18:58
  • Thanks, but i didn't get the answer. Can I apply np.dot() on dataset to convert it to gray scale? – Sahar Metwally Mar 18 '20 at 19:18
  • Yes exactly, you choose the ratios of RGB you want to use for conversion. Although I'm surprised you need to do this because MNIST data usually already comes in grayscale. Perhaps also check your original data dimensions and mention the source you're obtaining the MNIST data from. – HasnainMamdani Mar 18 '20 at 19:51
  • Thanks a lot for your reply. I used keras to load MNIST dataset. – Sahar Metwally Mar 18 '20 at 20:20
  • A comprehensive list of solutions can be found here: https://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python – AthulMuralidhar Mar 18 '20 at 20:34
  • The error you posted does not come from `reshape`. Please post the _full_ error traceback. I assume you get this error when trying to plot images, e.g. via `matplotlib`'s `imshow`. In that case, you simply have to remove the last dimension. – xdurch0 Mar 18 '20 at 23:14

1 Answers1

1

Easiest way is to use Pillow like so:

In [27]: from PIL import Image                                                                                                                        
In [28]: img = Image.open('test.jpg').convert('L') 
    ...: img.save('greyscale.jpg')  

More answers (incl matlab) here

AthulMuralidhar
  • 662
  • 1
  • 9
  • 26