from deepface.basemodels import VGGFace
from deepface.detectors import FaceDetector
from deepface.commons import functions
tf_version = int(tf.__version__.split(".")[0])
from keras.models import Model, Sequential
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Flatten, Dense, Dropout
from tensorflow import keras
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Flatten, Dense, Dropout
def loadModel(weights='./weights/facial_expression_model_weights.h5'):
model.add(Conv2D(64, (5, 5), activation='relu', input_shape=(48, 48, 1)))
model.add(MaxPooling2D(pool_size=(5, 5), strides=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(AveragePooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(AveragePooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(Dense(1024, activation='relu'))
model.add(Dense(1024, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
home = functions.get_deepface_home()
model.load_weights(weights)
detector_backend = 'opencv'
face_detector = FaceDetector.build_model(detector_backend)
emotion_model = loadModel()
emotion_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
cap = cv2.VideoCapture(0)
faces = FaceDetector.detect_faces(face_detector, detector_backend, img, align=False)
for face, (x, y, w, h) in faces:
roi_img = img[y:y + h, x:x + w]
gray_img = functions.preprocess_face(img=roi_img, target_size=(48, 48), grayscale=True,
enforce_detection=False, detector_backend='opencv')
emotion_predictions = emotion_model.predict(gray_img)[0, :]
print(emotion_predictions)
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 3)
cv2.putText(img, 'emotion={}'.format(emotion_labels[np.argmax(emotion_predictions)]), (x - 10, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255)
cv2.imshow('result', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
