File size: 1,468 Bytes
116211f
1dd90b7
 
 
 
9f42649
116211f
 
9f42649
116211f
 
 
 
 
 
 
 
9f42649
75c3aeb
9f42649
116211f
 
 
 
 
 
 
 
 
 
 
 
9f42649
116211f
 
 
 
 
75c3aeb
116211f
9f42649
116211f
 
9f42649
 
 
116211f
 
 
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
import gradio as gr
import cv2
import numpy as np
from keras.models import load_model

# Load your model
model = load_model('model.keras')

# Load the Haar Cascade for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Emotion labels
labels_dict = {
    0: 'Angry', 1: 'Disgust', 2: 'Fear', 3: 'Happy',
    4: 'Neutral', 5: 'Sad', 6: 'Smirk', 7: 'Surprise'
}

# Define prediction function
def detect_emotion(image):
    frame = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        face = gray[y:y+h, x:x+w]
        resized = cv2.resize(face, (48, 48))
        normalized = resized / 255.0
        reshaped = np.reshape(normalized, (1, 48, 48, 1))
        result = model.predict(reshaped)
        label = np.argmax(result, axis=1)[0]
        emotion = labels_dict[label]

        # Draw on frame
        cv2.rectangle(frame, (x, y), (x + w, y + h), (50, 50, 255), 2)
        cv2.rectangle(frame, (x, y - 40), (x + w, y), (50, 50, 255), -1)
        cv2.putText(frame, emotion, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
                    0.8, (255, 255, 255), 2)

    return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

# Create the Gradio Interface
iface = gr.Interface(
    fn=detect_emotion,
    inputs=gr.Image(source="webcam", type="numpy"),
    outputs="image",
    live=False
)

iface.launch()