Handwritten Digit Recognition Using Python and TensorFlow – Complete AI Project

Can a computer recognize a digit written by hand?

In this project, we will build a simple AI-based Handwritten Digit Recognition system using Python and TensorFlow.

The project uses the popular MNIST handwritten digit dataset to train a Convolutional Neural Network (CNN). After training, the model can recognize handwritten digits from 0 to 9.

To make the project easy to try, the completed project includes a pre-trained CNN model. You can download the project files, install the required Python packages, run the program, draw a digit using your mouse, and see what the AI predicts.

If you are interested in understanding how the AI model was created, the same article also explains the training process, including loading the MNIST dataset, building the CNN, training the model, evaluating its performance and saving the trained model.

🎯 2. What Will We Build?

In this project, we will build a simple AI-powered handwritten digit recognizer. You will draw a digit such as 0, 1, 2 … 9 using your mouse, and the trained CNN model will analyze the drawing and predict the digit.
⚙️ How the AI Application Works
✏️ 1. Draw a Digit
🖼️ 2. Image Preprocessing
🔲 3. Resize to 28 × 28
🧠 4. Trained CNN Model
🤖 5. AI Prediction
📊 6. Digit + Confidence
💡 What happens behind the scenes?
Your drawing is first cleaned and resized to the 28 × 28 pixel format expected by the CNN. The trained model then analyzes the image and predicts the most likely digit. Finally, the application displays the predicted digit along with its confidence score.

🚀 Project goal: Convert a handwritten drawing into an AI prediction using Python, TensorFlow and a Convolutional Neural Network (CNN).

🧰 3. What You Need

🔧 Requirements

Before starting, make sure you have:
  • 💻 A Windows computer
  • 🐍 Python 3.12
  • 🌐 An internet connection for installing the required packages
  • 📁 The project files provided with this tutorial
  • ⌨️ Basic familiarity with Command Prompt and running Python programs
⚠️ Important — Python Version
This project was successfully implemented and tested using Python 3.12 with TensorFlow.

If you already have another Python version, such as Python 3.14, installed on your computer, you do not need to uninstall it.

For this project, we will specifically use Python 3.12 to create and run the project environment.
💡 Why are we specifying Python 3.12?
During the development of this project, explicitly using Python 3.12 provided a reliable environment for installing TensorFlow and running the complete application. Therefore, we will use the same Python version in this tutorial to make the setup easier and more predictable.
📌 Tip: If multiple Python versions are installed on your computer, don’t worry—we will explicitly use Python 3.12 when setting up this project.

📥 4. Download the Project Files

📦 Download and Extract the Project

Download the project ZIP file using the download link provided below. Extract the ZIP file to a convenient location on your computer.

📁 The project package contains the trained CNN model, Python programs, and supporting files required to run and understand the handwritten digit recognition application.
📂 Project folder structure
handwritten_digit_recognition/
│
├── digit_cnn.keras
├── final_digit_recognizer.py
├── my_digit.png
├── requirements.txt
├── step1_train_cnn.py
├── step2_train_and_save.py
├── step3_drawing_canvas.py
└── my_digit.png

📋 File Description

📄 File 🎯 Purpose
digit_cnn.keras Pre-trained CNN model
final_digit_recognizer.py Final handwritten digit recognition application
requirements.txt Required Python packages
step1_train_cnn.py CNN training program
step2_train_and_save.py Training, evaluation and model-saving program
step3_drawing_canvas.py Drawing canvas for creating a handwritten digit image
my_digit.png Sample/saved handwritten digit image
✅ Good to know
The final recognizer uses the pre-trained digit_cnn.keras model. Therefore, if you only want to test the completed application, you do not need to train the model again.
💡 For learning: The training programs are also included so that you can understand how the CNN is trained, evaluated, and saved before using it for real-time digit recognition.

⭐ 5. Quick Start

Now comes the most exciting part! 🚀 You can test the completed AI application without training the model again.

⭐ Quick Start — Run the Completed Project
❓ Want to test the project without training the AI model?
You can do that immediately. The trained digit_cnn.keras model is already included in the project files.

📌 No retraining is required if your goal is simply to run and test the completed application.
▶️ Follow the commands below in the given order.
💡 Learning note: Later in this tutorial, you can also learn how the CNN model is trained and saved. For now, we will first run the already-trained model and see the AI application in action.

🐍 Step 1 — Check Python 3.12

Open Command Prompt on your Windows computer.

🔎 First, see which Python versions are installed:
py --list

This command displays the Python versions installed on your computer.

🎯 Now specifically check Python 3.12:
py -3.12 --version
✅ Expected output:
Python 3.12.x
🟢 Python 3.12 is available? Great! Continue to the next step.

