Skip to content

Instantly share code, notes, and snippets.

@viniciusarruda
Created February 13, 2020 21:08
Show Gist options
  • Save viniciusarruda/e1e3c3bf1096b9f404fa2caac83288d5 to your computer and use it in GitHub Desktop.
Save viniciusarruda/e1e3c3bf1096b9f404fa2caac83288d5 to your computer and use it in GitHub Desktop.
Test NMS for issue
import numpy as np # version 1.16.1 and python 3.6.7
def nms_cpu_kernel(dets, scores, iou_threshold):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
areas = (x2 - x1) * (y2 - y1)
order = scores.argsort()[::-1]
ndets = dets.shape[0]
suppressed = np.zeros(ndets)
keep = []
for i in range(ndets):
i = order[i]
if suppressed[i] == 1:
continue
keep.append(i)
ix1 = x1[i]
iy1 = y1[i]
ix2 = x2[i]
iy2 = y2[i]
iarea = areas[i]
for j in range(i + 1, ndets):
j = order[j]
if suppressed[j] == 1:
continue
xx1 = max(ix1, x1[j])
yy1 = max(iy1, y1[j])
xx2 = min(ix2, x2[j])
yy2 = min(iy2, y2[j])
w = max(0.0, xx2 - xx1)
h = max(0.0, yy2 - yy1)
inter = w * h
ovr = inter / (iarea + areas[j] - inter)
if ovr > iou_threshold:
suppressed[j] = 1
return keep
def nms(dets, thresh):
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
areas = (x2 - x1) * (y2 - y1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(i)
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= thresh)[0]
order = order[inds + 1]
return keep
if __name__ == '__main__':
boxes = [[0.0, 0.0, 1.0, 1.0],
[2.0, 1.0, 1.0, 2.0]]
boxes = np.array(boxes)
scores = np.array([1., 0.5])
keep = nms_cpu_kernel(boxes, scores, 0.7)
print(keep)
print()
# just putting in the function parameter format
boxes = [[0.0, 0.0, 1.0, 1.0, 1.0],
[2.0, 1.0, 1.0, 2.0, 0.5]]
boxes = np.array(boxes)
keep = nms(boxes, 0.7)
print(keep)
# The code above outpus:
# test.py:43: RuntimeWarning: invalid value encountered in double_scalars
# ovr = inter / (iarea + areas[j] - inter)
# [0, 1]
#
# test.py:71: RuntimeWarning: invalid value encountered in true_divide
# ovr = inter / (areas[i] + areas[order[1:]] - inter)
# [0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment