import cv2 import numpy as np from keras.models import load_model import gradio as gr # Load pre-trained model model = load_model("emotion_detection_model.h5") # Load OpenCV's pre-trained face detector face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + "haarcascade_frontalface_default.xml" ) # Define emotion labels EMOTIONS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"] # Function to detect and display emotions on faces def detect_emotions(image): frame = image.copy() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for x, y, w, h in faces: face_roi = gray[y : y + h, x : x + w] resized_roi = cv2.resize(face_roi, (48, 48)) normalized_roi = resized_roi / 255.0 reshaped_roi = normalized_roi.reshape(-1, 48, 48, 1) # Predict emotions predictions = model.predict(reshaped_roi) emotion_label = EMOTIONS[np.argmax(predictions)] # Display emotion label on face cv2.putText( frame, emotion_label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2, ) cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) return frame # Define Gradio interface iface = gr.Interface( fn=detect_emotions, inputs="image", outputs="image", title="Emotion Detection", description="Upload an Image to Detect Emotions in Faces", ) # Run Gradio app iface.launch(share=True)