Update model.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import tensorflow as tfimport numpy as npfrom PIL import Image# Load your trained CNN modelmodel = tf.keras.models.load_model("saved_model/Inception_V3_Animals_Classification.h5")# Same label order you used when training (from LabelEncoder)CLASS_NAMES = ["Cat", "Dog", "Snake"]def preprocess_image(img: Image.Image, target_size=(256, 256)):"""Preprocess a PIL image to match training pipeline:- Convert to RGB- Resize- Convert to float32- Normalize to [0,1]- Add batch dimension"""img = img.convert("RGB") # ensure 3 channelsimg = img.resize(target_size)img = np.array(img).astype("float32") / 255.0 # normalizeimg = np.expand_dims(img, axis=0) # (1, 256, 256, 3)return imgdef predict(img: Image.Image):# Apply preprocessinginput_tensor = preprocess_image(img)# Model predictionpreds = model.predict(input_tensor)probs = preds[0]class_idx = int(np.argmax(probs))confidence = float(np.max(probs))# Map all probabilitiesprob_dict = {CLASS_NAMES[i]: float(probs[i]) for i in range(len(CLASS_NAMES))}return CLASS_NAMES[class_idx], confidence, prob_dict1234567891011121314151617181920212223242526272829303132import tensorflow as tfimport numpy as npfrom PIL import Imageimport osMODEL_PATH = os.path.join(os.path.dirname(__file__),"saved_model","Inception_V3_Animals_Classification.h5")model = tf.keras.models.load_model(MODEL_PATH)CLASS_NAMES = ["Cat", "Dog", "Snake"]def preprocess_image(img: Image.Image, target_size=(256, 256):img = img.convert("RGB")img = img.resize(target_size)img = np.array(img).astype("float32") / 255.0img = np.expand_dims(img, axis=0)return imgdef predict(img: Image.Image):input_tensor = preprocess_image(img)preds = model.predict(input_tensor)[0]class_idx = int(np.argmax(preds))confidence = float(np.max(preds))prob_dict = {CLASS_NAMES[i]: float(preds[i]) for i in range(len(CLASS_NAMES))}return CLASS_NAMES[class_idx], confidence, prob_dict
model.py+31-39