CharimCibersegurata commited on
Commit
47355b0
1 Parent(s): c1e70a5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from keras.preprocessing.image import img_to_array
4
+ import imutils
5
+ import cv2
6
+ from keras.models import load_model
7
+ import numpy as np
8
+
9
+ # parameters for loading data and images
10
+ detection_model_path = 'haarcascade_frontalface_default.xml'
11
+ emotion_model_path = '_mini_XCEPTION.102-0.66.hdf5'
12
+
13
+ # hyper-parameters for bounding boxes shape
14
+ # loading models
15
+ face_detection = cv2.CascadeClassifier(detection_model_path)
16
+ emotion_classifier = load_model(emotion_model_path, compile=False)
17
+ EMOTIONS = ["angry", "disgusted", "scared", "happy", "sad", "surprised",
18
+ "neutral"]
19
+
20
+
21
+ def predict(frame):
22
+
23
+ frame = imutils.resize(frame, width=300)
24
+ gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
25
+ faces = face_detection.detectMultiScale(gray, scaleFactor=1.1,
26
+ minNeighbors=5, minSize=(30, 30),
27
+ flags=cv2.CASCADE_SCALE_IMAGE)
28
+
29
+ frameClone = frame.copy()
30
+ if len(faces) > 0:
31
+ faces = sorted(faces, reverse=True,
32
+ key=lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
33
+ (fX, fY, fW, fH) = faces
34
+ # Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
35
+ # the ROI for classification via the CNN
36
+ roi = gray[fY:fY + fH, fX:fX + fW]
37
+ roi = cv2.resize(roi, (64, 64))
38
+ roi = roi.astype("float") / 255.0
39
+ roi = img_to_array(roi)
40
+ roi = np.expand_dims(roi, axis=0)
41
+
42
+ preds = emotion_classifier.predict(roi)[0]
43
+ label = EMOTIONS[preds.argmax()]
44
+ else:
45
+ return frameClone, "Can't find your face"
46
+
47
+ probs = {}
48
+ cv2.putText(frameClone, label, (fX, fY - 10),
49
+ cv2.FONT_HERSHEY_DUPLEX, 1, (238, 164, 64), 1)
50
+ cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
51
+ (238, 164, 64), 2)
52
+
53
+ for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
54
+ probs[emotion] = float(prob)
55
+
56
+ return frameClone, probs
57
+
58
+
59
+ inp = gr.inputs.Image(source="webcam", label="Your face")
60
+ out = [
61
+ gr.outputs.Image(label="Predicted Emotion"),
62
+ gr.outputs.Label(num_top_classes=3, label="Top 3 Probabilities")
63
+ ]
64
+ title = "Emotion Classification"
65
+ description = "How well can this model predict your emotions? Take a picture with your webcam, and it will guess if" \
66
+ " you are: happy, sad, angry, disgusted, scared, surprised, or neutral."
67
+ thumbnail = "https://raw.githubusercontent.com/gradio-app/hub-emotion-recognition/master/thumbnail.png"
68
+
69
+ gr.Interface(predict, inp, out, capture_session=True, title=title, thumbnail=thumbnail,
70
+ description=description).launch(inbrowser=True)