File size: 1,578 Bytes
38c84fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)