dilkushsingh's picture
Update app.py
01e06e9 verified
raw
history blame
2.11 kB
import numpy as np
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import gradio as gr
import tensorflow as tf
from PIL import Image
import cv2
from tensorflow.keras.preprocessing import image
# Pipelining the model
from transformers import AutoImageProcessor, AutoModelForImageClassification
processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
model = AutoModelForImageClassification.from_pretrained("microsoft/resnet-50")
# Loading pre-trained model
# model = tf.keras.models.load_model('Final_Resnet50_Best_model.keras')
# Emotion labels dictionary
emotion_labels = {'angry': 0, 'disgust': 1, 'fear': 2, 'happy': 3, 'neutral': 4, 'sad': 5, 'surprise': 6}
index_to_emotion = {v: k for k, v in emotion_labels.items()}
index_to_emotion
def prepare_image(img_pil):
"""Preprocess the PIL image to fit model's input requirements."""
# Convert the PIL image to a numpy array with the target size
img = img_pil.resize((224, 224))
img_array = img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) # Convert single image to a batch.
img_array /= 255.0 # Rescale pixel values to [0,1], as done during training
return img_array
# Define the Gradio interface (assuming you have an index_to_emotion dictionary)
def predict_emotion(image):
"""Predict emotion from an uploaded 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 pimage and see the predicted emotion."
)
# Launch the Gradio interface
interface.launch(share=True)