This repository has been archived by the owner on Nov 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
extraction_model.py
341 lines (273 loc) · 13 KB
/
extraction_model.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
#!/usr/bin/env python3
"""Extraction of features, vectors, and faces, are held in the helper model."""
# Import packages.
import numpy as np
import cv2
import dlib
import math
import random
import glob
import time
from PIL import Image
from sklearn.decomposition import PCA
# My imports.
from sort_database.utils import *
# Set Face Detectors.
faceDet = cv2.CascadeClassifier("sort_database//" + HAAR)
faceDet2 = cv2.CascadeClassifier("sort_database//" + HAAR2)
faceDet3 = cv2.CascadeClassifier("sort_database//" + HAAR3)
faceDet4 = cv2.CascadeClassifier("sort_database//" + HAAR4)
faceDet5 = dlib.get_frontal_face_detector() # dlib's face detector
# Build the required objects.
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
predictor = dlib.shape_predictor("sort_database//" + PRED)
# Default sizes of training and testing sets (as ratios of the dataset)
training_set_size = 0.8
testing_set_size = 0.2
def convert_numpy(data):
"""Convert given data into numpy array."""
return np.array(data)
def get_images(emotion):
"""Split dataset into 80 percent training set and 20 percent prediction."""
files = glob.glob("sort_database//database//{}//*".format(emotion))
random.shuffle(files)
# training = files[:int(len(files) * training_set_size)]
# prediction = files[-int(len(files) * testing_set_size):]
# for testing
training = files[:5]
prediction = files[-5:]
return training, prediction
def get_images2(emotion):
"""Split dataset into 80 percent training set and 20 percent prediction."""
files = glob.glob("sort_database//database2//{}//*".format(emotion))
random.shuffle(files)
training = files[:int(len(files) * training_set_size)]
prediction = files[-int(len(files) * testing_set_size):]
# for testing
# training = files[:5]
# prediction = files[-5:]
return training, prediction
def get_face_opencv_vectors(img):
"""Get all the faces as OpenCV vectors."""
haar_detections = []
facefeatures = []
# Use dlib to detect faces in the frame.
detections = faceDet5(img, 1)
if len(detections) > 0: # dlib found faces
for face in detections:
x = face.left()
y = face.top()
w = face.right() - face.left()
h = face.bottom() - face.top()
facefeatures.append([x, y, w, h])
else:
haar_detections = faceDet.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections) > 0: # HAAR Cascade found faces
facefeatures = haar_detections
if len(facefeatures) == 0:
haar_detections2 = faceDet2.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections2) > 0: # HAAR Cascade 2 found faces
facefeatures = haar_detections2
if len(facefeatures) == 0:
haar_detections3 = faceDet3.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections3) > 0: # HAAR Cascade 3 found faces
facefeatures = haar_detections3
if len(facefeatures) == 0:
haar_detections4 = faceDet4.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections4) > 0: # HAAR Cascade 4 found faces
facefeatures = haar_detections4
# else:
# print("No face found")
return facefeatures
def get_face_dlib_rects(img):
"""Get all the faces as dlib Rectangles."""
haar_detections = []
# Use dlib to detect faces in the frame.
detections = faceDet5(img, 1)
if len(detections) > 0:
return detections
else:
haar_detections = faceDet.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections) > 0: # HAAR Cascade found faces
for (x, y, w, h) in haar_detections:
dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))
detections.append(dlib_rect)
break
if len(detections) == 0:
haar_detections2 = faceDet2.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections2) > 0: # HAAR Cascade 2 found faces
for (x, y, w, h) in haar_detections2:
dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))
detections.append(dlib_rect)
break
if len(detections) == 0:
haar_detections3 = faceDet3.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections3) > 0: # HAAR Cascade 3 found faces
for (x, y, w, h) in haar_detections3:
dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))
detections.append(dlib_rect)
break
if len(detections) == 0:
haar_detections4 = faceDet4.detectMultiScale(img, scaleFactor=1.1,
minNeighbors=10,
minSize=(5, 5),
flags=cv2.CASCADE_SCALE_IMAGE)
if len(haar_detections4) > 0: # HAAR Cascade 4 found faces
for (x, y, w, h) in haar_detections4:
dlib_rect = dlib.rectangle(int(x), int(y), int(x + w), int(y + h))
detections.append(dlib_rect)
break
# else:
# print("No face found")
return detections
def get_face_landmarks(img):
"""Get all the faces as flat landmark vectors."""
detections = get_face_dlib_rects(img)
# We may detect 0, 1 or many faces. Loop through each face detected.
for i, j in enumerate(detections):
# Draw facial landmarks with the predictor class.
shape = predictor(img, j)
xlist = []
ylist = []
# Store X and Y coordinates in separate lists.
for i in range(1, 68): # 68 because we're looking for 68 landmarks
xlist.append(float(shape.part(i).x))
ylist.append(float(shape.part(i).y))
# Find both coordinates for the centre of gravity (middle point).
xmean = np.mean(xlist)
ymean = np.mean(ylist)
# Calculate the distance from centre to other points in both axes.
xcentral = [(x-xmean) for x in xlist]
ycentral = [(y-ymean) for y in ylist]
# Condition the vectors.
landmarks_vectorised = []
for x, y, w, z in zip(xcentral, ycentral, xlist, ylist):
landmarks_vectorised.append(w)
landmarks_vectorised.append(z)
meannp = np.asarray((ymean, xmean))
coornp = np.asarray((z, w))
dist = np.linalg.norm(coornp-meannp)
landmarks_vectorised.append(dist)
landmarks_vectorised.append((math.atan2(y, x)*360)/(math.pi*2))
if len(detections) == 0:
return "error"
return landmarks_vectorised
def get_sets_as_images(emotions):
"""Make the sets to test on."""
training_data = []
training_labels = []
prediction_data = []
prediction_labels = []
for emotion in emotions:
print("Obtaining images that represent ``{}''.".format(emotion))
training, prediction = get_images2(emotion)
print("Allocating {}. This directory contains {} images."
.format(emotion, len(training)+len(prediction)))
# Append data to training and prediction lists and label 0 to num.
for item in training:
image = cv2.imread(item) # Open image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
clahe_image = clahe.apply(gray)
# clahe_image = cv2.equalizeHist(gray)
# cv2.imwrite('clahe.png', clahe_image)
check = get_face_dlib_rects(clahe_image)
if len(check) > 0:
training_data.append(clahe_image)
training_labels.append(emotions.index(emotion))
for item in prediction:
image = cv2.imread(item) # Open image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
clahe_image = clahe.apply(gray)
# clahe_image = cv2.equalizeHist(gray)
# cv2.imwrite('clahe.png', clahe_image)
check = get_face_dlib_rects(clahe_image)
if len(check) > 0:
prediction_data.append(clahe_image)
prediction_labels.append(emotions.index(emotion))
return training_data, training_labels, prediction_data, prediction_labels
def get_sets(emotions):
"""Make the feature vector sets to test on."""
training_data = []
training_labels = []
prediction_data = []
prediction_labels = []
for emotion in emotions:
print("Obtaining images that represent ``{}''.".format(emotion))
training, prediction = get_images(emotion)
print("***> Allocating {}. This directory contains {} images."
.format(emotion, len(training)+len(prediction)))
# Append data to training and prediction lists and label 0 to num.
for item in training:
image = cv2.imread(item) # Open image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
clahe_image = clahe.apply(gray)
# clahe_image = cv2.equalizeHist(gray)
# cv2.imwrite('clahe.png', clahe_image)
facefeatures = get_face_landmarks(clahe_image)
if (facefeatures != "error"):
training_data.append(facefeatures)
training_labels.append(emotions.index(emotion))
for item in prediction:
image = cv2.imread(item) # Open image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
clahe_image = clahe.apply(gray)
# clahe_image = cv2.equalizeHist(gray)
# cv2.imwrite('clahe.png', clahe_image)
facefeatures = get_face_landmarks(clahe_image)
if (facefeatures != "error"):
prediction_data.append(facefeatures)
prediction_labels.append(emotions.index(emotion))
return training_data, training_labels, prediction_data, prediction_labels
def get_sets_pca(emotions):
"""Make the feature vector sets to test on."""
X_train = X_test = y_train = y_test = []
n_components = len(emotions)
h = w = 380
for emotion in emotions:
print("Obtaining images that represent ``{}''.".format(emotion))
training, prediction = get_images(emotion)
for data in training:
print(Image.open(data).shape)
X_train.append(flatten_image(matrix_image(data)))
y_train.append(emotions.index(emotion))
for data in prediction:
X_test.append(flatten_image(matrix_image(data)))
y_test.append(emotions.index(emotion))
X_train = convert_numpy(X_train)
X_test = convert_numpy(X_test)
print(X_train.shape, X_train.dtype)
print("***> Allocating {}. This directory contains {} images."
.format(emotion, len(training)+len(prediction)))
print("Extracting the top {} eigenfaces from {} faces."
.format(n_components, X_train.shape[0]))
c0 = time.clock()
pca = PCA(svd_solver='randomized', n_components=n_components).fit(X_train)
print("Done in %0.3fs" % (time.clock() - c0))
eigenfaces = pca.components_.reshape((n_components, h, w))
print("Projecting the input data on the eigenfaces orthonormal basis.")
t0 = time.clock()
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("done in %0.3fs" % (time.clock() - t0))
return X_train_pca, X_test_pca, y_train, y_test