In the code below I created a neuronal network with mnist data set to recognize handwritten numbers, it works for the mnist data set but for my own in windows 11 paint created 28*28 Pixel images it wont work and shows the wrong output, why is it ?
import cv2 # computer vision --> Load images and process images
import numpy as np
import matplotlib.pyplot as plt # visulization
import tensorflow as tf # maschine learning
import os
mnist = tf.keras.datasets.mnist # load from tenserflow
#split dataset in training data and testing data
(x_train, y_train), (x_test, y_test) = mnist.load_data() # x_train = image itself, y_train number of image
# normalize = scaling it down between 0-1
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)
#
# model = tf.keras.models.Sequential() # basic sequential neuronal network
# model.add(tf.keras.layers.Flatten(input_shape=(28, 28))) # add a layer, Flatten = Flattens the input shape 784
# model.add(tf.keras.layers.Dense(128, activation='relu')) #connects every neuron 128 units
# model.add(tf.keras.layers.Dense(10, activation='softmax')) #softmax = all outputs add up to 1 = confidence 0-1 values how likely is the output
#
# model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',metrics=['accuracy'])
#
# #train the model
#
# model.fit(x_train,y_train, epochs=3)
#
# model.save('handwritten.model')
model = tf.keras.models.load_model('handwritten.model')
image_number = 1
while os.path.isfile(f"Digits/digit{image_number}.png"):
try:
img = cv2.imread(f"Digits/digit{image_number}.png")[:, :, 0]
img = np.invert(np.array([img])) # img in a list as a np-array
prediction = model.predict(img)
print(f"This digit is probably a {np.argmax(prediction)}") # which neuron has the highest number
plt.imshow(img[0], cmap=plt.cm.binary)
plt.show()
except Exception as e:
print(f"Error is {e}")
finally:
image_number += 1