Keras
Dog-Breed-Identification / App /dog_vision.py
Piyush242003's picture
Upload 69 files
b9f3d6d verified
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
import os
import pandas as pd
import cv2
import keras
from matplotlib.pyplot import imread
from flask import jsonify
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Create a function to load a trained model
def load_model(model_path):
'''
Loads a saved model from a specified path.
'''
print(f'Loading saved model from: {model_path}')
model = tf.keras.models.load_model(model_path,
custom_objects={'KerasLayer': hub.KerasLayer})
return model
loaded_full_model = load_model(r'C:\Users\piyus\OneDrive\Desktop\FlaskApp\Model\final-keras-model-xception.keras')
labels_csv = pd.read_csv(r'C:\Users\piyus\OneDrive\Desktop\FlaskApp\Model\labels.csv')
labels = labels_csv['breed'].to_numpy()
# Find the unique label values
unique_breeds = np.unique(labels)
IMG_SIZE = 150
# Turn probabilities into their respective label (easier to understand)
def get_pred_label(prediction_probabilities):
'''
Turn an array of prediction probabilities into a label.
'''
return unique_breeds[np.argmax(prediction_probabilities)]
# Identification Pipeline
# Identification Pipeline
def identificationPipeline(img_path):
'''
Takes an image path, preprocesses it, and returns the predicted breed.
'''
print(f"Received img_path: {img_path}")
# Validate Image Path
if not os.path.exists(img_path):
raise FileNotFoundError(f"Image not found at: {img_path}")
# Read & Preprocess Image
try:
image = tf.io.read_file(img_path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, size=[IMG_SIZE, IMG_SIZE])
image_reshaped = tf.reshape(image, (1, IMG_SIZE, IMG_SIZE, 3)) # Add batch dimension
# Predict
results = loaded_full_model.predict(image_reshaped)
confidence = np.max(results)
pred_label = get_pred_label(results)
if confidence < 0.1:
return "Unknown Object (Not a Dog)"
print(f"Predicted Label: {pred_label}")
return pred_label
except Exception as e:
return f"Error: {str(e)}"