AIOmarRehan commited on
Commit
830c435
·
verified ·
1 Parent(s): 10b93bd

Update model.py

Browse files
Files changed (1) hide show
  1. model.py +31 -39
model.py CHANGED
@@ -1,40 +1,32 @@
1
- import tensorflow as tf
2
- import numpy as np
3
- from PIL import Image
4
-
5
- # Load your trained CNN model
6
- model = tf.keras.models.load_model("saved_model/Inception_V3_Animals_Classification.h5")
7
-
8
- # Same label order you used when training (from LabelEncoder)
9
- CLASS_NAMES = ["Cat", "Dog", "Snake"]
10
-
11
- def preprocess_image(img: Image.Image, target_size=(256, 256)):
12
- """
13
- Preprocess a PIL image to match training pipeline:
14
- - Convert to RGB
15
- - Resize
16
- - Convert to float32
17
- - Normalize to [0,1]
18
- - Add batch dimension
19
- """
20
- img = img.convert("RGB") # ensure 3 channels
21
- img = img.resize(target_size)
22
- img = np.array(img).astype("float32") / 255.0 # normalize
23
- img = np.expand_dims(img, axis=0) # (1, 256, 256, 3)
24
- return img
25
-
26
- def predict(img: Image.Image):
27
- # Apply preprocessing
28
- input_tensor = preprocess_image(img)
29
-
30
- # Model prediction
31
- preds = model.predict(input_tensor)
32
- probs = preds[0]
33
-
34
- class_idx = int(np.argmax(probs))
35
- confidence = float(np.max(probs))
36
-
37
- # Map all probabilities
38
- prob_dict = {CLASS_NAMES[i]: float(probs[i]) for i in range(len(CLASS_NAMES))}
39
-
40
  return CLASS_NAMES[class_idx], confidence, prob_dict
 
1
+ import tensorflow as tf
2
+ import numpy as np
3
+ from PIL import Image
4
+ import os
5
+
6
+ MODEL_PATH = os.path.join(
7
+ os.path.dirname(__file__),
8
+ "saved_model",
9
+ "Inception_V3_Animals_Classification.h5"
10
+ )
11
+
12
+ model = tf.keras.models.load_model(MODEL_PATH)
13
+
14
+ CLASS_NAMES = ["Cat", "Dog", "Snake"]
15
+
16
+ def preprocess_image(img: Image.Image, target_size=(256, 256):
17
+ img = img.convert("RGB")
18
+ img = img.resize(target_size)
19
+ img = np.array(img).astype("float32") / 255.0
20
+ img = np.expand_dims(img, axis=0)
21
+ return img
22
+
23
+ def predict(img: Image.Image):
24
+ input_tensor = preprocess_image(img)
25
+ preds = model.predict(input_tensor)[0]
26
+
27
+ class_idx = int(np.argmax(preds))
28
+ confidence = float(np.max(preds))
29
+
30
+ prob_dict = {CLASS_NAMES[i]: float(preds[i]) for i in range(len(CLASS_NAMES))}
31
+
 
 
 
 
 
 
 
 
32
  return CLASS_NAMES[class_idx], confidence, prob_dict