├── README.md └── emotion dectection.py /README.md: -------------------------------------------------------------------------------- 1 | # emotion-detection -------------------------------------------------------------------------------- /emotion dectection.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import argparse 4 | import matplotlib.pyplot as plt 5 | import cv2 6 | from tensorflow.keras.models import Sequential 7 | from tensorflow.keras.layers import Dense, Dropout, Flatten 8 | from tensorflow.keras.layers import Conv2D 9 | from tensorflow.keras.optimizers import Adam 10 | from tensorflow.keras.layers import MaxPooling2D 11 | from tensorflow.keras.preprocessing.image import ImageDataGenerator 12 | import os 13 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 14 | 15 | mode = "display" 16 | 17 | # Create the model 18 | model = Sequential() 19 | 20 | model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1))) 21 | model.add(Conv2D(64, kernel_size=(3, 3), activation='relu')) 22 | model.add(MaxPooling2D(pool_size=(2, 2))) 23 | model.add(Dropout(0.25)) 24 | 25 | model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) 26 | model.add(MaxPooling2D(pool_size=(2, 2))) 27 | model.add(Conv2D(128, kernel_size=(3, 3), activation='relu')) 28 | model.add(MaxPooling2D(pool_size=(2, 2))) 29 | model.add(Dropout(0.25)) 30 | 31 | model.add(Flatten()) 32 | model.add(Dense(1024, activation='relu')) 33 | model.add(Dropout(0.5)) 34 | model.add(Dense(7, activation='softmax')) 35 | 36 | 37 | def emotion_recog(frame): 38 | model.load_weights('model.h5') 39 | 40 | # prevents openCL usage and unnecessary logging messages 41 | cv2.ocl.setUseOpenCL(False) 42 | 43 | # dictionary which assigns each label an emotion (alphabetical order) 44 | emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"} 45 | 46 | # frame = cv2.imread("image1.jpg") 47 | facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 48 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 49 | faces = facecasc.detectMultiScale(gray,scaleFactor=1.3, minNeighbors=5) 50 | 51 | for (x, y, w, h) in faces: 52 | cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 255), 3) 53 | roi_gray = gray[y:y + h, x:x + w] 54 | cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0) 55 | prediction = model.predict(cropped_img) 56 | maxindex = int(np.argmax(prediction)) 57 | cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA) 58 | 59 | # cv2_imshow(frame) 60 | return frame 61 | input = cv2.imread("E:\elon musk.jpg") 62 | output = emotion_recog(input) 63 | cv2_imshow(output) --------------------------------------------------------------------------------