Spaces:
Sleeping
Sleeping
import streamlit as st | |
import onnxruntime as ort | |
import cv2 | |
import numpy as np | |
from PIL import Image | |
# Set page configuration | |
st.set_page_config(page_title="Emotion Recognition App", layout="centered") | |
st.title("Emotion Recognition App") | |
# Load the ONNX model using onnxruntime | |
def load_model(): | |
model_path = "onnx_model.onnx" # Ensure this is the correct path to your uploaded ONNX model | |
return ort.InferenceSession(model_path) | |
# Load the emotion detection model | |
emotion_model = load_model() | |
# Process the uploaded image | |
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"]) | |
def preprocess_image(image): | |
"""Preprocess image to match model input requirements""" | |
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY) # Convert image to grayscale | |
image_resized = cv2.resize(image, (48, 48)) # Resize image to 48x48 | |
image_input = np.expand_dims(image_resized, axis=0) # Add batch dimension | |
image_input = np.expand_dims(image_input, axis=0) # Add channel dimension (for grayscale) | |
image_input = image_input.astype(np.float32) / 255.0 # Normalize the image | |
return image_input | |
def predict_emotion(image_input): | |
"""Run inference and predict the emotion""" | |
input_name = emotion_model.get_inputs()[0].name | |
output_name = emotion_model.get_outputs()[0].name | |
prediction = emotion_model.run([output_name], {input_name: image_input}) | |
emotion = np.argmax(prediction[0]) # Get the class with the highest probability | |
return emotion | |
# Define a function to display emotion text | |
def display_emotion(emotion): | |
"""Map emotion index to a human-readable emotion""" | |
emotion_map = { | |
0: "Anger", | |
1: "Disgust", | |
2: "Fear", | |
3: "Happiness", | |
4: "Sadness", | |
5: "Surprise", | |
6: "Neutral" | |
} | |
return emotion_map.get(emotion, "Unknown") | |
# If an image is uploaded | |
if uploaded_file is not None: | |
# Open and display the uploaded image | |
image = Image.open(uploaded_file) | |
st.image(image, caption="Uploaded Image", use_column_width=True) | |
# Preprocess the image | |
image_input = preprocess_image(image) | |
# Predict the emotion | |
emotion = predict_emotion(image_input) | |
emotion_label = display_emotion(emotion) | |
# Display the predicted emotion | |
st.write(f"Detected Emotion: {emotion_label}") | |