📂 Step 2 — Open the Project Folder

Suppose you extracted the project to the following location:

G:\Handwritten_Digit_Recognition
▶️ Open this folder in Command Prompt:
cd /d G:\Handwritten_Digit_Recognition
💡 Important: Replace the example path with the actual location of your project folder.

🐍 Step 3 — Create a Virtual Environment

From inside the project folder, create a virtual environment using Python 3.12.

⚙️ Run:
py -3.12 -m venv .venv
✅ This creates a separate Python environment named .venv inside your project folder.
🔒 The virtual environment keeps this project’s Python packages separate from packages installed for other Python projects.
🎯 Why use py -3.12?
This explicitly tells the Python Launcher to create the environment with Python 3.12, even if another Python version, such as Python 3.14, is also installed on your computer.

⚡ Step 4 — Activate the Environment

Activate the virtual environment you created in the previous step.

▶️ Run:
.venv\Scripts\activate

You should now see (.venv) at the beginning of the Command Prompt:

(.venv) G:\Handwritten_Digit_Recognition>
✅ The (.venv) prefix means that the project’s virtual environment is now active.

🐍 Step 5 — Verify Python

Now verify that the active environment is using Python 3.12.

🔎 Run:
python --version
✅ Expected output:
Python 3.12.x
⭐ Do not skip this check
This confirms that the project is using Python 3.12 inside the virtual environment, even if Python 3.14 or another version is also installed on your computer.
🚀 Python 3.12 confirmed? Excellent! Your project environment is ready for the required packages.

📦 Step 6 — Upgrade pip

Before installing the project packages, upgrade pip to its latest available version. Pip is Python’s package manager and is used to install the libraries required by this project.

▶️ Run:
python -m pip install --upgrade pip
⏳ Wait for the installation to finish before moving to the next step.

📚 Step 7 — Install Required Packages

Your project includes a requirements.txt file containing the Python packages needed by the project.

▶️ Run:
python -m pip install -r requirements.txt
📄 The file contains:
tensorflow
numpy
pillow

🧩 Packages Used in This Project

TensorFlow
Used to build, train and run the Convolutional Neural Network (CNN) model.
NumPy
Used for numerical operations and handling image arrays.
Pillow
Used for opening, creating and preprocessing image files.
Tkinter
Used to create the graphical drawing canvas. It is part of the standard Python installation on Windows and is not normally installed through this project’s requirements.txt.
Important: Make sure the virtual environment is still active before running the installation command. You should see (.venv) at the beginning of your Command Prompt.
🎉 Packages installed? Excellent! Your Python environment now has the main libraries required to run the handwritten digit recognition project.

🧠 Verify TensorFlow

🔍 Step 8 — Check TensorFlow Installation

TensorFlow is the main machine-learning library used by our handwritten digit recognition project. Let’s verify that it was installed correctly inside the active virtual environment.

▶️ Run:
python -c "import tensorflow as tf; print('TensorFlow Version:', tf.__version__)"
📌 You should see something similar to:
TensorFlow Version: 2.x.x
💡 The exact version displayed depends on the TensorFlow version installed in your project’s virtual environment.
✅ TensorFlow is working!
If the TensorFlow version is displayed without an error, your TensorFlow installation is working correctly.
Before continuing: Make sure your Command Prompt still shows (.venv). This confirms that you are checking TensorFlow from the project’s virtual environment.

🚀 Run the Final Application

▶️ Step 9 — Start the AI Digit Recognizer

Before running: Make sure you are still inside the project folder and that the (.venv) virtual environment is active.
▶️ Run:
python final_digit_recognizer.py
🧠 The program loads the trained model:
digit_cnn.keras
🎉 The application should now open the AI Handwritten Digit Recognizer window.

✏️ Draw a handwritten digit in the drawing area, submit it for recognition, and let the trained CNN model predict the digit.
🔍 What happens next?
Your drawing is preprocessed, converted into the format expected by the CNN, and passed to the trained model. The application then displays the predicted digit and its confidence.
Ready to try it? Draw a clear digit such as 5 or 8 and see what the AI predicts.

✏️ Step 10 — Draw a Digit

When the application starts, a drawing window will appear. Look for the heading:

🖥️ Draw a Digit (0-9)
🖱️ Use your mouse to draw a digit on the white canvas. Try to make the digit clear and reasonably centered.
🎯 Try drawing:
0 1 2 3 4 5 6 7 8 9

🤖 Step 11 — Click Predict

After drawing the digit, click the Predict button.

