Tanish22b0978's picture
Create app.py
90bcfa6 verified
import numpy as np
from PIL import Image
import gradio as gr
from keras.preprocessing.image import img_to_array
# Assume model and index_to_emotion are predefined
# model = ...
# index_to_emotion = ...
def prepare_image(img_pil):
"""Preprocess the PIL image to fit your model's input requirements."""
# Convert the image to grayscale
img = img_pil.convert('L')
# Resize the image to the target size
img = img.resize((224, 224))
# Convert the PIL image to a numpy array
img_array = img_to_array(img)
# Expand dimensions to match model's input shape (batch size, height, width, channels)
img_array = np.expand_dims(img_array, axis=0)
# Normalize pixel values to [0, 1]
img_array /= 255.0
return img_array
# Define the Gradio interface
def predict_emotion(image):
# Preprocess the image
processed_image = prepare_image(image)
# Make prediction using the model
prediction = model.predict(processed_image)
# Get the emotion label with the highest probability
predicted_class = np.argmax(prediction, axis=1)
predicted_emotion = index_to_emotion.get(predicted_class[0], "Unknown Emotion")
return predicted_emotion
interface = gr.Interface(
fn=predict_emotion, # Your prediction function
inputs=gr.Image(type="pil"), # Input for uploading an image, directly compatible with PIL images
outputs="text", # Output as text displaying the predicted emotion
title="Emotion Detection",
description="Upload an image and see the predicted emotion."
)
# Launch the Gradio interface
interface.launch()