-
Notifications
You must be signed in to change notification settings - Fork 214
/
nms.py
384 lines (265 loc) · 12.3 KB
/
nms.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
from time import time
from .utils import _normalize_grid
def _ind_prob_thresh(prob, prob_thresh, b=2):
if b is not None and np.isscalar(b):
b = ((b,b),)*prob.ndim
ind_thresh = prob > prob_thresh
if b is not None:
_ind_thresh = np.zeros_like(ind_thresh)
ss = tuple(slice(_bs[0] if _bs[0]>0 else None,
-_bs[1] if _bs[1]>0 else None) for _bs in b)
_ind_thresh[ss] = True
ind_thresh &= _ind_thresh
return ind_thresh
def _non_maximum_suppression_old(coord, prob, grid=(1,1), b=2, nms_thresh=0.5, prob_thresh=0.5, verbose=False, max_bbox_search=True):
"""2D coordinates of the polys that survive from a given prediction (prob, coord)
prob.shape = (Ny,Nx)
coord.shape = (Ny,Nx,2,n_rays)
b: don't use pixel closer than b pixels to the image boundary
returns retained points
"""
from .lib.stardist2d import c_non_max_suppression_inds_old
# TODO: using b>0 with grid>1 can suppress small/cropped objects at the image boundary
assert prob.ndim == 2
assert coord.ndim == 4
grid = _normalize_grid(grid,2)
# mask = prob > prob_thresh
# if b is not None and b > 0:
# _mask = np.zeros_like(mask)
# _mask[b:-b,b:-b] = True
# mask &= _mask
mask = _ind_prob_thresh(prob, prob_thresh, b)
polygons = coord[mask]
scores = prob[mask]
# sort scores descendingly
ind = np.argsort(scores)[::-1]
survivors = np.zeros(len(ind), bool)
polygons = polygons[ind]
scores = scores[ind]
if max_bbox_search:
# map pixel indices to ids of sorted polygons (-1 => polygon at that pixel not a candidate)
mapping = -np.ones(mask.shape,np.int32)
mapping.flat[ np.flatnonzero(mask)[ind] ] = range(len(ind))
else:
mapping = np.empty((0,0),np.int32)
if verbose:
t = time()
survivors[ind] = c_non_max_suppression_inds_old(np.ascontiguousarray(polygons.astype(np.int32)),
mapping, np.float32(nms_thresh), np.int32(max_bbox_search),
np.int32(grid[0]), np.int32(grid[1]),np.int32(verbose))
if verbose:
print("keeping %s/%s polygons" % (np.count_nonzero(survivors), len(polygons)))
print("NMS took %.4f s" % (time() - t))
points = np.stack([ii[survivors] for ii in np.nonzero(mask)],axis=-1)
return points
def non_maximum_suppression(dist, prob, grid=(1,1), b=2, nms_thresh=0.5, prob_thresh=0.5,
use_bbox=True, use_kdtree=True, verbose=False):
"""Non-Maximum-Supression of 2D polygons
Retains only polygons whose overlap is smaller than nms_thresh
dist.shape = (Ny,Nx, n_rays)
prob.shape = (Ny,Nx)
returns the retained points, probabilities, and distances:
points, prob, dist = non_maximum_suppression(dist, prob, ....
"""
# TODO: using b>0 with grid>1 can suppress small/cropped objects at the image boundary
assert prob.ndim == 2 and dist.ndim == 3 and prob.shape == dist.shape[:2]
dist = np.asarray(dist)
prob = np.asarray(prob)
n_rays = dist.shape[-1]
grid = _normalize_grid(grid,2)
# mask = prob > prob_thresh
# if b is not None and b > 0:
# _mask = np.zeros_like(mask)
# _mask[b:-b,b:-b] = True
# mask &= _mask
mask = _ind_prob_thresh(prob, prob_thresh, b)
points = np.stack(np.where(mask), axis=1)
dist = dist[mask]
scores = prob[mask]
# sort scores descendingly
ind = np.argsort(scores)[::-1]
dist = dist[ind]
scores = scores[ind]
points = points[ind]
points = (points * np.array(grid).reshape((1,2)))
if verbose:
t = time()
inds = non_maximum_suppression_inds(dist, points.astype(np.int32, copy=False), scores=scores,
use_bbox=use_bbox, use_kdtree=use_kdtree,
thresh=nms_thresh, verbose=verbose)
if verbose:
print("keeping %s/%s polygons" % (np.count_nonzero(inds), len(inds)))
print("NMS took %.4f s" % (time() - t))
return points[inds], scores[inds], dist[inds]
def non_maximum_suppression_sparse(dist, prob, points, b=2, nms_thresh=0.5,
use_bbox=True, use_kdtree = True, verbose=False):
"""Non-Maximum-Supression of 2D polygons from a list of dists, probs (scores), and points
Retains only polyhedra whose overlap is smaller than nms_thresh
dist.shape = (n_polys, n_rays)
prob.shape = (n_polys,)
points.shape = (n_polys,2)
returns the retained instances
(pointsi, probi, disti, indsi)
with
pointsi = points[indsi] ...
"""
# TODO: using b>0 with grid>1 can suppress small/cropped objects at the image boundary
dist = np.asarray(dist)
prob = np.asarray(prob)
points = np.asarray(points)
n_rays = dist.shape[-1]
assert dist.ndim == 2 and prob.ndim == 1 and points.ndim == 2 and \
points.shape[-1]==2 and len(prob) == len(dist) == len(points)
verbose and print("predicting instances with nms_thresh = {nms_thresh}".format(nms_thresh=nms_thresh), flush=True)
inds_original = np.arange(len(prob))
_sorted = np.argsort(prob)[::-1]
probi = prob[_sorted]
disti = dist[_sorted]
pointsi = points[_sorted]
inds_original = inds_original[_sorted]
if verbose:
print("non-maximum suppression...")
t = time()
inds = non_maximum_suppression_inds(disti, pointsi, scores=probi, thresh=nms_thresh, use_kdtree = use_kdtree, verbose=verbose)
if verbose:
print("keeping %s/%s polyhedra" % (np.count_nonzero(inds), len(inds)))
print("NMS took %.4f s" % (time() - t))
return pointsi[inds], probi[inds], disti[inds], inds_original[inds]
def non_maximum_suppression_inds(dist, points, scores, thresh=0.5, use_bbox=True, use_kdtree = True, verbose=1):
"""
Applies non maximum supression to ray-convex polygons given by dists and points
sorted by scores and IoU threshold
P1 will suppress P2, if IoU(P1,P2) > thresh
with IoU(P1,P2) = Ainter(P1,P2) / min(A(P1),A(P2))
i.e. the smaller thresh, the more polygons will be supressed
dist.shape = (n_poly, n_rays)
point.shape = (n_poly, 2)
score.shape = (n_poly,)
returns indices of selected polygons
"""
from .lib.stardist2d import c_non_max_suppression_inds
assert dist.ndim == 2
assert points.ndim == 2
n_poly = dist.shape[0]
if scores is None:
scores = np.ones(n_poly)
assert len(scores) == n_poly
assert points.shape[0] == n_poly
def _prep(x, dtype):
return np.ascontiguousarray(x.astype(dtype, copy=False))
inds = c_non_max_suppression_inds(_prep(dist, np.float32),
_prep(points, np.float32),
int(use_kdtree),
int(use_bbox),
int(verbose),
np.float32(thresh))
return inds
#########
def non_maximum_suppression_3d(dist, prob, rays, grid=(1,1,1), b=2, nms_thresh=0.5, prob_thresh=0.5, use_bbox=True, use_kdtree=True, verbose=False):
"""Non-Maximum-Supression of 3D polyhedra
Retains only polyhedra whose overlap is smaller than nms_thresh
dist.shape = (Nz,Ny,Nx, n_rays)
prob.shape = (Nz,Ny,Nx)
returns the retained points, probabilities, and distances:
points, prob, dist = non_maximum_suppression_3d(dist, prob, ....
"""
# TODO: using b>0 with grid>1 can suppress small/cropped objects at the image boundary
dist = np.asarray(dist)
prob = np.asarray(prob)
assert prob.ndim == 3 and dist.ndim == 4 and dist.shape[-1] == len(rays) and prob.shape == dist.shape[:3]
grid = _normalize_grid(grid,3)
verbose and print("predicting instances with prob_thresh = {prob_thresh} and nms_thresh = {nms_thresh}".format(prob_thresh=prob_thresh, nms_thresh=nms_thresh), flush=True)
# ind_thresh = prob > prob_thresh
# if b is not None and b > 0:
# _ind_thresh = np.zeros_like(ind_thresh)
# _ind_thresh[b:-b,b:-b,b:-b] = True
# ind_thresh &= _ind_thresh
ind_thresh = _ind_prob_thresh(prob, prob_thresh, b)
points = np.stack(np.where(ind_thresh), axis=1)
verbose and print("found %s candidates"%len(points))
probi = prob[ind_thresh]
disti = dist[ind_thresh]
_sorted = np.argsort(probi)[::-1]
probi = probi[_sorted]
disti = disti[_sorted]
points = points[_sorted]
verbose and print("non-maximum suppression...")
points = (points * np.array(grid).reshape((1,3)))
inds = non_maximum_suppression_3d_inds(disti, points, rays=rays, scores=probi, thresh=nms_thresh,
use_bbox=use_bbox, use_kdtree = use_kdtree,
verbose=verbose)
verbose and print("keeping %s/%s polyhedra" % (np.count_nonzero(inds), len(inds)))
return points[inds], probi[inds], disti[inds]
def non_maximum_suppression_3d_sparse(dist, prob, points, rays, b=2, nms_thresh=0.5, use_kdtree = True, verbose=False):
"""Non-Maximum-Supression of 3D polyhedra from a list of dists, probs and points
Retains only polyhedra whose overlap is smaller than nms_thresh
dist.shape = (n_polys, n_rays)
prob.shape = (n_polys,)
points.shape = (n_polys,3)
returns the retained instances
(pointsi, probi, disti, indsi)
with
pointsi = points[indsi] ...
"""
# TODO: using b>0 with grid>1 can suppress small/cropped objects at the image boundary
dist = np.asarray(dist)
prob = np.asarray(prob)
points = np.asarray(points)
assert dist.ndim == 2 and prob.ndim == 1 and points.ndim == 2 and \
dist.shape[-1] == len(rays) and points.shape[-1]==3 and len(prob) == len(dist) == len(points)
verbose and print("predicting instances with nms_thresh = {nms_thresh}".format(nms_thresh=nms_thresh), flush=True)
inds_original = np.arange(len(prob))
_sorted = np.argsort(prob)[::-1]
probi = prob[_sorted]
disti = dist[_sorted]
pointsi = points[_sorted]
inds_original = inds_original[_sorted]
verbose and print("non-maximum suppression...")
inds = non_maximum_suppression_3d_inds(disti, pointsi, rays=rays, scores=probi, thresh=nms_thresh, use_kdtree = use_kdtree, verbose=verbose)
verbose and print("keeping %s/%s polyhedra" % (np.count_nonzero(inds), len(inds)))
return pointsi[inds], probi[inds], disti[inds], inds_original[inds]
def non_maximum_suppression_3d_inds(dist, points, rays, scores, thresh=0.5, use_bbox=True, use_kdtree = True, verbose=1):
"""
Applies non maximum supression to ray-convex polyhedra given by dists and rays
sorted by scores and IoU threshold
P1 will suppress P2, if IoU(P1,P2) > thresh
with IoU(P1,P2) = Ainter(P1,P2) / min(A(P1),A(P2))
i.e. the smaller thresh, the more polygons will be supressed
dist.shape = (n_poly, n_rays)
point.shape = (n_poly, 3)
score.shape = (n_poly,)
returns indices of selected polygons
"""
from .lib.stardist3d import c_non_max_suppression_inds
assert dist.ndim == 2
assert points.ndim == 2
assert dist.shape[1] == len(rays)
n_poly = dist.shape[0]
if scores is None:
scores = np.ones(n_poly)
assert len(scores) == n_poly
assert points.shape[0] == n_poly
# sort scores descendingly
ind = np.argsort(scores)[::-1]
survivors = np.ones(n_poly, bool)
dist = dist[ind]
points = points[ind]
scores = scores[ind]
def _prep(x, dtype):
return np.ascontiguousarray(x.astype(dtype, copy=False))
if verbose:
t = time()
survivors[ind] = c_non_max_suppression_inds(_prep(dist, np.float32),
_prep(points, np.float32),
_prep(rays.vertices, np.float32),
_prep(rays.faces, np.int32),
_prep(scores, np.float32),
int(use_bbox),
int(use_kdtree),
int(verbose),
np.float32(thresh))
if verbose:
print("NMS took %.4f s" % (time() - t))
return survivors