brxerq commited on
Commit
f0e70db
·
verified ·
1 Parent(s): d495763

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -11
app.py CHANGED
@@ -5,11 +5,15 @@ import tensorflow as tf
5
  import tensorflow_hub as hub
6
  import cv2
7
 
8
- # Ensure compatibility between TensorFlow and TensorFlow Hub
9
- tf.keras.utils.get_custom_objects()['KerasLayer'] = hub.KerasLayer
10
 
11
- # Load the model with the correct path and custom objects
12
- model = tf.keras.models.load_model('bird_model4.h5', custom_objects={'KerasLayer': hub.KerasLayer})
 
 
 
 
13
 
14
  # Load class labels from the text file
15
  train_info = []
@@ -18,20 +22,20 @@ with open('labelwithspace.txt', 'r') as file:
18
 
19
  # Function to preprocess the image and make predictions
20
  def predict_image(image):
21
- # Resize the image to the expected input shape
22
  img = cv2.resize(image, (224, 224))
23
- img = img / 255.0 # Normalize the image to the range [0, 1]
24
 
25
- # Make predictions using the loaded model
26
  predictions = model.predict(img[np.newaxis, ...])[0]
27
- top_classes = np.argsort(predictions)[-3:][::-1] # Get indices of top 3 predictions
28
- top_class = top_classes[0] # Index of the highest prediction
29
- label = train_info[top_class] # Retrieve the class label using the index
30
  return label
31
 
32
  # Define the Gradio interface
33
  input_image = gr.inputs.Image(shape=(224, 224))
34
  output_label = gr.outputs.Label()
35
 
36
- # Launch the Gradio app
37
  gr.Interface(fn=predict_image, inputs=input_image, outputs=output_label, capture_session=True).launch()
 
5
  import tensorflow_hub as hub
6
  import cv2
7
 
8
+ # Register KerasLayer from TensorFlow Hub
9
+ tf.keras.utils.get_custom_objects().update({'KerasLayer': hub.KerasLayer})
10
 
11
+ # Load the model and specify custom objects
12
+ try:
13
+ model = tf.keras.models.load_model('bird_model4.h5', custom_objects={'KerasLayer': hub.KerasLayer})
14
+ except ValueError as e:
15
+ print("Error loading the model:", e)
16
+ exit()
17
 
18
  # Load class labels from the text file
19
  train_info = []
 
22
 
23
  # Function to preprocess the image and make predictions
24
  def predict_image(image):
25
+ # Resize and normalize the image
26
  img = cv2.resize(image, (224, 224))
27
+ img = img / 255.0
28
 
29
+ # Make predictions
30
  predictions = model.predict(img[np.newaxis, ...])[0]
31
+ top_classes = np.argsort(predictions)[-3:][::-1] # Indices of top 3 predictions
32
+ top_class = top_classes[0] # Index of the highest probability class
33
+ label = train_info[top_class] # Get the corresponding label
34
  return label
35
 
36
  # Define the Gradio interface
37
  input_image = gr.inputs.Image(shape=(224, 224))
38
  output_label = gr.outputs.Label()
39
 
40
+ # Launch the Gradio interface
41
  gr.Interface(fn=predict_image, inputs=input_image, outputs=output_label, capture_session=True).launch()