hb-setosys commited on
Commit
d70585e
·
verified ·
1 Parent(s): 044b146

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -33
app.py CHANGED
@@ -1,43 +1,31 @@
1
- import gradio as gr # Ensure you import gradio correctly
2
  import tensorflow as tf
3
  import numpy as np
 
4
 
5
- # Load the Keras model
6
  model = tf.keras.models.load_model("denis_mnist_cnn_model.h5")
7
 
8
- # Define a function to preprocess input and make predictions
9
- def predict(image):
10
- # Convert image to a numpy array
11
  image = np.array(image)
12
-
13
- # Resize the image to the expected shape (28, 28, 3) for RGB images
14
- image = tf.image.resize(image, (28, 28)) # Resize to 28x28 pixels
15
-
16
- # Check if the image is grayscale (single channel), and convert to RGB if necessary
17
- if image.shape[-1] == 1: # If it's grayscale (single channel)
18
- image = np.repeat(image, 3, axis=-1) # Convert grayscale to RGB by repeating the channel
19
-
20
- # Normalize the image
21
- image = image / 255.0
22
-
23
- # Add batch dimension
24
- image = np.expand_dims(image, axis=0) # Add batch dimension to match the model's expected input shape (1, 28, 28, 3)
25
-
26
- # Perform prediction
27
- prediction = model.predict(image)
28
-
29
- # Get the predicted class (index of the highest probability)
30
- predicted_class = np.argmax(prediction)
31
-
32
- # Return prediction as JSON (with the predicted class label)
33
  return {"prediction": int(predicted_class)}
34
 
35
  # Create a Gradio interface
36
- interface = gr.Interface(
37
- fn=predict,
38
- inputs="image", # Image input for testing
39
- outputs="json" # JSON output for prediction results
40
- )
41
 
42
- # Launch the interface
43
- interface.launch(share=True)
 
 
1
+ import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
+ from PIL import Image
5
 
6
+ # Load the trained model
7
  model = tf.keras.models.load_model("denis_mnist_cnn_model.h5")
8
 
9
+ # Preprocessing function for images
10
+ def preprocess_image(image):
11
+ # Resize the image to 28x28 as expected by the model
12
  image = np.array(image)
13
+ image = tf.image.resize(image, (28, 28)) # Resize to 28x28
14
+ image = tf.image.grayscale_to_rgb(image) # Convert grayscale to RGB (3 channels)
15
+ image = image / 255.0 # Normalize pixel values to [0, 1]
16
+ image = np.expand_dims(image, axis=0) # Add batch dimension
17
+ return image
18
+
19
+ # Function to make predictions
20
+ def predict(image):
21
+ image = preprocess_image(image)
22
+ prediction = model.predict(image) # Predict
23
+ predicted_class = np.argmax(prediction, axis=-1)[0] # Get the predicted class
 
 
 
 
 
 
 
 
 
 
24
  return {"prediction": int(predicted_class)}
25
 
26
  # Create a Gradio interface
27
+ interface = gr.Interface(fn=predict, inputs="image", outputs="json")
 
 
 
 
28
 
29
+ # Launch the Gradio interface
30
+ if __name__ == "__main__":
31
+ interface.launch()