23A475R commited on
Commit
cdadc4f
1 Parent(s): 2b8f874

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -18
app.py CHANGED
@@ -17,32 +17,41 @@ EMOTIONS = ['neutral', 'happiness', 'surprise', 'sadness', 'anger', 'disgust', '
17
  # face_detector_mtcnn = MTCNN()
18
  classifier = load_model(emotion_model_path)
19
 
20
- def predict_emotion(image):
21
- # Convert the image to grayscale
22
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
23
-
24
- # Detect faces in the grayscale image
25
  faces = face_detection.detectMultiScale(gray, scaleFactor=1.1,
26
  minNeighbors=5, minSize=(30, 30),
27
  flags=cv2.CASCADE_SCALE_IMAGE)
28
 
29
- confidences = {}
30
- for (x, y, w, h) in faces:
31
- # Extract the region of interest (ROI)
32
- roi_gray = gray[y:y+h, x:x+w]
33
- roi_gray = cv2.resize(roi_gray, (48, 48), interpolation=cv2.INTER_AREA)
 
 
 
 
 
 
 
 
34
 
35
- # Preprocess the ROI for prediction
36
- img = roi_gray.astype('float') / 255.0
37
- img = img_to_array(img)
38
- img = np.expand_dims(img, axis=0)
39
 
40
- # Make a prediction for the emotion
41
- prediction = emotion_classifier.predict(img)[0]
42
- confidences = {EMOTIONS[i]: float(prediction[i]) for i in range(len(EMOTIONS))}
 
 
43
 
44
- return confidences
 
45
 
 
 
46
 
47
 
48
 
 
17
  # face_detector_mtcnn = MTCNN()
18
  classifier = load_model(emotion_model_path)
19
 
20
+ def predict_emotion(frame):
21
+ frame = imutils.resize(frame, width=300)
22
+ gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
 
 
23
  faces = face_detection.detectMultiScale(gray, scaleFactor=1.1,
24
  minNeighbors=5, minSize=(30, 30),
25
  flags=cv2.CASCADE_SCALE_IMAGE)
26
 
27
+ frame_clone = frame.copy()
28
+ if len(faces) > 0:
29
+ faces = sorted(faces, reverse=True,
30
+ key=lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
31
+ (fX, fY, fW, fH) = faces
32
+
33
+ # Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
34
+ # the ROI for classification via the CNN
35
+ roi = gray[fY:fY + fH, fX:fX + fW]
36
+ roi = cv2.resize(roi, (48, 48))
37
+ roi = roi.astype("float") / 255.0
38
+ roi = img_to_array(roi)
39
+ roi = np.expand_dims(roi, axis=0)
40
 
41
+ preds = emotion_classifier.predict(roi)[0]
42
+ label = EMOTIONS[preds.argmax()]
 
 
43
 
44
+ # Overlay a box over the detected face
45
+ cv2.putText(frame_clone, label, (fX, fY - 10),
46
+ cv2.FONT_HERSHEY_DUPLEX, 1, (238, 164, 64), 1)
47
+ cv2.rectangle(frame_clone, (fX, fY), (fX + fW, fY + fH),
48
+ (238, 164, 64), 2)
49
 
50
+ else:
51
+ label = "Can't find your face"
52
 
53
+ probs = {emotion: float(prob) for emotion, prob in zip(EMOTIONS, preds)}
54
+ return frame_clone, probs
55
 
56
 
57