Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

emotion_classifier.py 5.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
  1. import cv2
  2. import glob
  3. import random
  4. import matplotlib.pyplot as plt
  5. import numpy as np
  6. import sys
  7. import pandas as pd
  8. import seaborn as sns
  9. def set_trace():
  10. """A Poor mans break point without this in iPython debugger.
  11. Can generate strange characters.
  12. """
  13. from IPython.core.debugger import Pdb
  14. Pdb().set_trace(sys._getframe().f_back)
  15. # Emotion list
  16. emotions = ["neutral", "anger", "contempt", "disgust",
  17. "fear", "happy", "sadness", "surprise"]
  18. # Initialize fisher face classifier
  19. # fishface = cv2.face.FisherFaceRecognizer_create()
  20. fishface = cv2.face.LBPHFaceRecognizer_create()
  21. # fishface = cv2.face.EigenFaceRecognizer_create()
  22. data = {}
  23. def get_files(emotion):
  24. """Define function to get file list randomly shuffle it and split 80/20."""
  25. files = glob.glob("dataset\\%s\\*" % emotion)
  26. random.shuffle(files)
  27. # get first 80% of file list
  28. training = files[:int(len(files) * 0.8)]
  29. # get last 20% of file list
  30. prediction = files[-int(len(files) * 0.2):]
  31. return training, prediction
  32. def make_sets():
  33. """Allocate sets for training and test."""
  34. training_data = []
  35. training_labels = []
  36. prediction_data = []
  37. prediction_labels = []
  38. for emotion in emotions:
  39. training, prediction = get_files(emotion)
  40. # Append data to training and prediction list, and generate labels 0-7
  41. for item in training:
  42. # open image
  43. image = cv2.imread(item)
  44. # convert to grayscale
  45. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  46. # append image array to training data list
  47. training_data.append(gray)
  48. training_labels.append(emotions.index(emotion))
  49. # repeat above process for prediction set
  50. for item in prediction:
  51. image = cv2.imread(item)
  52. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  53. prediction_data.append(gray)
  54. prediction_labels.append(emotions.index(emotion))
  55. return training_data, training_labels, prediction_data, prediction_labels
  56. def run_recognizer():
  57. """Run recognizer."""
  58. training_data, training_labels, prediction_data, prediction_labels = make_sets()
  59. print "training fisher face classifier"
  60. print "size of training set is:", len(training_labels), "images"
  61. fishface.train(training_data, np.asarray(training_labels))
  62. print "predicting classification set"
  63. cnt = 0
  64. correct = 0
  65. incorrect = 0
  66. for image in prediction_data:
  67. pred, conf = fishface.predict(image)
  68. if pred == prediction_labels[cnt]:
  69. correct += 1
  70. cnt += 1
  71. else:
  72. incorrect += 1
  73. cnt += 1
  74. return ((100 * correct) / (correct + incorrect)), fishface
  75. def map_emotions(df):
  76. """Map emotions to code."""
  77. emotion_map = {0: 'neutral',
  78. 1: 'anger',
  79. 2: 'contempt',
  80. 3: 'disgust',
  81. 4: 'fear',
  82. 5: 'happy',
  83. 6: 'sadness',
  84. 7: 'surprise'}
  85. df['Emotion'] = df['Emotion Code'].map(emotion_map)
  86. return df
  87. def plot_histographic_emotion_analysis(df, group):
  88. """Countplots."""
  89. try:
  90. sns.countplot(x='Emotion', data=df)
  91. except:
  92. set_trace()
  93. # plt.savefig('{}.png'.format(group))
  94. plt.show()
  95. # plt.clf()
  96. def predict_emotions(files, recognizer, group):
  97. """Predict Emotions and analyse distribution."""
  98. pred_list = []
  99. for file in files:
  100. print group, file
  101. image = cv2.imread(file)
  102. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  103. try:
  104. pred, conf = recognizer.predict(gray)
  105. except:
  106. set_trace()
  107. tup = (file[-14:], pred, conf)
  108. pred_list.append(tup)
  109. pred_df = pd.DataFrame(pred_list, columns=['Image',
  110. 'Emotion Code',
  111. 'Confidence'])
  112. pred_df = map_emotions(pred_df)
  113. plot_histographic_emotion_analysis(pred_df, group)
  114. def main():
  115. """Main function."""
  116. metascore = []
  117. for i in range(0, 1):
  118. correct, fishface = run_recognizer()
  119. print "got", correct, "percent correct!"
  120. metascore.append(correct)
  121. accuracy = pd.DataFrame({'Emotion Detector Accuracy': [np.mean(metascore)]})
  122. accuracy.to_csv('C:\Thesis111217\EmotionDetector\Outputs\EmotionDetector_acc.csv')
  123. print "\n\nend score:", np.mean(metascore), "percent correct!"
  124. set_trace()
  125. files = glob.glob("C:\Users\Creative\Documents\FacialExpressions\\Men_non_criminal_108\*")
  126. predict_emotions(files, fishface, 'Outputs\\Men_non_criminal_108')
  127. files = glob.glob("C:\Thesis111217\CriminalClassifier\static\\Women_criminal_108\*")
  128. predict_emotions(files, fishface, 'Outputs\\Women_criminal_108')
  129. if __name__ == '__main__':
  130. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...