🔮 Predict
🧠 The AI processes your drawing and sends the image to the trained CNN model. The model calculates the probability of each digit and selects the most likely one.
📊 Example result:
Digit: 7    Confidence: 98.XX%
💡 The confidence value can vary depending on the digit and how clearly it is drawn.
🔬 How is the result selected?
The final program compares the prediction probabilities for all ten digit classes and displays the class with the highest probability, together with its corresponding confidence percentage.
🎉 That’s it! You have just used a trained CNN model to recognize a handwritten digit.

🔄 Step 12 — Try Another Digit

🧹 Click:
Clear

Draw another digit and click Predict again.

💡 The Clear button resets the drawing canvas so that you can test another digit.

🎉 Congratulations!

You have successfully run an AI-based Handwritten Digit Recognition system using Python, TensorFlow and a CNN model.

🧩 Your complete process was:
🐍 Python 3.12
⚙️ Virtual Environment
📦 Install Required Packages
🧠 Load Trained CNN Model
✏️ Draw Handwritten Digit
🖼️ Preprocess Image
🤖 CNN Prediction
📊 Digit + Confidence
💡 What you have learned: You have seen how a handwritten image can be converted into numerical data, processed by a CNN, and transformed into an AI prediction.
🚀 Next: Now that the application is working, we can explore how the CNN model works and understand the important Python code behind the project.

🎓 6. Then Transition into the Training Phase

You have now tested the completed application. But an important question remains: Where did the AI model come from?

🎓 How Was the AI Model Trained?
The file digit_cnn.keras contains a trained CNN model.

In the next section, we will go behind the scenes and learn how this model is created using the MNIST handwritten digit dataset and TensorFlow.
🛑 Only want to use the completed project?
You can stop here. The training process is optional if your goal is simply to run and use the completed application.
🚀 Want to understand how the AI works?
Continue to the Training Phase below to learn how the CNN is trained, evaluated, and saved for later predictions.
💡 Why this approach?
A beginner does not have to spend time training a model before experiencing the result. You can first see the AI application working and then, if interested, learn how the trained model was created.
🧠 Ready to go behind the scenes?  →  Training Phase

🎓 7. Training Phase — Build the CNN Model Using MNIST

You have already tested the completed Handwritten Digit Recognition application using the pre-trained digit_cnn.keras model.

But how was this AI model created?

In this section, we will train our own Convolutional Neural Network (CNN) using the MNIST handwritten digit dataset.

Note: Training is optional if you only want to use the completed project. The pre-trained digit_cnn.keras file is already included.

MNIST is a popular dataset containing handwritten digits from 0 to 9.

Each digit image has a size of:

28 × 28 pixels

The dataset contains:

  • 60,000 images for training
  • 10,000 images for testing
  • 10 possible classes: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Our CNN learns patterns from these handwritten images and then uses those patterns to recognize new handwritten digits.

🧠 2. How Does Training Work?

The CNN learns to recognize handwritten digits through a sequence of steps. The overall training process can be represented as:

📚 1. MNIST Dataset
🖼️ 2. Load the Images
📊 3. Normalize Pixel Values
🔲 4. Reshape Images
🧠 5. Build the CNN Model
🎯 6. Train the CNN
📈 7. Evaluate the Model
💾 8. Save the Trained Model
🧠 digit_cnn.keras
💡 What is the result?
The CNN learns patterns from thousands of handwritten digit images. After training and evaluation, the trained model is saved as digit_cnn.keras.
🔗 Why is this important?
The saved digit_cnn.keras file is later loaded by the final recognition program. This allows the application to make predictions without training the CNN every time it starts.

3. Training Program

The project contains the following training program:

This program performs the complete CNN training process.

The important stages are:

  1. Load the MNIST dataset
  2. Prepare the images
  3. Build the CNN
  4. Train the CNN
  5. Evaluate the model
  6. Save the trained model

📚 4. Load the MNIST Dataset

Our program uses TensorFlow to load the popular MNIST handwritten digit dataset. MNIST contains images of handwritten digits from 0 to 9 and is commonly used for learning image classification and CNN-based digit recognition.

from tensorflow.keras.datasets import mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
🗂️ The dataset is divided into two parts:
Training data → x_train, y_train
Testing data → x_test, y_test
🖼️ x_train and x_test contain the handwritten digit images.
🏷️ y_train and y_test contain the corresponding correct digit labels.
🎯 Why two sets?
The training set teaches the CNN how handwritten digits look, while the testing set is used later to check how well the trained model recognizes images it has not seen during training.
💡 Remember: x = images   |   y = labels

📊 5. Normalize the Images

MNIST images use grayscale pixel values from 0 to 255. Before sending the images to the CNN, we scale these values to a much smaller range.

