def paint(event):
x1, y1 = (event.x - 10), (event.y - 10)
x2, y2 = (event.x + 10), (event.y + 10)
canvas.create_oval(x1, y1, x2, y2, fill="black", width=1)
draw.line([x1, y1, x2, y2], fill="black", width=1)
Function to clear canvas
def clear():
canvas.delete("all")
draw.rectangle([0, 0, 280, 280], fill="white")
def recognize_digit():
HWND = canvas.winfo_id()
rect = (canvas.winfo_rootx(), canvas.winfo_rooty(), canvas.winfo_rootx() + canvas.winfo_width(),
canvas.winfo_rooty() + canvas.winfo_height())
im = ImageGrab.grab(rect)
# Convert to grayscale
image_gray = im.convert('L')
# Resize and pad the image to match MNIST dimensions (28x28)
width, height = image_gray.size
if width > height:
new_height = 28
new_width = int(width * (28 / height))
else:
new_width = 28
new_height = int(height * (28 / width))
image_resized = image_gray.resize((new_width, new_height))
padded_image = Image.new('L', (28, 28), color=255) # Create a white background
padded_image.paste(image_resized, ((28 - new_width) // 2, (28 - new_height) // 2))
# Invert colors (black digit on white background)
inverted_image = ImageOps.invert(padded_image)
# Convert image to array
img_array = np.array(inverted_image)
# Normalize pixel values
img_array_normalized = img_array.astype('float32') / 255.0