Update model.py
Browse files
model.py
CHANGED
|
@@ -1,27 +1,32 @@
|
|
| 1 |
-
import
|
|
|
|
| 2 |
from PIL import Image
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
label,
|
| 10 |
-
round(confidence, 3),
|
| 11 |
-
{k: round(v, 3) for k, v in probs.items()}
|
| 12 |
-
)
|
| 13 |
-
|
| 14 |
-
demo = gr.Interface(
|
| 15 |
-
fn=classify_image,
|
| 16 |
-
inputs=gr.Image(type="pil", label="Upload an image"),
|
| 17 |
-
outputs=[
|
| 18 |
-
gr.Label(label="Predicted Class"),
|
| 19 |
-
gr.Number(label="Confidence"),
|
| 20 |
-
gr.JSON(label="All Probabilities")
|
| 21 |
-
],
|
| 22 |
-
title="Animal Image Classifier",
|
| 23 |
-
description="Upload an image and the model will predict the animal."
|
| 24 |
)
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|