🖼️ Original pixel values: 0 → 255
🎯 After normalization: 0 → 1
🐍 This is done using:
x_train = x_train.astype("float32") / 255.0
x_test  = x_test.astype("float32") / 255.0
🔢 Simple example:
Original pixel value: 255   →   Normalized value: 1.0
For example, a pixel value of 128 becomes approximately 0.502.
💡 Why do we normalize?
Neural networks generally work better when input values are kept within a small, consistent range. Scaling the pixel values from 0–255 to 0–1 makes the image data easier for the CNN to process during training.
🧠 Remember: 255 ÷ 255 = 1.0   |   0 ÷ 255 = 0.0
So every pixel is converted to a value between 0 and 1.

🔲 6. Reshape the Images

The MNIST images are originally stored as 28 × 28 grayscale images. Our CNN also needs to know the image’s channel dimension.

📐 Image shape changes from:
28 × 28 28 × 28 × 1
💡 What does the 1 mean?
The 1 represents the grayscale image channel. A grayscale image needs only one channel because each pixel contains a single brightness value. A color RGB image, in contrast, normally has three channels.
🐍 The program uses:
x_train = x_train.reshape(-1, 28, 28, 1)
x_test  = x_test.reshape(-1, 28, 28, 1)
🔍 Understanding the shape:

-1 → Let Python automatically determine the number of images.
28, 28 → Height and width of each image.
1 → One grayscale channel.
🖼️ One image received by the CNN
Handwritten
Digit
28 pixels × 28 pixels × 1 channel
Now the images are ready!
Each MNIST image has the shape 28 × 28 × 1, which provides the CNN with the height, width, and grayscale channel information it expects.

🧠 7. Build the CNN Model

Now we create the Convolutional Neural Network (CNN) that will learn to recognize handwritten digits. The model is built using TensorFlow/Keras.

🏗️ CNN Architecture
🖼️ Input — 28 × 28 × 1
🔍 Conv2D — 32 filters
📉 MaxPooling2D
🔍 Conv2D — 64 filters
📉 MaxPooling2D
🔄 Flatten
🧠 Dense — 128 neurons
🎯 Dense — 10 neurons
📊 Prediction — Digits 0 to 9
🐍 The main model structure is:
model = tf.keras.Sequential([
    tf.keras.layers.Input(shape=(28, 28, 1)),

    tf.keras.layers.Conv2D(32, (3, 3), activation="relu"),
    tf.keras.layers.MaxPooling2D(),

    tf.keras.layers.Conv2D(64, (3, 3), activation="relu"),
    tf.keras.layers.MaxPooling2D(),

    tf.keras.layers.Flatten(),

    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dense(10, activation="softmax")
])
🔍 What do these layers do?
🔍 Conv2D → Detects useful patterns such as edges and shapes.
📉 MaxPooling2D → Reduces the spatial size while retaining important features.
🔄 Flatten → Converts the extracted feature maps into a one-dimensional vector.
🧠 Dense → Combines the learned features to make the final decision.
🎯 Softmax output → Produces probabilities for the ten digit classes, 0 through 9.
Important: The final layer contains 10 neurons because the model must choose between the ten possible digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
💡 In simple terms:
The CNN first extracts visual features from the handwritten image, gradually combines those features, and finally produces a probability for each digit from 0 to 9.

🧠 8. Understanding the CNN Layers

💡 You don’t need to understand every mathematical detail to run this project. However, knowing the basic purpose of each CNN layer will help you understand how the handwritten digit is recognized.
🔷 1. Input Layer
Input(shape=(28, 28, 1))
The CNN expects each input image to contain:
🖼️ 28 × 28 pixels
1 grayscale channel
🔷 2. First Convolution Layer
Conv2D(32, (3, 3), activation="relu")
🔍 This layer looks for useful visual patterns in the digit, such as:
  • Edges
  • Curves
  • Lines
  • Simple shapes
🎯 The first convolution layer uses 32 filters to learn these features.
📉 3. First MaxPooling Layer
MaxPooling2D()
This layer reduces the spatial size of the feature maps while keeping the most important information.
🔷 4. Second Convolution Layer
Conv2D(64, (3, 3), activation="relu")
The second convolution layer learns more complex features by combining patterns detected by the earlier layer.

🎯 This layer uses 64 filters.
📉 5. Second MaxPooling Layer
MaxPooling2D()
Another reduction step is performed so that the network can focus on important learned features while using fewer computations.
🔄 6. Flatten Layer
Flatten()
The extracted feature maps are converted into a one-dimensional vector so they can be passed to the fully connected Dense layers.
🧠 7. Dense Layer
Dense(128, activation="relu")
This layer combines the learned features and prepares them for the final digit classification.
🎯 8. Output Layer
Dense(10, activation="softmax")
The final layer produces a probability for each of the 10 possible digits (0–9).

