import os import tkinter as tk import numpy as np import tensorflow as tf from PIL import Image, ImageDraw def get_or_train_model(model_path="digit_model.keras"): """Loads an existing CNN model or trains a new one if it doesn't exist.""" if os.path.exists(model_path): print("Loading existing model...") return tf.keras.models.load_model(model_path) print("Training model for the first time... This will take a moment.") # Load MNIST dataset (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Preprocess: reshape to include the channel dimension and normalize to 0-1 x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0 x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0 # Build CNN architecture model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Conv2D(64, kernel_size=(3, 3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) # Compile and train model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=5, batch_size=128, validation_split=0.1) # Save the model so we don't have to retrain next time model.save(model_path) return model class DigitRecognizerApp: def __init__(self, root, model): self.root = root self.root.title("Handwritten Digit Recognizer") self.model = model self.canvas_width = 280 self.canvas_height = 280 self.brush_size = 12 # Initialize Tkinter Canvas self.canvas = tk.Canvas(self.root, width=self.canvas_width, height=self.canvas_height, bg="black", cursor="cross") self.canvas.grid(row=0, column=0, columnspan=2, pady=10) self.canvas.bind("", self.paint) # Initialize an invisible PIL Image and Draw object to capture the input accurately self.image = Image.new("L", (self.canvas_width, self.canvas_height), 0) self.draw = ImageDraw.Draw(self.image) # UI Buttons & Labels self.predict_btn = tk.Button(self.root, text="Predict", command=self.predict_digit, font=("Helvetica", 12)) self.predict_btn.grid(row=1, column=0, pady=5) self.clear_btn = tk.Button(self.root, text="Clear", command=self.clear_canvas, font=("Helvetica", 12)) self.clear_btn.grid(row=1, column=1, pady=5) self.result_label = tk.Label(self.root, text="Draw a digit and click Predict", font=("Helvetica", 14)) self.result_label.grid(row=2, column=0, columnspan=2, pady=10) def paint(self, event): """Draws white strokes on a black background, matching MNIST formatting.""" x1, y1 = (event.x - self.brush_size), (event.y - self.brush_size) x2, y2 = (event.x + self.brush_size), (event.y + self.brush_size) # Draw on the visible Tkinter canvas self.canvas.create_oval(x1, y1, x2, y2, fill="white", outline="white") # Draw on the invisible PIL Image concurrently self.draw.ellipse([x1, y1, x2, y2], fill="white") def clear_canvas(self): """Wipes both the Tkinter canvas and the PIL image.""" self.canvas.delete("all") self.image = Image.new("L", (self.canvas_width, self.canvas_height), 0) self.draw = ImageDraw.Draw(self.image) self.result_label.config(text="Draw a digit and click Predict") def predict_digit(self): """Processes the drawn image and passes it to the CNN model.""" # Resize image from 280x280 to 28x28 (MNIST standard) using high-quality downsampling img_resized = self.image.resize((28, 28), Image.Resampling.LANCZOS) # Convert to numpy array, scale to 0-1 range, and reshape for the model input img_array = np.array(img_resized) img_array = img_array.reshape(1, 28, 28, 1).astype('float32') / 255.0 # Pass through CNN model prediction = self.model.predict(img_array) digit = np.argmax(prediction) confidence = np.max(prediction) * 100 # Update UI self.result_label.config(text=f"Prediction: {digit} (Confidence: {confidence:.2f}%)") if __name__ == "__main__": # Ensure TensorFlow ignores purely informational logs os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 1. Prepare Model cnn_model = get_or_train_model() # 2. Launch App root = tk.Tk() app = DigitRecognizerApp(root, cnn_model) root.mainloop()