Upload 6 files
Browse files- EvaluateEmotionDetector.py +52 -0
- TrainEmotionDetector.py +78 -0
- haarcascades/haarcascade_frontalface_default.xml +0 -0
- main.py +73 -0
- model/emotion_model.h5 +3 -0
- model/emotion_model.json +1 -0
EvaluateEmotionDetector.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import numpy as np
|
3 |
+
from keras.models import model_from_json
|
4 |
+
import matplotlib.pyplot as plt
|
5 |
+
from keras.preprocessing.image import ImageDataGenerator
|
6 |
+
from sklearn.metrics import confusion_matrix, classification_report,ConfusionMatrixDisplay
|
7 |
+
|
8 |
+
|
9 |
+
emotion_dict = {0: "Happy", 1: "Neutral", 2: "Sad"}
|
10 |
+
|
11 |
+
# load json and create model
|
12 |
+
json_file = open('model/emotion_model.json', 'r')
|
13 |
+
loaded_model_json = json_file.read()
|
14 |
+
json_file.close()
|
15 |
+
emotion_model = model_from_json(loaded_model_json)
|
16 |
+
|
17 |
+
# load weights into new model
|
18 |
+
emotion_model.load_weights("model/emotion_model.h5")
|
19 |
+
print("Loaded model from disk")
|
20 |
+
|
21 |
+
# Initialize image data generator with rescaling
|
22 |
+
test_data_gen = ImageDataGenerator(rescale=1./255)
|
23 |
+
|
24 |
+
# Preprocess all test images
|
25 |
+
test_generator = test_data_gen.flow_from_directory(
|
26 |
+
'data/test',
|
27 |
+
target_size=(48, 48),
|
28 |
+
batch_size=64,
|
29 |
+
color_mode="grayscale",
|
30 |
+
class_mode='categorical',
|
31 |
+
classes=['Happy', 'Neutral', 'Sad'])
|
32 |
+
|
33 |
+
# do prediction on test data
|
34 |
+
predictions = emotion_model.predict(test_generator)
|
35 |
+
|
36 |
+
# see predictions
|
37 |
+
for result in predictions:
|
38 |
+
max_index = int(np.argmax(result))
|
39 |
+
print(emotion_dict[max_index])
|
40 |
+
|
41 |
+
print("-----------------------------------------------------------------")
|
42 |
+
# confusion matrix
|
43 |
+
c_matrix = confusion_matrix(test_generator.classes, predictions.argmax(axis=1))
|
44 |
+
print(c_matrix)
|
45 |
+
cm_display = ConfusionMatrixDisplay(confusion_matrix=c_matrix, display_labels=list(emotion_dict.values()))
|
46 |
+
cm_display.plot(cmap=plt.cm.Blues)
|
47 |
+
plt.show()
|
48 |
+
|
49 |
+
# Classification report
|
50 |
+
print("-----------------------------------------------------------------")
|
51 |
+
print(classification_report(test_generator.classes, predictions.argmax(axis=1)))
|
52 |
+
|
TrainEmotionDetector.py
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
# import required packages
|
3 |
+
import cv2
|
4 |
+
from keras.models import Sequential
|
5 |
+
from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
|
6 |
+
from keras.optimizers import Adam
|
7 |
+
from keras.preprocessing.image import ImageDataGenerator
|
8 |
+
from sklearn.utils.class_weight import compute_class_weight
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
# Initialize image data generator with rescaling
|
12 |
+
train_data_gen = ImageDataGenerator(rescale=1./255)
|
13 |
+
validation_data_gen = ImageDataGenerator(rescale=1./255)
|
14 |
+
|
15 |
+
# Preprocess all test images
|
16 |
+
train_generator = train_data_gen.flow_from_directory(
|
17 |
+
'data/train',
|
18 |
+
target_size=(48, 48),
|
19 |
+
batch_size=64,
|
20 |
+
color_mode="grayscale",
|
21 |
+
class_mode='categorical')
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
# Calculate class weights
|
26 |
+
class_labels = train_generator.classes
|
27 |
+
class_weights = compute_class_weight(class_weight = "balanced", classes= np.unique(class_labels), y= class_labels)
|
28 |
+
class_weight_dict = dict(enumerate(class_weights))
|
29 |
+
|
30 |
+
|
31 |
+
# Preprocess all train images
|
32 |
+
validation_generator = validation_data_gen.flow_from_directory(
|
33 |
+
'data/test',
|
34 |
+
target_size=(48, 48),
|
35 |
+
batch_size=64,
|
36 |
+
color_mode="grayscale",
|
37 |
+
class_mode='categorical')
|
38 |
+
|
39 |
+
# create model structure
|
40 |
+
emotion_model = Sequential()
|
41 |
+
|
42 |
+
emotion_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48, 48, 1)))
|
43 |
+
emotion_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
|
44 |
+
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
|
45 |
+
emotion_model.add(Dropout(0.25))
|
46 |
+
|
47 |
+
emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
|
48 |
+
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
|
49 |
+
emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
|
50 |
+
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
|
51 |
+
emotion_model.add(Dropout(0.25))
|
52 |
+
|
53 |
+
emotion_model.add(Flatten())
|
54 |
+
emotion_model.add(Dense(1024, activation='relu'))
|
55 |
+
emotion_model.add(Dropout(0.5))
|
56 |
+
emotion_model.add(Dense(3, activation='softmax'))
|
57 |
+
|
58 |
+
cv2.ocl.setUseOpenCL(False)
|
59 |
+
|
60 |
+
emotion_model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.0001), metrics=['accuracy'])
|
61 |
+
|
62 |
+
# Train the neural network/model
|
63 |
+
emotion_model_info = emotion_model.fit_generator(
|
64 |
+
train_generator,
|
65 |
+
steps_per_epoch=len(train_generator) // 64,
|
66 |
+
epochs=100,
|
67 |
+
validation_data=validation_generator,
|
68 |
+
validation_steps=7178 // 64,
|
69 |
+
class_weight=class_weight_dict)
|
70 |
+
|
71 |
+
|
72 |
+
# save model structure in jason file
|
73 |
+
model_json = emotion_model.to_json()
|
74 |
+
with open("model/emotion_model.json", "w") as json_file:
|
75 |
+
json_file.write(model_json)
|
76 |
+
|
77 |
+
# save trained model weight in .h5 file
|
78 |
+
emotion_model.save_weights('model/emotion_model.h5')
|
haarcascades/haarcascade_frontalface_default.xml
ADDED
The diff for this file is too large to render.
See raw diff
|
|
main.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
from keras.models import model_from_json
|
4 |
+
from collections import Counter
|
5 |
+
import time
|
6 |
+
|
7 |
+
emotion_dict = {0: "Happy", 1: "Neutral/Sad", 2: "Sad"}
|
8 |
+
detected_emotions = [] # List to store detected emotions
|
9 |
+
|
10 |
+
# Function to reset the list of detected emotions
|
11 |
+
def reset_detected_emotions():
|
12 |
+
global detected_emotions
|
13 |
+
detected_emotions = []
|
14 |
+
|
15 |
+
# Function to process the frame and update the detected emotions
|
16 |
+
def process_frame(cap2, emotion_model):
|
17 |
+
global detected_emotions
|
18 |
+
ret, frame = cap2.read()
|
19 |
+
frame = cv2.resize(frame, (1280, 720))
|
20 |
+
|
21 |
+
face_detector = cv2.CascadeClassifier('emotion/haarcascades/haarcascade_frontalface_default.xml')
|
22 |
+
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
23 |
+
|
24 |
+
num_faces = face_detector.detectMultiScale(gray_frame, scaleFactor=1.3, minNeighbors=5)
|
25 |
+
|
26 |
+
for (x, y, w, h) in num_faces:
|
27 |
+
roi_gray_frame = gray_frame[y:y + h, x:x + w]
|
28 |
+
cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray_frame, (48, 48)), -1), 0)
|
29 |
+
|
30 |
+
emotion_prediction = emotion_model.predict(cropped_img)
|
31 |
+
maxindex = int(np.argmax(emotion_prediction))
|
32 |
+
detected_emotions.append(emotion_dict[maxindex])
|
33 |
+
|
34 |
+
# Function to get the most common emotion from the list
|
35 |
+
def get_most_common_emotion():
|
36 |
+
global detected_emotions
|
37 |
+
if detected_emotions:
|
38 |
+
counter = Counter(detected_emotions)
|
39 |
+
most_common_emotion = counter.most_common(1)[0][0]
|
40 |
+
return most_common_emotion
|
41 |
+
else:
|
42 |
+
return None
|
43 |
+
|
44 |
+
def call_me():
|
45 |
+
# Load the emotion model
|
46 |
+
json_file = open('emotion/model/emotion_model.json', 'r')
|
47 |
+
loaded_model_json = json_file.read()
|
48 |
+
json_file.close()
|
49 |
+
emotion_model = model_from_json(loaded_model_json)
|
50 |
+
emotion_model.load_weights("emotion/model/emotion_model.h5")
|
51 |
+
print("Loaded model from disk")
|
52 |
+
|
53 |
+
# Start the webcam feed
|
54 |
+
cap2 = cv2.VideoCapture(0)
|
55 |
+
|
56 |
+
duration = 5 # seconds
|
57 |
+
end_time = time.time() + duration
|
58 |
+
|
59 |
+
# Example usage of the functions
|
60 |
+
while time.time() < end_time:
|
61 |
+
process_frame(cap2, emotion_model)
|
62 |
+
|
63 |
+
cap2.release()
|
64 |
+
# print(cap)
|
65 |
+
cv2.destroyAllWindows()
|
66 |
+
|
67 |
+
# Get the most common emotion detected during the session
|
68 |
+
most_common_emotion = get_most_common_emotion()
|
69 |
+
return most_common_emotion
|
70 |
+
# print("Most Common Emotion:", most_common_emotion)
|
71 |
+
# print("User's current Emotion:", most_common_emotion)
|
72 |
+
|
73 |
+
|
model/emotion_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:95033f96d0bbd3f695b4bd4ee95e442d3cd98f80c6bcef745d442238352adec2
|
3 |
+
size 9397216
|
model/emotion_model.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"module": "keras.layers", "class_name": "InputLayer", "config": {"batch_input_shape": [null, 48, 48, 1], "dtype": "float32", "sparse": false, "ragged": false, "name": "conv2d_input"}, "registered_name": null}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d", "trainable": true, "dtype": "float32", "batch_input_shape": [null, 48, 48, 1], "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 48, 48, 1]}}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "dtype": "float32", "filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 46, 46, 32]}}, {"module": "keras.layers", "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d", "trainable": true, "dtype": "float32", "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}, "registered_name": null, "build_config": {"input_shape": [null, 44, 44, 64]}}, {"module": "keras.layers", "class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.25, "noise_shape": null, "seed": null}, "registered_name": null, "build_config": {"input_shape": [null, 22, 22, 64]}}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "dtype": "float32", "filters": 128, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 22, 22, 64]}}, {"module": "keras.layers", "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "dtype": "float32", "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}, "registered_name": null, "build_config": {"input_shape": [null, 20, 20, 128]}}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d_3", "trainable": true, "dtype": "float32", "filters": 128, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 10, 10, 128]}}, {"module": "keras.layers", "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "dtype": "float32", "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}, "registered_name": null, "build_config": {"input_shape": [null, 8, 8, 128]}}, {"module": "keras.layers", "class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "dtype": "float32", "rate": 0.25, "noise_shape": null, "seed": null}, "registered_name": null, "build_config": {"input_shape": [null, 4, 4, 128]}}, {"module": "keras.layers", "class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": "float32", "data_format": "channels_last"}, "registered_name": null, "build_config": {"input_shape": [null, 4, 4, 128]}}, {"module": "keras.layers", "class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 1024, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 2048]}}, {"module": "keras.layers", "class_name": "Dropout", "config": {"name": "dropout_2", "trainable": true, "dtype": "float32", "rate": 0.5, "noise_shape": null, "seed": null}, "registered_name": null, "build_config": {"input_shape": [null, 1024]}}, {"module": "keras.layers", "class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 3, "activation": "softmax", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 1024]}}]}, "keras_version": "2.15.0", "backend": "tensorflow"}
|