🏆 The digit with the highest probability becomes the model’s prediction.
🧩 In one line:
🖼️ Input → 🔍 Conv2D → 📉 Pooling → 🔍 Conv2D → 📉 Pooling → 🔄 Flatten → 🧠 Dense → 🎯 Output
💡 Simple idea:
The early CNN layers learn visual features, the middle layers combine those features, and the final layers use them to decide which digit the image represents.
📉 9. Max Pooling
MaxPooling2D((2, 2))
📐 Pooling reduces the spatial size of the feature maps.

This reduces the amount of computation while retaining important information about the features detected by the convolution layer.
💡 Default pool size: 2 × 2
🔷 10. Second Convolution Layer
Conv2D(64, (3, 3), activation="relu")
The second convolution layer uses 64 filters.

🔍 It can learn more complex patterns by combining features detected by the earlier convolution layer.
🔄 11. Flatten
Flatten()
The extracted feature maps are converted into a one-dimensional form.

🔗 This allows the extracted features to be passed to the fully connected Dense layers that perform the final classification.
🧩 Remember the sequence:
🔍 Conv2D → 📉 MaxPooling → 🔍 Conv2D → 📉 MaxPooling → 🔄 Flatten → 🧠 Dense
🚀 What comes next?
After Flatten converts the learned features into a one-dimensional vector, the Dense layers use those features to determine which digit is most likely.
🧠 12. Dense Layer
Dense(128, activation="relu")
After the Flatten layer, the learned features are passed to this fully connected layer.

🔗 It contains 128 neurons and combines the learned features to help determine which digit is present.
🎯 13. Output Layer
Dense(10, activation="softmax")
The output layer contains 10 neurons — one for each possible digit from 0 to 9.
0  1  2  3  4   5  6  7  8  9
📊 The softmax activation converts the network’s output into probabilities for the ten possible digits.
🔢 Example Prediction Probabilities
Suppose the model produces the following probabilities:
Digit 0 → 0.01
Digit 1 → 0.02
Digit 2 → 0.03
Digit 3 → 0.91
Digit 4 → 0.01
Digit 5 → 0.00
Digit 6 → 0.01
Digit 7 → 0.00
Digit 8 → 0.01
Digit 9 → 0.00
🏆 The highest probability wins.
In this example, digit 3 has the highest probability: 0.91 (91%).
🤖 Model Prediction
Predicted Digit: 3
💡 In simple terms:
The CNN doesn’t simply say “this is a 3.” It first produces probabilities for all ten digits. The final program selects the digit with the highest probability and displays it as the prediction.

⚙️ 9. Compile the Model

Before training begins, the CNN must be compiled. Compilation tells TensorFlow how the model should learn, how its errors should be measured, and what performance information should be reported.

model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)
🔍 What do these settings mean?
Setting Purpose
adam Optimizer that adjusts the model’s weights during training.
sparse_categorical_crossentropy Loss function used to measure how far the predictions are from the correct digit labels.
accuracy Measures how many digit predictions are correct.
💡 Think of compilation as setting the rules for learning.

🤖 Optimizer → How the model updates itself
📉 Loss → How the model measures its mistakes
📊 Accuracy → How well the model is performing
Important: Compiling the model does not train the CNN. It only prepares the model for training. The actual learning happens in the next step when we call model.fit().
🚀 Next: The model is now ready to learn from the MNIST training data. We will use model.fit() to train the CNN.

🎯 10. Train the CNN

The model is now built and compiled. The next step is to let the CNN learn from the MNIST training images.

model.fit(
    x_train,
    y_train,
    epochs=5,
    validation_data=(x_test, y_test)
)
🔍 What do these values mean?
x_train → Training images
y_train → Correct digit labels
epochs=5 → Train the CNN for five training cycles
x_test, y_test → Images and labels used for validation
💡 What is an epoch?
One epoch means the model has gone through the training dataset once. In this project, 5 epochs means the CNN gets five training cycles to improve its ability to recognize handwritten digits.
📈 What does TensorFlow display?
Epoch 1/5
...
accuracy: ...
val_accuracy: ...

Epoch 2/5
...
accuracy: ...
val_accuracy: ...
📊 Understanding the training output

accuracy → Accuracy measured on the training images.
val_accuracy → Accuracy measured on the validation images.
Epoch 1/5 → The first of five training cycles.
🧠 What happens during training?
The CNN compares its predictions with the correct digit labels, calculates the error, and adjusts its internal weights. This process is repeated across the training data so that the model gradually becomes better at recognizing handwritten digits.
Important: Training may take some time depending on your computer and the TensorFlow configuration. When training finishes, the model can be evaluated and then saved as digit_cnn.keras.
🚀 Next: After training, we need to check how well the CNN performs on data it has not used for learning.
This is done in the model evaluation step.

