panik commited on
Commit
3a66e6c
1 Parent(s): 2329d7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -2
app.py CHANGED
@@ -1,9 +1,55 @@
1
  import gradio as gr
2
  import cv2
 
 
 
3
 
4
- def process_image(img):
5
- blur = cv2.blur(img,(5,5))
 
 
 
 
 
 
 
6
  return blur
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  interface = gr.Interface(
9
  fn = process_image,
1
  import gradio as gr
2
  import cv2
3
+ import numpy as np
4
+ from keras.preprocessing.image import img_to_array
5
+ from keras.models import model_from_json
6
 
7
+ # Facial expression recognizer initialization
8
+ face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
9
+ model = model_from_json(open('facial_expression_model_structure.json', 'r').read())
10
+ model.load_weights('facial_expression_model_weights.h5')
11
+
12
+ emotions = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')
13
+
14
+ def blur_image(img):
15
+ blur = cv2.blur(img,(10, 10))
16
  return blur
17
+
18
+ def process_image(img):
19
+ # Resize the frame
20
+ frame = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
21
+
22
+ # Convert to grayscale
23
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
24
+
25
+ # Run the face detector on the grayscale image
26
+ face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)
27
+
28
+ # Draw a rectangle around the face
29
+ for (x,y,w,h) in face_rects:
30
+ #cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3)
31
+ cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) #draw rectangle to main image
32
+
33
+ detected_face = frame[int(y):int(y+h), int(x):int(x+w)] #crop detected face
34
+ detected_face = cv2.cvtColor(detected_face, cv2.COLOR_BGR2GRAY) #transform to gray scale
35
+ detected_face = cv2.resize(detected_face, (48, 48)) #resize to 48x48
36
+
37
+ img_pixels = img_to_array(detected_face)
38
+ img_pixels = np.expand_dims(img_pixels, axis = 0)
39
+
40
+ img_pixels /= 255 #pixels are in scale of [0, 255]. normalize all pixels in scale of [0, 1]
41
+
42
+ predictions = model.predict(img_pixels) #store probabilities of 7 expressions
43
+
44
+ #find max indexed array 0: angry, 1:disgust, 2:fear, 3:happy, 4:sad, 5:surprise, 6:neutral
45
+ max_index = np.argmax(predictions[0])
46
+ emotion = emotions[max_index]
47
+
48
+ #write emotion text above rectangle
49
+ cv2.putText(frame, emotion, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)
50
+
51
+ return frame
52
+
53
 
54
  interface = gr.Interface(
55
  fn = process_image,