DetectEmotions / app.py
Ahmadkhan12's picture
Update app.py
bb9fde7 verified
raw
history blame
2.19 kB
import streamlit as st
import cv2
import numpy as np
from PIL import Image
from fer import FER
# Set the page config
st.set_page_config(page_title="Emotion Recognition App", layout="centered")
st.title("Emotion Recognition App")
# Upload an image
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
# Load FER emotion detection model
emotion_detector = FER(mtcnn=True) # Use MTCNN for better face detection
# Resize image to reduce memory usage
def resize_image(image, max_size=(800, 800)):
"""
Resizes the image to the specified maximum size while maintaining aspect ratio.
"""
image.thumbnail(max_size, Image.Resampling.LANCZOS)
return image
# Process the uploaded image
if uploaded_file is not None:
# Check file size to prevent loading large images
if uploaded_file.size > 10 * 1024 * 1024: # 10 MB limit
st.error("File too large. Please upload an image smaller than 10 MB.")
else:
# Open and resize the image
image = Image.open(uploaded_file)
image = resize_image(image)
# Convert image to numpy array
image_np = np.array(image)
# Detect emotions
results = emotion_detector.detect_emotions(image_np)
if results:
for face in results:
# Get bounding box and detected emotion
box = face["box"]
emotions = face["emotions"]
dominant_emotion = max(emotions, key=emotions.get)
# Draw a rectangle around the face
x, y, w, h = box
cv2.rectangle(image_np, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display detected emotion
cv2.putText(
image_np,
dominant_emotion,
(x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.9,
(255, 0, 0),
2,
)
# Display the processed image
st.image(image_np, caption="Processed Image", use_column_width=True)
else:
st.warning("No faces detected or unable to determine emotions.")