CoolFace
Apppublic

DataScience313/Human_Emotion_Detection

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
app.py80 linesDownload Raw Back to root
1import os2os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # Disable GPU3os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'   # Suppress TF logs4 5import streamlit as st6import tensorflow as tf7import numpy as np8import matplotlib.pyplot as plt9import cv210from PIL import Image11 12# Load the model13model = tf.keras.models.load_model('model.h5')14 15# Class labels16class_names = ['angry', 'happy', 'sad']17CONFIDENCE_THRESHOLD = 0.5018 19def is_already_contrast_stretched(img_np):20    return img_np.min() <= 10 and img_np.max() >= 24521 22def contrast_stretch(image):23    b, g, r = cv2.split(image)24    min_intensity, max_intensity = 50, 20025    b = np.uint8(np.clip((b - min_intensity) * 255.0 / (max_intensity - min_intensity), 0, 255))26    g = np.uint8(np.clip((g - min_intensity) * 255.0 / (max_intensity - min_intensity), 0, 255))27    r = np.uint8(np.clip((r - min_intensity) * 255.0 / (max_intensity - min_intensity), 0, 255))28    return cv2.merge([b, g, r])29 30def preprocess_image(uploaded_file):31    img = Image.open(uploaded_file).convert('RGB')32    img_np = np.array(img)33    img_cv = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)34 35    if not is_already_contrast_stretched(img_cv):36        img_cv = contrast_stretch(img_cv)37 38    img_resized = cv2.resize(img_cv, (224, 224))39    img_rgb = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)40    img_array = tf.keras.applications.resnet50.preprocess_input(np.expand_dims(img_rgb, axis=0))41    return img_array42 43def main():44    st.set_page_config(page_title="Emotion Detection", layout="centered")45    st.title('๐Ÿง  Human Emotion Detection')46    st.write("Upload a facial image to classify emotions: Angry, Happy, or Sad.")47 48    uploaded_file = st.file_uploader("๐Ÿ“ค Upload an image", type=["jpg", "jpeg", "png"])49 50    if uploaded_file:51        st.image(Image.open(uploaded_file), caption="๐Ÿ–ผ๏ธ Uploaded Image", use_column_width=True)52 53        try:54            processed_img = preprocess_image(uploaded_file)55            predictions = model.predict(processed_img)[0]56 57            pred_idx = np.argmax(predictions)58            pred_class = class_names[pred_idx]59            confidence = predictions[pred_idx]60 61            if confidence < CONFIDENCE_THRESHOLD:62                st.warning("โš ๏ธ This image doesn't appear valid. Please upload a clear facial image.")63            else:64                st.markdown(f"### ๐Ÿ” Predicted Emotion: **{pred_class.capitalize()}**")65                st.markdown(f"### โœ… Confidence: **{confidence * 100:.2f}%**")66 67                fig, ax = plt.subplots()68                bars = ax.barh(class_names, predictions * 100, color='skyblue')69                bars[pred_idx].set_color('green')70                ax.set_xlim(0, 100)71                ax.set_xlabel("Confidence (%)")72                ax.set_title("Prediction Probabilities")73                st.pyplot(fig)74 75        except Exception as e:76            st.error("โŒ Error processing image. Please upload a valid image.")77 78if __name__ == '__main__':79    main()80