3

I've created a model (LeNet-5), which is giving pretty good accuracy(98%).

Then I tried to see how will it perform on my hand written data(Obviously from different distribution, just curious). So I took the picture of a 5 and converted it to gray-scale using PIL and saw what it predicts. It didn't perform well.

Code to convert to gray-scale:

# Open the file
im = Image.open(path)

# Resize the image
im_resized = im.resize(size)

# Convert to grayscale
gr = ImageOps.grayscale(im_resized)

And It also didn't perform well on some other images from Internet. Then I got suspicious from the numbers.

MNIST: background is black and number in white

my image: background is white and number in black

So I wanted to see the images of MNIST. But all I get is some white dots. No meaningful image at all.

Here is the code snippet to see the image:

from mnist import MNIST
mndata = MNIST(mndir)

train_images, train_labels = mndata.load_training()
test_images, test_labels = mndata.load_testing()

ar = np.array(test_images[10], np.int32)
ar = np.resize(ar, (28, 28))
im = Image.fromarray(ar, 'L')
im.show()

For this I get something like:

a weird number

Edit:

When I tested it again, I came to know the PIL library requires uint8 type to show the image. For more info: PIL-produces-black-image. To make the above code work, use

ar = np.resize(ar, (28, 28)).astype(np.uint8)
Abhisek
  • 4,610
  • 3
  • 17
  • 27
  • Omit `np.array(test_images[10], np.int32)` and change the line below to `ar = np.resize(test_images[10], (28, 28))`. MNIST images probably do not have the alpha channel, and when you force the pixels to be 32 bits you end up stepping too much per pixel. – broderick Feb 13 '23 at 13:10
  • @broderick: Thanks for the suggestion. I tested it after a long time. It turns out PIL library requires `uint8` type to show the image. I have updated the question. – Abhisek Feb 26 '23 at 07:13

1 Answers1

0

here is a small code to see the image. This helps to print an inline image of MNIST

get_ipython().magic(u'matplotlib inline') #to print inline images

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

#load the data

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', validation_size=0)

#we can plot an example image from the MNIST dataset.
img = mnist.train.images[2]
plt.imshow(img.reshape((28, 28)), cmap='Greys_r')

ideally this should work.

Mohanrac
  • 85
  • 6