|
import gradio as gr |
|
import tensorflow as tf |
|
import tensorflow_hub as hub |
|
from PIL import Image |
|
import numpy as np |
|
from tensorflow.keras.preprocessing.image import img_to_array, load_img |
|
|
|
|
|
def load_model_with_hub(model_path): |
|
|
|
model = tf.keras.models.load_model(model_path, compile=False) |
|
|
|
|
|
keras_layer = hub.KerasLayer("https://tfhub.dev/google/imagenet/resnet_v2_101/feature_vector/5", trainable=False) |
|
|
|
|
|
model.add(keras_layer) |
|
|
|
return model |
|
|
|
|
|
model = load_model_with_hub('model_cat_dog.h5') |
|
|
|
def predict(input_image): |
|
try: |
|
|
|
input_image = img_to_array(input_image) |
|
|
|
input_image = np.resize(input_image, (224, 224, 3)) |
|
input_image = np.array(input_image).astype(np.float32) / 255.0 |
|
input_image = np.expand_dims(input_image, axis=0) |
|
|
|
|
|
|
|
prediction = model.predict(input_image) |
|
|
|
|
|
labels = ['Cat', 'Dog'] |
|
threshold = 0.5 |
|
predicted_class = 'Dog' if prediction[0] > threshold else 'Cat' |
|
prediction_probability = prediction[0] if predicted_class == 'Dog' else 1 - prediction[0] |
|
|
|
cat_emoji = "\U0001F408" |
|
dog_emoji = "\U0001F415" |
|
|
|
selected_emoji = dog_emoji if predicted_class == 'Dog' else cat_emoji |
|
|
|
|
|
output = f"{selected_emoji} {predicted_class}" |
|
|
|
return output |
|
except Exception as e: |
|
return str(e) |
|
|
|
examples = ["dog1.jpeg", |
|
"cat1.jpg"] |
|
|
|
|
|
iface = gr.Interface( |
|
fn=predict, |
|
inputs=gr.inputs.Image(shape=(224, 224)), |
|
outputs="text", |
|
title = 'Image Recognition - Cats vs Dogs', |
|
examples = examples |
|
) |
|
|
|
iface.launch() |