|
import numpy as np |
|
import gradio as gr |
|
import tensorflow as tf |
|
import cv2 |
|
|
|
|
|
model = tf.keras.models.load_model("./sketch_recognition_numbers_model.h5") |
|
|
|
|
|
labels = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] |
|
|
|
def predict(data): |
|
|
|
img = data["composite"] |
|
img = np.array(img) |
|
|
|
|
|
if img.shape[-1] == 4: |
|
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB) |
|
|
|
|
|
if img.shape[-1] == 3: |
|
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) |
|
|
|
|
|
img = cv2.resize(img, (28, 28)) |
|
|
|
|
|
img = img / 255.0 |
|
|
|
|
|
img = img.reshape(1, 28, 28, 1) |
|
|
|
|
|
preds = model.predict(img)[0] |
|
|
|
print(preds) |
|
|
|
|
|
top_3_classes = np.argsort(preds)[-3:][::-1] |
|
top_3_probs = preds[top_3_classes] |
|
class_names = [labels[i] for i in top_3_classes] |
|
print(class_names, top_3_probs, top_3_classes) |
|
|
|
|
|
return {class_names[i]: float(top_3_probs[i]) for i in range(3)} |
|
|
|
|
|
title = "Welcome to your first sketch recognition app!" |
|
head = ( |
|
"<center>" |
|
"<img src='./mnist-classes.png' width=400>" |
|
"<p>The model is trained to classify numbers (from 0 to 9). " |
|
"To test it, draw your number in the space provided (use the editing tools in the image editor).</p>" |
|
"</center>" |
|
) |
|
ref = "Find the complete code [here](https://github.com/ovh/ai-training-examples/tree/main/apps/gradio/sketch-recognition)." |
|
|
|
with gr.Blocks(title=title) as demo: |
|
|
|
gr.Markdown(head) |
|
gr.Markdown(ref) |
|
|
|
with gr.Row(): |
|
|
|
im = gr.Sketchpad(type="numpy", label="Draw your digit here (use brush and eraser)") |
|
|
|
|
|
label = gr.Label(num_top_classes=3, label="Predictions") |
|
|
|
|
|
im.change(predict, inputs=im, outputs=label) |
|
|
|
demo.launch(share=True) |