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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -10
app.py CHANGED
@@ -5,27 +5,28 @@ import tensorflow as tf
5
  import tensorflow_hub as hub
6
  import cv2
7
 
8
- # Define a dictionary to map the custom layer to its implementation
9
- custom_objects = {'KerasLayer': hub.KerasLayer}
10
 
11
- # Load your model (ensure the path to the model file is correct)
12
- model = tf.keras.models.load_model('bird_model4.h5', custom_objects=custom_objects)
13
 
14
- # Load the class labels from the text file
15
  train_info = []
16
  with open('labelwithspace.txt', 'r') as file:
17
  train_info = [line.strip() for line in file.readlines()]
18
 
19
  # Function to preprocess the image and make predictions
20
  def predict_image(image):
21
- # Resize the image to the model's input size
22
  img = cv2.resize(image, (224, 224))
23
- img = img / 255.0 # Normalize the image
24
- # Make predictions using the model
 
25
  predictions = model.predict(img[np.newaxis, ...])[0]
26
  top_classes = np.argsort(predictions)[-3:][::-1] # Get indices of top 3 predictions
27
- top_class = top_classes[0] # Index of the top prediction
28
- label = train_info[top_class] # Retrieve the label using the index
29
  return label
30
 
31
  # Define the Gradio interface
 
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 = []
16
  with open('labelwithspace.txt', 'r') as file:
17
  train_info = [line.strip() for line in file.readlines()]
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