Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
from tensorflow.keras.models import load_model
|
| 5 |
+
import cv2
|
| 6 |
+
from PIL import Image, ImageOps
|
| 7 |
+
|
| 8 |
+
# Load the trained model
|
| 9 |
+
model = load_model('digit_recognizer_model.h5')
|
| 10 |
+
|
| 11 |
+
# Streamlit app title
|
| 12 |
+
st.title("Handwritten Digit Recognizer")
|
| 13 |
+
|
| 14 |
+
# Instructions
|
| 15 |
+
st.write("Draw a digit below and click 'Predict' to see the model's prediction.")
|
| 16 |
+
|
| 17 |
+
# Create a canvas component
|
| 18 |
+
from streamlit_drawable_canvas import st_canvas
|
| 19 |
+
|
| 20 |
+
# Set up the canvas
|
| 21 |
+
canvas_result = st_canvas(
|
| 22 |
+
fill_color="black", # Drawing background color
|
| 23 |
+
stroke_width=10,
|
| 24 |
+
stroke_color="white",
|
| 25 |
+
background_color="black",
|
| 26 |
+
height=280,
|
| 27 |
+
width=280,
|
| 28 |
+
drawing_mode="freedraw",
|
| 29 |
+
key="canvas",
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Predict button
|
| 33 |
+
if st.button('Predict'):
|
| 34 |
+
if canvas_result.image_data is None:
|
| 35 |
+
st.write("Please draw a digit first!")
|
| 36 |
+
else:
|
| 37 |
+
# Convert the canvas image to grayscale
|
| 38 |
+
img = cv2.cvtColor(canvas_result.image_data.astype('uint8'), cv2.COLOR_BGR2GRAY)
|
| 39 |
+
|
| 40 |
+
# Resize to 28x28 pixels, the input size for the model
|
| 41 |
+
img_resized = cv2.resize(img, (28, 28))
|
| 42 |
+
|
| 43 |
+
# Invert the image (white background, black digit)
|
| 44 |
+
img_resized = cv2.bitwise_not(img_resized)
|
| 45 |
+
|
| 46 |
+
# Normalize the image
|
| 47 |
+
img_resized = img_resized / 255.0
|
| 48 |
+
|
| 49 |
+
# Reshape for the model: (1, 28, 28, 1)
|
| 50 |
+
img_resized = img_resized.reshape(1, 28, 28, 1)
|
| 51 |
+
|
| 52 |
+
# Predict the digit
|
| 53 |
+
prediction = model.predict(img_resized)
|
| 54 |
+
predicted_digit = np.argmax(prediction)
|
| 55 |
+
|
| 56 |
+
# Display the prediction
|
| 57 |
+
st.write(f"Predicted Digit: {predicted_digit}")
|
| 58 |
+
|
| 59 |
+
# Clear button
|
| 60 |
+
if st.button('Clear'):
|
| 61 |
+
st.experimental_rerun()
|