papasega commited on
Commit
38b45ca
·
verified ·
1 Parent(s): aacafac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -18
app.py CHANGED
@@ -1,28 +1,55 @@
1
  import tensorflow as tf
2
  import gradio as gr
3
  import numpy as np
 
4
 
5
- # Load the CNN model from the .h5 file
6
  model = tf.keras.models.load_model('TP_MNIST_CNN_model.h5')
7
 
8
- def predict_digit(image):
9
- # Preprocess the input image
10
- image = np.expand_dims(image, axis=0) # Add batch dimension
11
- image = image / 255.0 # Normalize pixel values
 
 
 
 
 
 
12
 
13
- # Make predictions
14
- predictions = model.predict(image)
 
15
 
16
- # Get the predicted digit
17
- predicted_digit = np.argmax(predictions)
 
18
 
19
- return predicted_digit
 
 
 
 
 
 
 
 
20
 
21
- # Define Gradio interface
22
- gr.Interface(
23
- title="Reconnaissance d'écriture manuscrite des données MNIST by PSW",
24
- fn=predict_digit,
25
- inputs=gr.Sketchpad(label="Desinner le chiffre ici", height=350, width=800),
26
- outputs="number",
27
- live=True
28
- ).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
1
  import tensorflow as tf
2
  import gradio as gr
3
  import numpy as np
4
+ import cv2
5
 
6
+ # Load model
7
  model = tf.keras.models.load_model('TP_MNIST_CNN_model.h5')
8
 
9
+ def preprocess_and_predict(input_data):
10
+ if input_data is None:
11
+ return None
12
+
13
+ # Gradio 4.x Sketchpad returns a dict usually: {'composite': array, 'layers': [...]}
14
+ # We take the composite image
15
+ if isinstance(input_data, dict):
16
+ image = input_data['composite']
17
+ else:
18
+ image = input_data
19
 
20
+ # 1. Resize to MNIST standard (28x28)
21
+ # Interpolation AREA is better for shrinking images without losing thin lines
22
+ image = cv2.resize(image, (28, 28), interpolation=cv2.INTER_AREA)
23
 
24
+ # 2. Convert to Grayscale (if RGB/RGBA)
25
+ if len(image.shape) == 3:
26
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
27
 
28
+ # 3. Normalize & Invert Logic
29
+ # MNIST is White digits on Black background.
30
+ # If user draws Black on White, we must invert.
31
+ # Check mean pixel intensity: if high (>127), background is likely white.
32
+ if np.mean(image) > 127:
33
+ image = 255 - image
34
+
35
+ # 4. Normalize 0-1
36
+ image = image / 255.0
37
 
38
+ # 5. Reshape for Model (Batch, Height, Width, Channels)
39
+ image = image.reshape(1, 28, 28, 1)
40
+
41
+ # Prediction
42
+ predictions = model.predict(image, verbose=0)
43
+ return int(np.argmax(predictions))
44
+
45
+ # Modern Gradio 4 Interface
46
+ iface = gr.Interface(
47
+ fn=preprocess_and_predict,
48
+ inputs=gr.Sketchpad(label="Dessinez un chiffre", type="numpy"),
49
+ outputs="label",
50
+ title="MNIST Digit Recognition",
51
+ description="Reconnaissance de chiffres manuscrits via CNN. Dessinez au centre.",
52
+ allow_flagging="never"
53
+ )
54
+
55
+ iface.launch()