Hand writing digit recognition algorithm

In this project, I am writing an algorithm to recognize hand writing digits, by using neural networks. I’ll use the following modules : numpy, cv2, os and of course tensorflow.
My Code:

import os
import cv2
import numpy as np
import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test)  = mnist.load_data()

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()
model.add(tf.keras.layers.Flatten(input_shape = (28, 28)))
model.add(tf.keras.layers.Dense(128, activation = 'relu'))
model.add(tf.keras.layers.Dense(128, activation = 'relu'))
model.add(tf.keras.layers.Dense(10, activation = 'softmax'))

model.compile(optimizer = 'adam', loss ='sparse_categorical_crossentropy', metrics = ['accuracy'])

model.fit(x_train, y_train, epochs=3)
model.save('handwritten.model')


model = tf.keras.models.load_model('handwritten.model')

img_nub = 1
while os.path.isfile(f"digits/digit{img_nub}.png"):

        img = cv2.imread(f"digits/digit{img_nub}.png")[:,:,0]
        imp = np.invert(np.array([img]))
        prediction = model.predict(img)
        print(f"this digit is probably : {np.argmax(prediction)}")
        img_nub += 1


I ran into a problem when I tried to test this algorithm with 28 * 28 pixel white and black images (png)

and this is the Error :

ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape (None, 28)```

Thank you.

@issamelimrany I’ve done Deep Learning a while back. If I’m not wrong you don’t need the .Flatten for the first (input) layer, just the input shape will do. Something like this:

Flatten is usually to convert Convolutional layers into Dense Layers. (i.e. feature learning to classification steps)

Thank you for your effort, but I’ve discovered that it’s just a syntax error, instead of calling a variable by img I typed imp.