hb-setosys commited on
Commit
b42a3d4
·
verified ·
1 Parent(s): 5d13cc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -15
app.py CHANGED
@@ -1,31 +1,39 @@
1
  import gradio as gr
2
  import tensorflow as tf
3
- from tensorflow.keras.applications import ResNet152, preprocess_input, decode_predictions
4
  from tensorflow.keras.preprocessing.image import img_to_array
5
  from PIL import Image
6
  import numpy as np
7
 
8
  # Load the pre-trained ResNet152 model
9
- MODEL_PATH = "resnet152-image-classifier.h5" # Directory where the model is saved
10
- model = tf.keras.models.load_model(MODEL_PATH)
 
 
 
 
11
 
12
  def predict_image(image):
13
  """
14
- This function processes the uploaded image and returns the top 3 predictions.
15
  """
16
- # Preprocess the image
17
- image = image.resize((224, 224)) # ResNet152 expects 224x224 input
18
- image_array = img_to_array(image)
19
- image_array = preprocess_input(image_array) # Normalize the image
20
- image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
 
21
 
22
- # Get predictions
23
- predictions = model.predict(image_array)
24
- decoded_predictions = decode_predictions(predictions, top=3)[0]
25
 
26
- # Format predictions as a dictionary
27
- results = {label: f"{confidence * 100:.2f}%" for _, label, confidence in decoded_predictions}
28
- return results
 
 
 
29
 
30
  # Create the Gradio interface
31
  interface = gr.Interface(
 
1
  import gradio as gr
2
  import tensorflow as tf
3
+ from tensorflow.keras.applications.resnet import ResNet152, preprocess_input, decode_predictions
4
  from tensorflow.keras.preprocessing.image import img_to_array
5
  from PIL import Image
6
  import numpy as np
7
 
8
  # Load the pre-trained ResNet152 model
9
+ MODEL_PATH = "resnet152-image-classifier.h5" # Path to the saved model
10
+ try:
11
+ model = tf.keras.models.load_model(MODEL_PATH)
12
+ except Exception as e:
13
+ print(f"Error loading model: {e}")
14
+ exit()
15
 
16
  def predict_image(image):
17
  """
18
+ Process the uploaded image and return the top 3 predictions.
19
  """
20
+ try:
21
+ # Preprocess the image
22
+ image = image.resize((224, 224)) # ResNet152 expects 224x224 input
23
+ image_array = img_to_array(image)
24
+ image_array = preprocess_input(image_array) # Normalize the image
25
+ image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
26
 
27
+ # Get predictions
28
+ predictions = model.predict(image_array)
29
+ decoded_predictions = decode_predictions(predictions, top=3)[0]
30
 
31
+ # Format predictions as a dictionary
32
+ results = {label: f"{confidence * 100:.2f}%" for _, label, confidence in decoded_predictions}
33
+ return results
34
+
35
+ except Exception as e:
36
+ return {"Error": str(e)}
37
 
38
  # Create the Gradio interface
39
  interface = gr.Interface(