Spaces:
Sleeping
Sleeping
File size: 2,350 Bytes
46274ff 36dac79 7ffdd20 46274ff 7ffdd20 c096457 36dac79 21ef691 7ffdd20 36dac79 7ffdd20 36dac79 7ffdd20 36dac79 7ffdd20 1effd41 7ffdd20 c096457 7ffdd20 36dac79 7ffdd20 36dac79 7ffdd20 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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
@st.cache_resource
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_RGB2BGR)
image_resized = cv2.resize(image, (224, 224)) # Resize image to model input size
image_input = np.transpose(image_resized, (2, 0, 1)) # Change data format for the model
image_input = image_input.astype(np.float32) / 255.0 # Normalize the image
image_input = np.expand_dims(image_input, axis=0) # Add batch dimension
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}")
|