forked from bruceyang2012/Face-detection-with-mobilenet-ssd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredictor.py
297 lines (251 loc) · 9.13 KB
/
predictor.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
from __future__ import print_function
import warnings
warnings.filterwarnings("ignore")
from keras.optimizers import Adam, SGD, Nadam
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard, LearningRateScheduler
from keras.callbacks import Callback
from keras import backend as K
from keras.models import load_model
from math import ceil
import numpy as np
from termcolor import colored
#from matplotlib import pyplot as plt
from tqdm import tqdm
#from lg_model_dwc import build_model_300x300
#from lg_model_224x224 import lg_model
from mn_model import mn_model
from face_generator import BatchGenerator
from keras_ssd_loss import SSDLoss
from ssd_box_encode_decode_utils import SSDBoxEncoder, decode_y, decode_y2
# training parameters
from keras import backend as K
import scipy.misc as sm
import json
from keras.preprocessing import image
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
model_path = './models/'
model_name = 'ssd_mobilenet_face_epoch_25_loss0.0916.h5'
test_data = 'wider_val_v1.npy'
OMP_NUM_THREADS=4
import threading
class threadsafe_iter:
def __init__(self, it):
self.it = it
self.lock = threading.Lock()
def __iter__(self):
return self
def next(self):
with self.lock:
return self.it.next()
def threadsafe_generator(f):
def g(*a, **kw):
return threadsafe_iter(f(*a, **kw))
return g
img_height =512
img_width = 512
img_channels = 3
batch_size = 16
n_classes = 2
class_names = ['background', 'face']
scales = [0.07, 0.15, 0.33, 0.51, 0.69, 0.87, 1.05] # anchorboxes for coco dataset
aspect_ratios = [[0.5, 1.0, 2.0],
[1.0/3.0, 0.5, 1.0, 2.0, 3.0],
[1.0/3.0, 0.5, 1.0, 2.0, 3.0],
[1.0/3.0, 0.5, 1.0, 2.0, 3.0],
[0.5, 1.0, 2.0],
[0.5, 1.0, 2.0]] # The anchor box aspect ratios used in the original SSD300
two_boxes_for_ar1 = True
limit_boxes = True # Whether or not you want to limit the anchor boxes to lie entirely within the image boundaries
variances = [0.1, 0.1, 0.2, 0.2] # The variances by which the encoded target coordinates are scaled as in the original implementation
coords = 'centroids' # Whether the box coordinates to be used as targets for the model should be in the 'centroids' or 'minmax' format, see documentation
normalize_coords = True
voc_path = "./"
images_path = "dataset/WIDER_val/images"
def save_bb(path, filename, results, prediction=True):
# print filename
img = image.load_img(filename, target_size=(img_height, img_width))
img = image.img_to_array(img)
filename = filename.split("/")[-1]
if(not prediction):
filename = filename[:-4] + "_gt" + ".jpg"
#fig,currentAxis = plt.subplots(1)
currentAxis = plt.gca()
# Get detections with confidence higher than 0.6.
colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist()
color_code = min(len(results), 16)
# print colored("total number of bbs: %d" % len(results), "yellow")
for result in results:
# Parse the outputs.
if(prediction):
det_label = result[0]
det_conf = result[1]
det_xmin = result[2]
det_xmax = result[3]
det_ymin = result[4]
det_ymax = result[5]
else :
det_label = result[0]
det_xmin = result[1]
det_xmax = result[2]
det_ymin = result[3]
det_ymax = result[4]
xmin = int(det_xmin)
ymin = int(det_ymin)
xmax = int(det_xmax)
ymax = int(det_ymax)
if(prediction):
score = det_conf
plt.imshow(img / 255.)
label = int(int(det_label))
#print label
label_name = class_names[label]
# label_name = class_names[label]
# print label_name
# print label
if(prediction):
display_txt = '{:0.2f}, {}'.format(score, label_name)
else:
display_txt = '{}'.format(label_name)
# print (xmin, ymin, ymin, ymax)
coords = (xmin, ymin), (xmax-xmin), (ymax-ymin)
color_code = color_code-1
color = colors[color_code]
currentAxis.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=2))
# currentAxis.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5})
plt.savefig(path + filename)
# print 'saved' , path + filename
plt.clf()
#
# K.clear_session()
#
# model, model_layer, img_input, predictor_sizes = mn_model(image_size=(img_height, img_width, img_channels),
# n_classes = n_classes,
# min_scale = None,
# max_scale = None,
# scales = scales,
# aspect_ratios_global = None,
# aspect_ratios_per_layer = aspect_ratios,
# two_boxes_for_ar1= two_boxes_for_ar1,
# limit_boxes=limit_boxes,
# variances= variances,
# coords=coords,
# normalize_coords=normalize_coords)
# print model.summary()
#
# print colored("model definition... done.", "green")
#
# print colored("loading detection weights...", "yellow")
#
# model.load_weights(model_path + model_name, by_name= True)
#
# print colored('weights %s loaded' % (model_path + model_name), 'green')
#
#
# print colored("done.", "green")
#
# ssd_box_encoder = SSDBoxEncoder(img_height=img_height,
# img_width=img_width,
# n_classes=n_classes,
# predictor_sizes=predictor_sizes,
# min_scale=None,
# max_scale=None,
# scales=scales,
# aspect_ratios_global=None,
# aspect_ratios_per_layer=aspect_ratios,
# two_boxes_for_ar1=two_boxes_for_ar1,
# limit_boxes=limit_boxes,
# variances=variances,
# pos_iou_threshold=0.5,
# neg_iou_threshold=0.2,
# coords=coords,
# normalize_coords=normalize_coords)
#
#
#
#
#
#
# test_dataset = BatchGenerator(images_path=voc_path + images_path,
# include_classes='all',
# box_output_format = ['class_id', 'xmin', 'xmax', 'ymin', 'ymax'])
#
# print colored("reading evaluation data...", "cyan")
#
# test_dataset.parse_xml(
# annotations_path=test_data,
# image_set_path='None',
# image_set='None',
# classes = class_names,
# exclude_truncated=False,
# exclude_difficult=False,
# ret=False,
# debug = False)
#
# print colored("done.", "green")
#
# print colored("creating batches...", "cyan")
#
# test_generator = test_dataset.generate(
# batch_size=batch_size,
# train=False,
# ssd_box_encoder=ssd_box_encoder,
# equalize=False,
# brightness=False,
# flip=False,
# translate=False,
# scale=False,
# crop=False,
# #random_crop = (img_height,img_width,1,3),
# random_crop=False,
# resize=(img_height, img_width),
# #resize=False,
# gray=False,
# limit_boxes=True,
# include_thresh=0.4,
# diagnostics=False)
#
# print colored("done.", "green")
#
# n_test_samples = test_dataset.get_n_samples()
#
# print ("===>Total number of test samples = {}".format(n_test_samples))
#
#
# print colored("now predicting...", "yellow")
#
#
#
# _CONF = 0.01
# _IOU = 0.15
#
#
# for i in range(n_test_samples/batch_size):
# X, y, filenames = next(test_generator)
#
# y_pred = model.predict(X)
#
#
# y_pred_decoded = decode_y2(y_pred,
# confidence_thresh=_CONF,
# iou_threshold=_IOU,
# top_k='all',
# input_coords=coords,
# normalize_coords=normalize_coords,
# img_height=img_height,
# img_width=img_width)
#
#
# np.set_printoptions(suppress=True)
#
#
# for i in range(batch_size):
# print colored("image %d :" %i, "cyan")
# print colored("predicted", "green")
# print y_pred_decoded[i]
# print colored("ground truth", "red")
# print y[i]
#
# save_bb("./output_test/", filenames[i], y_pred_decoded[i])
# save_bb("./output_test/", filenames[i], y[i], prediction=False)