-
Notifications
You must be signed in to change notification settings - Fork 0
/
emotions.py
381 lines (293 loc) · 9.63 KB
/
emotions.py
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
import random
import pickle
# Load the Drive helper and mount
from google.colab import drive
drive.mount('/content/drive')
#Load haar cascade xml
face_cascade = cv2.CascadeClassifier('/content/drive/My Drive/Emotions/haarcascade_frontalface_default.xml')
#Get directory strings
DATADIR = "/content/drive/My Drive/Emotions/TrainingData"
DATADIRHAAR = "/content/drive/My Drive/Emotions/Cascaded"
DATADIRRAW = "/content/drive/My Drive/Emotions/TrainingDataRaw"
#Category of emotions
CATEGORIES = ["anger","disgust","fear","joy","sadness", "surprise"]
#Show first image in training set
for category in CATEGORIES:
path = os.path.join(DATADIR, category)
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
plt.imshow(img_array, cmap="gray")
plt.show()
break
break
#Use haar cascade to detect face in image
faces = face_cascade.detectMultiScale(img_array)
#Extract face from image
for (x,y,w,h) in faces:
img_array = img_array[y:y+h, x:x+w]
#Display Face
plt.imshow(img_array, cmap="gray")
plt.show()
#Define normalisation sise
IMGSIZE = 120
#Resize image to 120 x 120
resized_array = cv2.resize(img_array, (IMGSIZE, IMGSIZE))
#Display Resized Image
plt.imshow(resized_array, cmap="gray")
plt.show()
#Mirror Function
def mirror(img):
mirrored_img = np.fliplr(img)
return mirrored_img
#Mirror image
mirrored_img = mirror(resized_array)
#Display mirrored image
plt.imshow(mirrored_img, cmap="gray")
plt.show()
#Flip Function
def flip(img):
flipped_img = np.flipud(img)
return flipped_img
#Flipped image
flipped_img = flip(resized_array)
#Display flipped image
plt.imshow(flipped_img, cmap="gray")
plt.show()
#Rotate Left function
def rotate_left(img):
#Find centre
image_center = tuple(np.array(img.shape[1::-1]) / 2)
#Get rotation martix
rot_mat_left = cv2.getRotationMatrix2D(image_center, 90, 1.0)
#Manipulate image
rotate_left = cv2.warpAffine(img, rot_mat_left, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotate_left
#Rotate image
rotated_img = rotate_left(resized_array)
#Display image
plt.imshow(rotated_img, cmap="gray")
plt.show()
#Rotate Right function
def rotate_right(img):
#Find centre
image_center = tuple(np.array(img.shape[1::-1]) / 2)
#Get rotation martix
rot_mat_right = cv2.getRotationMatrix2D(image_center, -90, 1.0)
#Manipulate image
rotate_right = cv2.warpAffine(img, rot_mat_right, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotate_right
#Rotate image
rotated_img = rotate_right(resized_array)
#Display image
plt.imshow(rotated_img, cmap="gray")
plt.show()
#Rotate 180 function
def rotated(img):
#Find centre
image_center = tuple(np.array(img.shape[1::-1]) / 2)
#Get rotation martix
rot_mat = cv2.getRotationMatrix2D(image_center, 180, 1.0)
#Manipulate image
rotated = cv2.warpAffine(img, rot_mat, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotated
#Rotate image
rotated_img = rotated(resized_array)
#Display image
plt.imshow(rotated_img, cmap="gray")
plt.show()
def gauss_noise(image):
row,col = image.shape
s_vs_p = 0.5
amount = 0.1
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
#Add noise
noise_img = gauss_noise(resized_array)
#Display image
plt.imshow(resized_array, cmap="gray")
plt.show()
#Display image
plt.imshow(noise_img, cmap="gray")
plt.show()
#Cascade training set
def haar_cascade():
#For number of emotion categories
for category in CATEGORIES:
#Get file path to read data
path = os.path.join(DATADIRRAW, category)
#Get file path to read data
pathwrite = os.path.join(DATADIRHAAR, category)
#Get value of category array index
class_num = CATEGORIES.index(category)
#For number of images in category
for img in os.listdir(path):
try:
#Get image from folder
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
#Detect face in image
faces = face_cascade.detectMultiScale(img_array)
#Extract face from image
for (x,y,w,h) in faces:
img_array = img_array[y:y+h, x:x+w]
#Write extracted face to folder
cv2.imwrite(os.path.join(pathwrite,img),img_array)
#pass image if invalid
except Exception as e:
pass
#Call function
#haar_cascade()
#Training data vector
training_data = []
#Rotate Left function
def rotate_left(img):
image_center = tuple(np.array(img.shape[1::-1]) / 2)
rot_mat_left = cv2.getRotationMatrix2D(image_center, 90, 1.0)
rotate_left = cv2.warpAffine(img, rot_mat_left, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotate_left
#Rotate Right function
def rotate_right(img):
image_center = tuple(np.array(img.shape[1::-1]) / 2)
rot_mat_right = cv2.getRotationMatrix2D(image_center, -90, 1.0)
rotate_right = cv2.warpAffine(img, rot_mat_right, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotate_right
#Rotate 180 function
def rotated(img):
image_center = tuple(np.array(img.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, 180, 1.0)
rotated = cv2.warpAffine(img, rot_mat, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotated
#Mirror Function
def mirror(img):
mirrored_img = np.fliplr(img)
return mirrored_img
#Flip Function
def flip(img):
flipped_img = np.flipud(img)
return flipped_img
#Add noise
def noise(image):
row,col = image.shape
s_vs_p = 0.5
amount = 0.1
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
#Create training data function
def create_training_data():
#For number of emotion categories
for category in CATEGORIES:
#Get file path to read data
path = os.path.join(DATADIR, category)
#Get value of category array index
class_num = CATEGORIES.index(category)
#For number of images in category
for img in os.listdir(path):
try:
#Get image from folder
img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
#Augment image
resized_img = cv2.resize(img_array, (IMGSIZE, IMGSIZE))
#rotate_left_img = rotate_left(resized_img)
#rotate_right_img = rotate_right(resized_img)
#rotated_img = rotated(resized_img)
#mirrored_img = mirror(resized_img)
#flipped_img = flip(resized_array)
#noisey_img = noise(resized_array)
#Append to training vector
training_data.append([resized_img, class_num])
#training_data.append([rotate_left_img, class_num])
#training_data.append([rotate_right_img, class_num])
#training_data.append([rotated_img, class_num])
#training_data.append([mirrored_img, class_num])
#training_data.append([flipped_img, class_num])
#training_data.append([noisey_img, class_num])
#pass image if invalid
except Exception as e:
pass
#Call function
#create_training_data()
#Shuffle data
random.shuffle(training_data)
#Print length of training data
print(len(training_data))
#print first tren labels
for sample in training_data[:10]:
print(sample[1])
#Create features and label vectors
X = []
y = []
#Append data to vectors
for features, label in training_data:
X.append(features)
y.append(label)
#Reshape features
X = np.array(X).reshape(-1, IMGSIZE, IMGSIZE, 1)
#Write features
pickle_out = open("/content/drive/My Drive/Emotions/X.pickle","wb")
pickle.dump(X, pickle_out)
pickle_out.close()
#Write labels
pickle_out = open("/content/drive/My Drive/Emotions/y.pickle","wb")
pickle.dump(y, pickle_out)
pickle_out.close()
#Read features
pickle_in = open("/content/drive/My Drive/Emotions/X.pickle", "rb")
X = pickle.load(pickle_in)
#Read labels
pickle_in = open("/content/drive/My Drive/Emotions/y.pickle","rb")
y = pickle.load(pickle_in)
#First label
y[0]
#Display first feature array
X[0]
#Display size of each category
print(len(training_data))
anger_counter = 0
disgust_counter = 0
fear_counter = 0
joy_counter = 0
sadness_counter = 0
surprise_counter = 0
for x in range(len(training_data)):
if y[x] == 0:
anger_counter += 1
if y[x] == 1:
disgust_counter += 1
if y[x] == 2:
fear_counter += 1
if y[x] == 3:
joy_counter += 1
if y[x] == 4:
sadness_counter += 1
if y[x] == 5:
surprise_counter += 1
print(anger_counter)
print(disgust_counter)
print(fear_counter)
print(joy_counter)
print(sadness_counter)
print(surprise_counter)