CoolFace
Apppublic

Rual113GJ/Cats_and_Dogs_Classification

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py67 linesDownload Raw Back to root
1import gradio as gr2import tensorflow as tf3import tensorflow_hub as hub4from PIL import Image5import numpy as np6from tensorflow.keras.preprocessing.image import img_to_array, load_img7 8# Function to load the model with custom objects9def load_model_with_hub(model_path):10    # Load the model architecture without weights11    model = tf.keras.models.load_model(model_path, compile=False)12 13    # Define the KerasLayer from TensorFlow Hub14    keras_layer = hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_101/feature_vector/5", trainable=False)15 16    # Add the KerasLayer to the model17    model.add(keras_layer)18 19    return model20 21# Loading saved model with custom objects22model = load_model_with_hub('model_cat_dog.h5')23 24def predict(input_image):25    try:26        # Convert PIL Image to Numpy array27        input_image = img_to_array(input_image)28        # Resize the Numpy array29        input_image = np.resize(input_image, (224, 224, 3))30        input_image = np.array(input_image).astype(np.float32) / 255.031        input_image = np.expand_dims(input_image, axis=0) 32 33 34        # Making prediction35        prediction = model.predict(input_image)36 37        # Postprocess prediction38        labels = ['Cat', 'Dog']39        threshold = 0.5  # threshold for classifying as 'Dog'40        predicted_class = 'Dog' if prediction[0] > threshold else 'Cat'41        prediction_probability = prediction[0] if predicted_class == 'Dog' else 1 - prediction[0]42 43        cat_emoji = "\U0001F408"  # Cat emoji44        dog_emoji = "\U0001F415"  # Dog emoji45 46        selected_emoji = dog_emoji if predicted_class == 'Dog' else cat_emoji47 48        # Combine the predicted class and the probability into a single string49        output = f"{selected_emoji} {predicted_class}"50 51        return output52    except Exception as e:53        return str(e)54 55examples = ["dog1.jpeg",56            "cat1.jpg"]57 58# Creating Gradio interface59iface = gr.Interface(60    fn=predict, 61    inputs=gr.inputs.Image(shape=(224, 224)), 62    outputs="text",63    title = 'Image Recognition - Cats vs Dogs',64    examples = examples65)66 67iface.launch()