EngrKashifKhan's picture
Create app.py
a2631ed verified
import gradio as gr
import tensorflow as tf
import numpy as np
import pickle
import cv2
# Load model and class names
model = tf.keras.models.load_model("model.h5")
with open("class_names.pkl", "rb") as f:
class_names = pickle.load(f)
# Image preprocessing function
def preprocess_image(img):
img = cv2.resize(img, (224, 224))
img = img / 255.0
return np.expand_dims(img, axis=0)
# Prediction function
def predict(img):
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # Convert PIL image to OpenCV format
processed = preprocess_image(img)
prediction = model.predict(processed)[0]
predicted_label = class_names[np.argmax(prediction)]
confidence = float(np.max(prediction)) * 100
return f"Predicted: {predicted_label} ({confidence:.2f}%)"
# Gradio interface
interface = gr.Interface(
fn=predict,
inputs=gr.Image(type="numpy", label="Upload an Animal Image"),
outputs="text",
title="Animal Classifier with ResNet50",
description="Upload an image of an animal to classify using a pretrained ResNet50 model."
)
interface.launch()