Search code examples
pythonnumpypython-imaging-librarymnist

Problem in converting digit image to numpy array


I am practicing with the MNIST digit dataset. I was excited to make any method for converting my hand written digits to numpy array. But was not getting the expected result. Here's what I have written in photoshop: Image of 8 written in photoshop

Image of 7 written in photoshop

Then I have written a code that convert the png image to np array that looks like this:

from PIL import Image
img  =Image.open('New Project (11).png')
img_arr = np.array(img)
img_arr = img_arr.flatten()
img_arr = img_arr.astype('float64')
some_digit = img_arr.reshape(28,28)

import matplotlib as mpl
import matplotlib.pyplot as plt

plt.imshow(some_digit,cmap='binary')

The result given was like this:

enter image description hereenter image description here

What wrong have I done or what is other easy alternative. Thanks for any help.


Solution

  • I found the problem. The numpy array that I have converted from the image is actually correct. For some reason it shows different. I have used skimage instead of PIL and inverted the image and it worked. The code is as follows:

    
    import skimage.io as lo
    from skimage import util 
    img = lo.imread("New Project (16).png")
    img = util.invert(img)
    img_arr = np.array(img)
    img_arr = img_arr.flatten()
    
    # type(img_arr)
    img_arr = img_arr.astype('float64')
    
    some_digit = img_arr.reshape(28,28)
    # some_digit = np.invert(some_digit)
    # some_digit
    
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    # some_digit = X[0]
    # some_digit_image = some_digit.reshape(28,28)
    
    plt.imshow(some_digit,cmap='binary')