| 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' |
|
|
| |
| 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() |
|
|
| |
| unique_breeds = np.unique(labels) |
| IMG_SIZE = 150 |
|
|
| |
| def get_pred_label(prediction_probabilities): |
| ''' |
| Turn an array of prediction probabilities into a label. |
| ''' |
| return unique_breeds[np.argmax(prediction_probabilities)] |
|
|
|
|
| |
| |
| def identificationPipeline(img_path): |
| ''' |
| Takes an image path, preprocesses it, and returns the predicted breed. |
| ''' |
| print(f"Received img_path: {img_path}") |
|
|
| |
| if not os.path.exists(img_path): |
| raise FileNotFoundError(f"Image not found at: {img_path}") |
|
|
| |
| 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)) |
|
|
| |
| 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)}" |
|
|
|
|
|
|
|
|