-
Notifications
You must be signed in to change notification settings - Fork 66
/
face_detector.py
65 lines (53 loc) · 2.18 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
import tensorflow as tf
import numpy as np
class FaceDetector:
def __init__(self, model_path, gpu_memory_fraction=0.25, visible_device_list='0'):
"""
Arguments:
model_path: a string, path to a pb file.
gpu_memory_fraction: a float number.
visible_device_list: a string.
"""
with tf.gfile.GFile(model_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
graph = tf.Graph()
with graph.as_default():
tf.import_graph_def(graph_def, name='import')
self.input_image = graph.get_tensor_by_name('import/image_tensor:0')
self.output_ops = [
graph.get_tensor_by_name('import/boxes:0'),
graph.get_tensor_by_name('import/scores:0'),
graph.get_tensor_by_name('import/num_boxes:0'),
]
gpu_options = tf.GPUOptions(
per_process_gpu_memory_fraction=gpu_memory_fraction,
visible_device_list=visible_device_list
)
config_proto = tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)
self.sess = tf.Session(graph=graph, config=config_proto)
def __call__(self, image, score_threshold=0.5):
"""Detect faces.
Arguments:
image: a numpy uint8 array with shape [height, width, 3],
that represents a RGB image.
score_threshold: a float number.
Returns:
boxes: a float numpy array of shape [num_faces, 4].
scores: a float numpy array of shape [num_faces].
Note that box coordinates are in the order: ymin, xmin, ymax, xmax!
"""
h, w, _ = image.shape
image = np.expand_dims(image, 0)
boxes, scores, num_boxes = self.sess.run(
self.output_ops, feed_dict={self.input_image: image}
)
num_boxes = num_boxes[0]
boxes = boxes[0][:num_boxes]
scores = scores[0][:num_boxes]
to_keep = scores > score_threshold
boxes = boxes[to_keep]
scores = scores[to_keep]
scaler = np.array([h, w, h, w], dtype='float32')
boxes = boxes * scaler
return boxes, scores