cisemh commited on
Commit
13f8a14
·
verified ·
1 Parent(s): 14ae290

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -43
app.py CHANGED
@@ -7,55 +7,33 @@ import numpy as np
7
  title = "Welcome to your first sketch recognition app!"
8
  head = "<center>The robot was trained to classify numbers (0 to 9). To test it, write your number in the space provided.</center>"
9
 
10
- # Image size and label mapping
11
- img_size = 28
12
- labels = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
13
 
14
  # Load the trained model
15
  model = tf.keras.models.load_model("number_recognition_model_colab.keras")
16
 
17
- def predict(img):
18
- try:
19
- # Convert the input image to a NumPy array if needed
20
- if not isinstance(img, np.ndarray):
21
- img = np.array(img)
22
 
23
- # Convert the image to grayscale if it's not already
24
- if img.ndim == 3 and img.shape[-1] == 3:
25
- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
26
- elif img.ndim == 2:
27
- img = np.expand_dims(img, axis=-1)
28
 
29
- # Resize the image to the expected input size
30
- img = cv2.resize(img, (img_size, img_size))
31
 
32
- # Normalize the image
33
- img = img.astype('float32') / 255.0
34
- img = img.reshape(1, img_size, img_size, 1)
35
 
36
- # Get predictions from the model
37
- preds = model.predict(img)[0]
38
 
39
- # Return the predicted probabilities for each class
40
- return {label: float(pred) for label, pred in zip(labels, preds)}
41
-
42
- except Exception as e:
43
- return {"Error": str(e)}
44
-
45
- # Use a sketchpad as input for drawing
46
- input_component = gr.Sketchpad()
47
-
48
- # Output will show the top 3 predicted classes
49
- output_component = gr.Label(num_top_classes=3)
50
-
51
- # Create the Gradio interface
52
- interface = gr.Interface(
53
- fn=predict,
54
- inputs=input_component,
55
- outputs=output_component,
56
- title=title,
57
- description=head
58
- )
59
-
60
- # Launch the interface
61
- interface.launch(debug=True)
 
7
  title = "Welcome to your first sketch recognition app!"
8
  head = "<center>The robot was trained to classify numbers (0 to 9). To test it, write your number in the space provided.</center>"
9
 
 
 
 
10
 
11
  # Load the trained model
12
  model = tf.keras.models.load_model("number_recognition_model_colab.keras")
13
 
 
 
 
 
 
14
 
15
+ def recognize_digit(image):
16
+ if image is not None:
17
+ image = image.reshape((1, 28, 28, 1)).astype('float32')/255
 
 
18
 
19
+ prediction = model.predict(image)
 
20
 
21
+ return {str(i): float(prediction[0][i]) for i in range(10)}
22
+ else:
23
+ return ''
24
 
 
 
25
 
26
+ # Build and launch the Gradio interface
27
+ demo = gr.Interface(
28
+ fn = recognize_digit,
29
+ inputs = gr.Image(
30
+ shape=(28, 28),
31
+ image_mode='L',
32
+ invert_colors=True,
33
+ source='canvas',
34
+ brush_radius=1,
35
+ tool="color-sketch",
36
+ ),
37
+ outputs = gr.Label(num_top_classes=3),
38
+ live = True
39
+ ).launch(share=True)