11. Evaluate the Trained Model

After training, the program evaluates the CNN using the test dataset:

The test dataset contains images that were not used to train the model.

This gives us an indication of how well the CNN can recognize previously unseen handwritten digits.

💾 12. Save the Trained Model

Once training is complete, we save the trained CNN so that it can be used later without training the model again.

🧠 Trained model file
digit_cnn.keras
🐍 The model is saved using:
model.save("digit_cnn.keras")
Why is saving the model important?

Training a CNN takes time. Once the model has learned how to recognize handwritten digits, there is no need to train it again every time we want to use the application.

💡 We can simply load the saved model and use it to make predictions.
🔄 Train Once → Use Many Times
🧠 Train CNN 💾 Save Model 📂 Load Model 🤖 Predict
🔗 How does the final application use it?

The training program creates digit_cnn.keras.
The final recognition program loads this file and uses the learned CNN to recognize a digit drawn by the user.
🎯 Complete AI Pipeline
📚 MNIST Dataset → 🧠 CNN Training → 💾 digit_cnn.keras → 🖥️ Final Recognizer → ✏️ Draw Digit → 🤖 Prediction
🚀 The key idea: The saved `.keras` file contains the trained model. The final application does not need to learn from MNIST again; it simply loads the trained model and uses it for handwritten digit prediction.

13. How to Train the Model Yourself

If you want to train the CNN yourself, make sure your virtual environment is activated.

From the project folder, run:

The training process will begin.

You will see the training progress in the terminal.

After training is completed, the program creates:

in the project folder.

There are two ways to use this project.

⭐ Option 1 — Just Run the Completed Project

Use the supplied:

and run:

This is the Quick Start method.

🎓 Option 2 — Train the CNN Yourself

Run:

The program trains the CNN and creates a new:

You can then run:

This method is useful if you want to understand how the AI model is created.

🔄 15. Alternative Training Program

The project also includes an alternative training program:

step2_train_and_save.py
🧠 This is another complete training program. It performs the major steps required to create and save the CNN model.
⚙️ What does it do?
📚 Load MNIST
🖼️ Preprocess Images
🧠 Build CNN
🎯 Train Model
📈 Evaluate Model
💾 Save → digit_cnn.keras
▶️ You can use either training program:
🟦 Option 1
python step1_train_cnn.py
— OR —
🟩 Option 2 — Complete Training Script
python step2_train_and_save.py
⚠️ Do not run both training programs unnecessarily.

Both scripts are intended to perform the training workflow. Choose one of them when you want to experiment with model training.
💡 Which one should a beginner use?

If you simply want to understand and reproduce the complete training workflow, use step2_train_and_save.py. It trains the CNN, evaluates it, and saves the resulting digit_cnn.keras model for use by the final recognizer.
🔗 Remember the connection:
Training program → 💾 digit_cnn.keras → 🖥️ Final Digit Recognizer

Once the model has been saved, you do not need to train it again just to run the final application.

🔄 17. What Happens After Training?

Once training is complete, the project has a trained AI model that can be reused to recognize new handwritten digits.

🧠 Trained AI Model
digit_cnn.keras
🖥️ The final application loads this trained model and provides a drawing canvas where you can create a new handwritten digit.
✏️ You draw a digit
7
Example handwritten digit
⚙️ 16. What does the program do?
✏️ Your Drawing
🖼️ Image Preprocessing
🔲 Convert to 28 × 28 × 1
🧠 Trained CNN
🤖 Prediction + Confidence
🔍 Why is preprocessing necessary?
Your drawing is not immediately ready for the CNN. The program prepares it in the same general format used during training — including resizing it to 28 × 28, converting it to the required grayscale format, and scaling the pixel values.
This is where the project becomes interactive.

The model has already learned from the MNIST dataset. Now your own drawing becomes the input, and the trained CNN uses what it learned to make a prediction.
🧠 Learn once → 💾 Save → ✏️ Draw → 🤖 Predict

🎨 Step 3 — Drawing Canvas

Now that we understand how the CNN is trained, let’s look at the drawing canvas included in the project. It provides a simple way to create a handwritten digit using your mouse.

📄 The file responsible for this is:
step3_drawing_canvas.py
🖱️ It creates a graphical window where you can draw a handwritten digit using your mouse.

✏️ 1. What Does the Drawing Canvas Do?

The drawing canvas provides a simple digital space where you can create a handwritten digit. The drawing can then be saved as an image for further processing.

