-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
81 lines (62 loc) · 2.29 KB
/
train.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
import glob
import dlib
import cv2
import cPickle
import random
import face
import numpy as np
def adjust_gamma(input_image, gamma=1.0):
table = np.array([((iteration / 255.0) ** (1.0 / gamma)) * 255
for iteration in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(input_image, table)
def read_image(path, gamma=0.75):
output = cv2.imread(path)
return adjust_gamma(output, gamma=gamma)
def face_vector(input_image):
faces = face.detector(input_image, 1)
if not faces:
return None
f = faces[0]
shape = face.predictor(input_image, f)
face_descriptor = face.face_model.compute_face_descriptor(input_image, shape)
return face_descriptor
max_size = 340
male_label = +1
female_label = -1
print "Retrieving males images ..."
males = glob.glob("./imdb-datasets/images/males/*.jpg")
print "Retrieved {} faces !".format(len(males))
print "Retrieving females images ..."
females = glob.glob("./imdb-datasets/images/females/*.jpg")
print "Retrieved {} faces !".format(len(females))
females = females[:max_size]
males = males[:max_size]
vectors = dlib.vectors()
labels = dlib.array()
print "Reading males images ..."
for i, male in enumerate(males):
print "Reading {} of {}\r".format(i, len(males))
face_vectors = face_vector(read_image(male))
if face_vectors is None:
continue
vectors.append(dlib.vector(face_vectors))
labels.append(male_label)
print "Reading females images ..."
for i, female in enumerate(females):
print "Reading {} of {}\r".format(i, len(females))
face_vectors = face_vector(read_image(female))
if face_vectors is None:
continue
vectors.append(dlib.vector(face_vectors))
labels.append(female_label)
svm = dlib.svm_c_trainer_radial_basis()
svm.set_c(10)
classifier = svm.train(vectors, labels)
print "Prediction for male sample: {}".format(classifier(vectors[random.randrange(0, max_size)]))
print "Prediction for female sample: {}".format(classifier(vectors[max_size + random.randrange(0, max_size)]))
print "Dumping to gender_model.pickle"
with open('./data/gender_model.pickle', 'wb') as handle:
cPickle.dump(classifier, handle)
print "Testing pickle load function from gender_model.pickle"
with open('./data/gender_model.pickle', 'rb') as handle:
classifier = cPickle.load(handle)