|
|
|
|
|
|
|
import cv2
|
|
import numpy as np
|
|
import tensorflow as tf
|
|
|
|
|
|
face_detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
|
|
|
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
|
|
emotion_model = tf.keras.models.load_model("model_emotion.h5")
|
|
emotion_model.load_weights("model_weights_new.h5")
|
|
print("Loaded emotion model from disk")
|
|
|
|
|
|
def predict_img(frame):
|
|
|
|
frame = cv2.resize(frame, (1280, 720))
|
|
num_faces = face_detector.detectMultiScale(frame, scaleFactor=1.3, minNeighbors=5)
|
|
|
|
|
|
for (x, y, w, h) in num_faces:
|
|
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (0, 255, 0), 4)
|
|
roi_gray_frame = frame[y:y + h, x:x + w]
|
|
|
|
|
|
resized_img = cv2.resize(roi_gray_frame, (48, 48))
|
|
gray_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)
|
|
input_img = np.expand_dims(gray_img, axis=-1)
|
|
input_img = np.expand_dims(input_img, axis=0)
|
|
|
|
|
|
input_img = input_img / 255.0
|
|
|
|
|
|
emotion_prediction = emotion_model.predict(input_img)
|
|
maxindex = int(np.argmax(emotion_prediction))
|
|
emotion_label = emotion_dict[maxindex]
|
|
|
|
|
|
cv2.putText(frame, emotion_label, (x+5, y-20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)
|
|
|
|
return frame
|
|
|
|
|
|
cap = cv2.VideoCapture(0)
|
|
|
|
while True:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
break
|
|
|
|
annotated_frame = predict_img(frame)
|
|
cv2.imshow('Emotion Detection', annotated_frame)
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord('q'):
|
|
break
|
|
|
|
cap.release()
|
|
cv2.destroyAllWindows()
|
|
|