⚙️ Basic process
🖱️ Draw a Digit
🎨 Drawing Canvas
💾 Save Drawing
my_digit.png
🔢 For example, you can draw:
7
💾 You can save the drawing as:
my_digit.png
Important: The drawing canvas only creates the handwritten image. The CNN model is responsible for recognizing the digit.

The complete recognition process requires the drawing to be preprocessed into the format expected by the trained CNN before prediction.
🔗 Where does this fit in the project?

🎨 Drawing Canvas → 🖼️ Image → ⚙️ Preprocessing → 🧠 Trained CNN → 🎯 Prediction
🚀 Next: We will look at how the drawing is converted into an image format that the CNN can understand.

▶️ 2. Run the Drawing Canvas

Make sure your virtual environment is activated.

From the project folder, run:

python step3_drawing_canvas.py
🖥️ A drawing window will appear.
🖱️ Use your mouse to draw a digit on the canvas.

✏️ 3. Drawing the Digit

Use the mouse like a pen and draw a digit on the canvas.

For example:

✏️ Draw → 5

🎯 Try to make the digit reasonably clear and centered on the canvas.

🔬 You can experiment with different handwriting styles. This is one of the interesting parts of the project: seeing how the trained AI model responds to your own handwritten input.

Drawing Tip: Don’t worry if your handwriting is not perfect. Try several versions of the same digit and observe how the prediction changes.
🚀 Next: Once the digit has been drawn, the image can be saved and prepared for the next stage — image preprocessing before it is given to the trained CNN.

🧹 4. Clear the Canvas

If you make a mistake or want to draw a different digit, click:

🧹 Clear

This removes the current drawing so you can start again with a fresh canvas.

💾 5. Save the Drawing

After drawing your digit, click:

💾 Save

The program saves the drawing as:

my_digit.png

📁 The image is saved in the project folder.

📂 Your project folder may then contain:
Handwritten_Digit_Recognition/
│
├── digit_cnn.keras
├── final_digit_recognizer.py
├── my_digit.png
├── requirements.txt
├── step1_train_cnn.py
├── step2_train_and_save.py
└── step3_drawing_canvas.py
Remember: Clear lets you start a new drawing, while Save stores the current drawing as my_digit.png.
🚀 Next: The saved image can now be used as input for the next stage of the project, where the image is preprocessed and prepared for the CNN.

⭐ 6. Important: my_digit.png Is Optional

There is an important distinction between the drawing canvas program and the final recognizer.

🎨 Drawing Canvas Program
step3_drawing_canvas.py
This program is mainly useful for creating and saving a handwritten digit image.
📄 It creates: my_digit.png
🤖 Final Digit Recognizer
final_digit_recognizer.py
The final recognizer has its own drawing canvas. Therefore, it does not require my_digit.png to start the application.
▶️ You can run the completed recognizer directly
python final_digit_recognizer.py
💡 Key Point

You do not have to run Step 3 first.

If your goal is simply to test the completed AI application, you can run final_digit_recognizer.py directly.
🔎 At a Glance
🎨 step3_drawing_canvas.py → Creates and saves a drawing
📄 my_digit.png → Saved drawing image (optional)
🤖 final_digit_recognizer.py → Complete interactive digit recognizer
🚀 For the quickest test: Activate the virtual environment, make sure digit_cnn.keras is present, and run final_digit_recognizer.py.

🚀 7. The Final Application Is More Convenient

The final application combines the drawing and digit recognition process into a single interactive program.

🔄 Its workflow is:
✏️ Draw a Digit
🖼️ Image Preprocessing
🧠 Trained CNN Model
digit_cnn.keras
🤖 Prediction
🎯 Digit + Confidence
💡 Why is this more convenient?

You don’t need to create a separate image with the drawing canvas first. The final application provides its own canvas, preprocesses your drawing, sends it to the trained CNN, and immediately displays the prediction.
⭐ Recommended Program for Beginners
If you simply want to try the completed AI project, run:
python final_digit_recognizer.py
No separate drawing step is required.
The final recognizer already contains the drawing canvas, so you can start the application directly as long as the trained digit_cnn.keras file is available.
🎨 Draw → ⚙️ Process → 🧠 Recognize → 🎯 Predict

🖼️ 8. What Happens to Your Drawing?

When you draw a digit in the final application, the program does not simply send the raw 400 × 400 drawing directly to the CNN.

⚙️ The program first performs image preprocessing to convert your drawing into a form that matches the input format expected by the trained CNN.
🔄 The basic process is:
✏️ Your Drawing 400 × 400
🔄 Invert Image
🔍 Find the Digit
✂️ Crop Unnecessary Space
🎯 Center the Digit
📐 Resize to 28 × 28
📊 Normalize Pixel Values
🧠 Send to CNN
🎯 Prediction
Why is preprocessing necessary?

