realmanise's picture
Update app.py
16bfadb verified
Raw History Blame Contribute Delete
1.62 kB
import gradio as gr
import tensorflow as tf
import numpy as np
import cv2
model = tf.keras.models.load_model('my_model (1).keras')
def center_and_resize(img):
# 1. Find the bounding box of the digit
coords = cv2.findNonZero(img)
x, y, w, h = cv2.boundingRect(coords)
# 2. Extract and create a square frame with padding
digit = img[y:y+h, x:x+w]
scale = 20.0 / max(w, h)
new_w, new_h = int(w * scale), int(h * scale)
digit = cv2.resize(digit, (new_w, new_h))
# 3. Paste into the center of a 28x28 black canvas
canvas = np.zeros((28, 28), dtype=np.uint8)
dx, dy = (28 - new_w) // 2, (28 - new_h) // 2
canvas[dy:dy+new_h, dx:dx+new_w] = digit
return canvas
def predict_digit(sketchpad_data):
# Extract the drawing layer
img = sketchpad_data['composite']
# Preprocess: Grayscale -> Invert -> Threshold -> Center
img = cv2.cvtColor(img, cv2.COLOR_RGBA2GRAY)
_, img = cv2.threshold(img, 50, 255, cv2.THRESH_BINARY)
# If the canvas is empty, return zeros
if cv2.countNonZero(img) == 0:
return {str(i): 0.0 for i in range(10)}
img = center_and_resize(img)
# Normalize and prepare for model
img = img.astype('float32') / 255.0
img = np.expand_dims(img, axis=(0, -1))
# Predict
prediction = model.predict(img)
return {str(i): float(prediction[0][i]) for i in range(10)}
demo = gr.Interface(
fn=predict_digit,
inputs=gr.Sketchpad(label="Draw a digit", type="numpy"),
outputs=gr.Label(num_top_classes=3),
title="Robust MNIST Classifier"
)
demo.launch()