|
from PIL import ImageGrab |
|
import tensorflow as tf |
|
import numpy as np |
|
import tkinter as tk |
|
|
|
|
|
model = tf.keras.models.load_model("./model/model.h5") |
|
model.load_weights("./model/model_weights.h5") |
|
|
|
|
|
root = tk.Tk() |
|
root.title("Handwritten Digit Recognition") |
|
|
|
|
|
canvas = tk.Canvas(root, width=280, height=250, bg='black') |
|
canvas.pack() |
|
|
|
screen = tk.Label(root, text="Draw a number", font=("Helvetica", 24)) |
|
screen.pack() |
|
|
|
|
|
|
|
def start_draw(event): |
|
global last_x, last_y |
|
last_x, last_y = event.x, event.y |
|
|
|
|
|
def draw(event): |
|
global last_x, last_y |
|
x, y = event.x, event.y |
|
canvas.create_line((last_x, last_y, x, y), fill="white", width=10) |
|
last_x, last_y = x, y |
|
|
|
|
|
|
|
def predict_digit(): |
|
x = root.winfo_rootx() + canvas.winfo_x() |
|
y = root.winfo_rooty() + canvas.winfo_y() |
|
x1 = x + canvas.winfo_width() |
|
y1 = y + canvas.winfo_height() |
|
|
|
|
|
|
|
|
|
img = ImageGrab.grab((x+31, y+38, x1, y1)) |
|
|
|
|
|
|
|
|
|
img = img.convert('L') |
|
img = img.resize((28, 28)) |
|
img_array = np.array(img) |
|
img_array = img_array.reshape(1, 28, 28, 1) / 255.0 |
|
prediction = model.predict(img_array) |
|
|
|
|
|
predicted_digit = np.argmax(prediction) |
|
screen.config(text="Predicted digit: " + str(predicted_digit)) |
|
|
|
|
|
|
|
def clear_canvas(): |
|
canvas.delete("all") |
|
screen.config(text="Draw a number") |
|
|
|
|
|
|
|
canvas.bind("<Button-1>", start_draw) |
|
canvas.bind("<B1-Motion>", draw) |
|
|
|
|
|
predict_button = tk.Button(root, text="Predict", command=predict_digit) |
|
predict_button.pack() |
|
|
|
reset_button = tk.Button(root, text="Clear", command=clear_canvas) |
|
reset_button.pack() |
|
|
|
|
|
root.mainloop() |
|
|