The CNN was trained using 28 × 28 MNIST images. Your drawing starts as a much larger image, so it must be converted into a compatible format before the CNN can make a prediction.
📐 From Your Drawing to CNN Input
400 × 400 28 × 28 × 1
💡 In simple terms: The preprocessing stage acts as a translator between your drawing and the CNN.

✏️ Your drawing is converted into the same general image format the CNN learned from during training.

🤖 Only after this conversion is the image passed to the trained model for digit recognition.

🎯 9. Predict the Digit

Once your drawing has been preprocessed, it is passed to the trained CNN. The model produces a probability for each of the 10 possible digits, from 0 to 9.

🔢 Possible digit classes
0 1 2 3 4 5 6 7 8 9
🧠 How is the digit selected?

The CNN calculates a probability for every digit. The program then selects the digit with the highest probability as its prediction.
📊 Example prediction
Predicted Digit: 7
Confidence: 98%
What does confidence mean?

The confidence value represents the model’s predicted probability for the selected digit. A higher value means the model assigned a stronger probability to that particular class.

The exact value can vary depending on the digit you draw, the way you write it, and how closely the drawing resembles patterns learned from the MNIST dataset.
🔍 Remember: The CNN does not receive the text “7” as input.

It receives the preprocessed image of your handwritten digit and calculates probabilities for all ten digit classes.
✏️ Drawing → ⚙️ Preprocessing → 🧠 CNN → 📊 10 Probabilities → 🎯 Highest Probability
🚀 Next: We will see how the final application allows you to clear the canvas, draw another digit, and test the CNN repeatedly.
⭐ Recommended Way to Demonstrate the Project

For a quick classroom, lab, or personal demonstration, you only need to run the completed recognizer.

▶️ Command Prompt
python final_digit_recognizer.py
🎬 Then follow these simple steps:
1. ✏️ Draw a digit on the canvas.
2. ▶️ Click Predict.
3. 🎯 Observe the predicted digit.
4. 📊 Observe the confidence value.
5. 🧹 Click Clear.
6. 🔄 Draw another digit and test again.
💡 Demonstration Tip

Try several digits and different handwriting styles. This makes the demonstration more interesting and lets you observe how the model’s prediction and confidence can change.
Complete Interactive Demonstration

✏️ Draw → 🎯 Predict → 📊 Check Confidence → 🧹 Clear → 🔄 Try Again
🚀 No retraining is required for the demonstration. The application uses the already-trained digit_cnn.keras model to recognize your handwritten digits.

🎯 What We Have Built

At this point, we have covered the complete practical workflow of our handwritten digit recognition project — from training the CNN to recognizing a digit drawn by the user.

📚 MNIST Dataset
🧠 CNN Training
💾 Trained Model
digit_cnn.keras
✏️ User Draws a Digit
⚙️ Image Preprocessing
🧠 CNN Prediction
🎯 Recognized Digit + Confidence
💡 In simple terms: The CNN first learns from thousands of handwritten examples in the MNIST dataset. After training, the learned model is saved as digit_cnn.keras.

The final application then allows you to draw a new digit, preprocesses the drawing, and sends it through the trained CNN to obtain a prediction.
The important achievement

We have gone from training an AI model to building an interactive application that can recognize your own handwritten digits.
📚 Learn → 🧠 Train → 💾 Save → ✏️ Draw → ⚙️ Process → 🤖 Predict → 🎯 Recognize

🛠️ Common Problems and Solutions

If you encounter an error while setting up or running the project, check the common problems below before troubleshooting further.

⚠️ Problem 💡 Solution
TensorFlow installation fails Use Python 3.12 for this project and install the packages inside the project’s virtual environment.
Wrong Python version is being used Create the virtual environment specifically with Python 3.12:

py -3.12 -m venv .venv
No module named tensorflow Activate .venv and install the project requirements:

python -m pip install -r requirements.txt
No module named PIL Install Pillow:

python -m pip install pillow
Model file not found Make sure digit_cnn.keras is in the same project folder as final_digit_recognizer.py.
Drawing application does not open Make sure you are using a standard Windows Python installation with Tkinter available.
One Important Tip — Python 3.12

If you have both Python 3.12 and Python 3.14 installed on your computer, you do not need to uninstall Python 3.14.

This project should use a virtual environment created with Python 3.12.
🔍 Quick Environment Check

If something is not working, first activate the virtual environment and run:
python --version
You should see something similar to:
Python 3.12.x
💡 Troubleshooting order: Check the Python version → activate .venv → install requirements.txt → verify TensorFlow → check digit_cnn.keras → run the application.

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »