-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathface_detector.py
161 lines (115 loc) · 4.96 KB
/
face_detector.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
import numpy as np
import cv2
import dlib
import resources.mtcnn.mtcnn as mtcnn
import tensorflow as tf
## Initializer for face detector classes
class OpenCVHaarFaceDetector():
def __init__(self,
scaleFactor=1.3,
minNeighbors=5,
model_path='models/haarcascade_frontalface_default.xml'):
self.face_cascade = cv2.CascadeClassifier(model_path)
self.scaleFactor = scaleFactor
self.minNeighbors = minNeighbors
def detect_face(self, image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = self.face_cascade.detectMultiScale(gray, self.scaleFactor,
self.minNeighbors)
faces = [[x, y, x + w, y + h] for x, y, w, h in faces]
return np.array(faces)
class DlibHOGFaceDetector():
def __init__(self, nrof_upsample=0, det_threshold=0):
self.hog_detector = dlib.get_frontal_face_detector()
self.nrof_upsample = nrof_upsample
self.det_threshold = det_threshold
def detect_face(self, image):
dets, scores, idx = self.hog_detector.run(image, self.nrof_upsample,
self.det_threshold)
faces = []
for i, d in enumerate(dets):
x1 = int(d.left())
y1 = int(d.top())
x2 = int(d.right())
y2 = int(d.bottom())
faces.append(np.array([x1, y1, x2, y2]))
return np.array(faces)
class DlibCNNFaceDetector():
def __init__(self,
nrof_upsample=0,
model_path='models/mmod_human_face_detector.dat'):
self.cnn_detector = dlib.cnn_face_detection_model_v1(model_path)
self.nrof_upsample = nrof_upsample
def detect_face(self, image):
dets = self.cnn_detector(image, self.nrof_upsample)
faces = []
for i, d in enumerate(dets):
x1 = int(d.rect.left())
y1 = int(d.rect.top())
x2 = int(d.rect.right())
y2 = int(d.rect.bottom())
score = float(d.confidence)
faces.append(np.array([x1, y1, x2, y2]))
return np.array(faces)
class TensorflowMTCNNFaceDetector():
def __init__(self, model_path='models/mtcnn'):
self.minsize = 15
self.threshold = [0.6, 0.7, 0.7] # three steps's threshold
self.factor = 0.709 # scale factor
with tf.Graph().as_default():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf.Session(config=config)
with self.sess.as_default():
self.pnet, self.rnet, self.onet = mtcnn.create_mtcnn(
self.sess, model_path)
def detect_face(self, image):
dets, face_landmarks = mtcnn.detect_face(
image, self.minsize, self.pnet, self.rnet, self.onet,
self.threshold, self.factor)
faces = dets[:, :4].astype('int')
conf_score = dets[:, 4]
return faces
class TensoflowMobilNetSSDFaceDector():
def __init__(self,
det_threshold=0.3,
model_path='models/ssd/frozen_inference_graph_face.pb'):
self.det_threshold = det_threshold
self.detection_graph = tf.Graph()
with self.detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(model_path, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
with self.detection_graph.as_default():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
self.sess = tf.Session(graph=self.detection_graph, config=config)
def detect_face(self, image):
h, w, c = image.shape
image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = self.detection_graph.get_tensor_by_name(
'image_tensor:0')
boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
classes = self.detection_graph.get_tensor_by_name(
'detection_classes:0')
num_detections = self.detection_graph.get_tensor_by_name(
'num_detections:0')
(boxes, scores, classes, num_detections) = self.sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
boxes = np.squeeze(boxes)
scores = np.squeeze(scores)
filtered_score_index = np.argwhere(
scores >= self.det_threshold).flatten()
selected_boxes = boxes[filtered_score_index]
faces = np.array([[
int(x1 * w),
int(y1 * h),
int(x2 * w),
int(y2 * h),
] for y1, x1, y2, x2 in selected_boxes])
return faces