Naveen82's picture
Upload 3 files
58b1024 verified
import cv2
import numpy as np
import tensorflow as tf
import gradio as gr
# Load trained model
model = tf.keras.models.load_model('emotion_detection_model.h5')
# Load Haar Cascade
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Emotion labels
class_names = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
# Function to detect emotion
def detect_emotion_frame(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=5, minSize=(60, 60)
)
for (x, y, w, h) in faces:
roi_gray = gray[y:y + h, x:x + w]
resized = cv2.resize(roi_gray, (48, 48))
normalized = resized / 255.0
reshaped = np.reshape(normalized, (1, 48, 48, 1))
prediction = model.predict(reshaped)
max_index = int(np.argmax(prediction))
emotion = class_names[max_index]
# Draw box and emotion
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(
frame, emotion, (x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2
)
return frame
# Gradio interface
demo = gr.Interface(
fn=detect_emotion_frame,
inputs=gr.Image(source="webcam", streaming=True),
outputs=gr.Image(),
live=True,
title="Live Emotion Detection",
description="Real-time face emotion detection using deep learning."
)
if __name__ == "__main__":
demo.launch()