Khunndev Sisyphus commited on
Commit
4608266
·
1 Parent(s): 13ef64d

Make client NMS and centroid dedup O(n) with a spatial grid for dense bundles.

Browse files

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>

frontend/src/lib/nms.ts CHANGED
@@ -20,25 +20,7 @@ export function nonMaxSuppression(
20
  iouThreshold: number,
21
  maxDet: number,
22
  ): RawDetection[] {
23
- const sorted = [...detections].sort((a, b) => b.confidence - a.confidence)
24
- const kept: RawDetection[] = []
25
-
26
- for (const det of sorted) {
27
- let skip = false
28
- for (const k of kept) {
29
- if (iou(det, k) > iouThreshold) {
30
- skip = true
31
- break
32
- }
33
- }
34
- if (!skip) {
35
- kept.push(det)
36
- }
37
- if (kept.length >= maxDet) {
38
- break
39
- }
40
- }
41
- return kept
42
  }
43
 
44
  /** Intersection-Over-Smaller: metric(a,b) = interArea / min(areaA, areaB). */
@@ -55,33 +37,87 @@ function ios(a: BBox, b: BBox): number {
55
  return inter / smaller
56
  }
57
 
58
- /** Greedy NMS using the intersection-over-smaller metric (good for dedup of nested boxes). */
59
- export function nmsIOS(
 
 
 
 
 
 
 
 
 
 
60
  detections: RawDetection[],
61
- iosThreshold: number,
 
62
  maxDet: number,
63
  ): RawDetection[] {
 
64
  const sorted = [...detections].sort((a, b) => b.confidence - a.confidence)
65
- const kept: RawDetection[] = []
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  for (const det of sorted) {
68
  let skip = false
69
- for (const k of kept) {
70
- if (ios(det, k) > iosThreshold) {
71
- skip = true
72
- break
 
 
 
 
 
 
 
 
73
  }
74
- }
75
  if (!skip) {
76
  kept.push(det)
 
 
 
 
 
 
 
 
77
  }
78
- if (kept.length >= maxDet) {
79
- break
80
- }
81
  }
82
  return kept
83
  }
84
 
 
 
 
 
 
 
 
 
 
85
  export function filterOutliers(
86
  detections: RawDetection[],
87
  lowerMult = 0.25,
 
20
  iouThreshold: number,
21
  maxDet: number,
22
  ): RawDetection[] {
23
+ return nmsGrid(detections, iou, iouThreshold, maxDet)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
  /** Intersection-Over-Smaller: metric(a,b) = interArea / min(areaA, areaB). */
 
37
  return inter / smaller
38
  }
39
 
40
+ type Metric = (a: BBox, b: BBox) => number
41
+
42
+ /**
43
+ * Greedy NMS accelerated by a uniform spatial grid. EXACT — it only skips
44
+ * pairs that cannot share a grid cell, and two boxes can only have IoU/IOS > 0
45
+ * if they geometrically overlap (hence share a cell). Each kept box is inserted
46
+ * into every cell its bbox covers; a candidate checks the buckets overlapping
47
+ * its own bbox. For uniformly sized detections (pipe ends) this is ~O(n)
48
+ * instead of O(n^2) — dense bundles of 2000+ pipes were spending seconds in the
49
+ * brute-force scan on phones.
50
+ */
51
+ function nmsGrid(
52
  detections: RawDetection[],
53
+ metric: Metric,
54
+ threshold: number,
55
  maxDet: number,
56
  ): RawDetection[] {
57
+ if (detections.length === 0) return detections
58
  const sorted = [...detections].sort((a, b) => b.confidence - a.confidence)
 
59
 
60
+ // Cell size from the median box so a typical detection occupies ~1 cell.
61
+ const sizes = sorted
62
+ .map((d) => Math.min(d.xmax - d.xmin, d.ymax - d.ymin))
63
+ .sort((a, b) => a - b)
64
+ const cell = Math.max(1, sizes[Math.floor(sizes.length / 2)])
65
+
66
+ const grid = new Map<number, RawDetection[]>()
67
+ const visitCells = (box: BBox, cb: (key: number) => void) => {
68
+ const x0 = Math.floor(box.xmin / cell)
69
+ const x1 = Math.floor((box.xmax - 1e-6) / cell)
70
+ const y0 = Math.floor(box.ymin / cell)
71
+ const y1 = Math.floor((box.ymax - 1e-6) / cell)
72
+ for (let gx = x0; gx <= x1; gx++) {
73
+ for (let gy = y0; gy <= y1; gy++) {
74
+ cb(gx * 100000 + gy)
75
+ }
76
+ }
77
+ }
78
+
79
+ const kept: RawDetection[] = []
80
  for (const det of sorted) {
81
  let skip = false
82
+ const seen = new Set<RawDetection>()
83
+ visitCells(det, (key) => {
84
+ if (skip) return
85
+ const bucket = grid.get(key)
86
+ if (!bucket) return
87
+ for (const b of bucket) {
88
+ if (seen.has(b)) continue
89
+ seen.add(b)
90
+ if (metric(det, b) > threshold) {
91
+ skip = true
92
+ return
93
+ }
94
  }
95
+ })
96
  if (!skip) {
97
  kept.push(det)
98
+ visitCells(det, (key) => {
99
+ let bucket = grid.get(key)
100
+ if (!bucket) {
101
+ bucket = []
102
+ grid.set(key, bucket)
103
+ }
104
+ bucket.push(det)
105
+ })
106
  }
107
+ if (kept.length >= maxDet) break
 
 
108
  }
109
  return kept
110
  }
111
 
112
+ /** Greedy NMS using the intersection-over-smaller metric (good for dedup of nested boxes). */
113
+ export function nmsIOS(
114
+ detections: RawDetection[],
115
+ iosThreshold: number,
116
+ maxDet: number,
117
+ ): RawDetection[] {
118
+ return nmsGrid(detections, ios, iosThreshold, maxDet)
119
+ }
120
+
121
  export function filterOutliers(
122
  detections: RawDetection[],
123
  lowerMult = 0.25,
frontend/src/lib/postprocess.ts CHANGED
@@ -66,9 +66,17 @@ interface MergeByMedianNnResult {
66
  * Merge duplicate detections using median nearest-neighbour centroid distance.
67
  * Boxes whose centroid is closer than CENTROID_MERGE_NN_FACTOR x median NN
68
  * distance to an already-kept (higher-confidence) box are dropped.
 
 
 
 
 
 
 
69
  */
70
  export function mergeByMedianNn(detections: RawDetection[]): MergeByMedianNnResult {
71
- if (detections.length < 3) {
 
72
  return { detections, merged: 0, medianNn: null }
73
  }
74
 
@@ -77,44 +85,63 @@ export function mergeByMedianNn(detections: RawDetection[]): MergeByMedianNnResu
77
  cy: (d.ymin + d.ymax) / 2,
78
  }))
79
 
80
- // nearest-neighbour distance for each centroid
81
- const nn: number[] = []
82
- for (let i = 0; i < cs.length; i++) {
 
 
 
 
83
  let best = Infinity
84
- for (let j = 0; j < cs.length; j++) {
85
- if (i === j) continue
86
- const dx = cs[i].cx - cs[j].cx
87
- const dy = cs[i].cy - cs[j].cy
88
- const dist = Math.sqrt(dx * dx + dy * dy)
89
- if (dist < best) best = dist
90
  }
91
- nn.push(best)
92
  }
93
-
94
- const sortedNn = [...nn].sort((a, b) => a - b)
95
- const medianNn = sortedNn[Math.floor(sortedNn.length / 2)]
96
  const mergeThreshold = CENTROID_MERGE_NN_FACTOR * medianNn
97
 
98
- // pair each detection with its centroid, then sort by confidence desc
 
 
 
 
99
  const paired = detections
100
  .map((d, i) => ({ d, c: cs[i] }))
101
  .sort((a, b) => b.d.confidence - a.d.confidence)
102
 
103
- const keptCentroids: Array<{ cx: number; cy: number }> = []
104
  const kept: RawDetection[] = []
105
-
106
  for (const { d, c } of paired) {
 
 
107
  let duplicate = false
108
- for (const k of keptCentroids) {
109
- const dx = c.cx - k.cx
110
- const dy = c.cy - k.cy
111
- if (dx * dx + dy * dy < mergeThreshold * mergeThreshold) {
112
- duplicate = true
113
- break
 
 
 
 
 
 
114
  }
115
  }
116
  if (!duplicate) {
117
- keptCentroids.push(c)
 
 
 
 
 
 
118
  kept.push(d)
119
  }
120
  }
 
66
  * Merge duplicate detections using median nearest-neighbour centroid distance.
67
  * Boxes whose centroid is closer than CENTROID_MERGE_NN_FACTOR x median NN
68
  * distance to an already-kept (higher-confidence) box are dropped.
69
+ *
70
+ * Performance: the median NN distance is estimated from an evenly-spaced sample
71
+ * (O(K*n) instead of an all-pairs O(n^2) scan — the median is robust to
72
+ * sampling), and the dedup pass uses a uniform grid (cell = mergeThreshold,
73
+ * 3x3 neighbourhood query) so each centroid only compares against nearby kept
74
+ * centroids. Together this keeps dense bundles (2000+ pipes) from blocking the
75
+ * UI while preserving the same dedup behaviour.
76
  */
77
  export function mergeByMedianNn(detections: RawDetection[]): MergeByMedianNnResult {
78
+ const n = detections.length
79
+ if (n < 3) {
80
  return { detections, merged: 0, medianNn: null }
81
  }
82
 
 
85
  cy: (d.ymin + d.ymax) / 2,
86
  }))
87
 
88
+ // Estimate the median nearest-neighbour distance from an evenly-spaced sample
89
+ // of centroids. For n <= sample size this is the exact all-pairs median.
90
+ const sampleK = Math.min(256, n)
91
+ const sampleNn: number[] = []
92
+ for (let s = 0; s < sampleK; s++) {
93
+ const i = Math.floor((s / sampleK) * n)
94
+ const ci = cs[i]
95
  let best = Infinity
96
+ for (let j = 0; j < n; j++) {
97
+ if (j === i) continue
98
+ const dx = ci.cx - cs[j].cx
99
+ const dy = ci.cy - cs[j].cy
100
+ const dd = dx * dx + dy * dy
101
+ if (dd < best) best = dd
102
  }
103
+ sampleNn.push(Math.sqrt(best))
104
  }
105
+ sampleNn.sort((a, b) => a - b)
106
+ const medianNn = sampleNn[Math.floor(sampleNn.length / 2)]
 
107
  const mergeThreshold = CENTROID_MERGE_NN_FACTOR * medianNn
108
 
109
+ // Dedup via a uniform grid on centroids (cell = mergeThreshold). A kept
110
+ // centroid within mergeThreshold must sit in the candidate's cell or one of
111
+ // its 8 neighbours, so a 3x3 query is complete and exact for this threshold.
112
+ const gcell = Math.max(1, mergeThreshold)
113
+ const grid = new Map<number, Array<{ cx: number; cy: number }>>()
114
  const paired = detections
115
  .map((d, i) => ({ d, c: cs[i] }))
116
  .sort((a, b) => b.d.confidence - a.d.confidence)
117
 
 
118
  const kept: RawDetection[] = []
 
119
  for (const { d, c } of paired) {
120
+ const gx = Math.floor(c.cx / gcell)
121
+ const gy = Math.floor(c.cy / gcell)
122
  let duplicate = false
123
+ for (let dx = -1; dx <= 1 && !duplicate; dx++) {
124
+ for (let dy = -1; dy <= 1 && !duplicate; dy++) {
125
+ const bucket = grid.get((gx + dx) * 100000 + (gy + dy))
126
+ if (!bucket) continue
127
+ for (const k of bucket) {
128
+ const ddx = c.cx - k.cx
129
+ const ddy = c.cy - k.cy
130
+ if (ddx * ddx + ddy * ddy < mergeThreshold * mergeThreshold) {
131
+ duplicate = true
132
+ break
133
+ }
134
+ }
135
  }
136
  }
137
  if (!duplicate) {
138
+ const key = gx * 100000 + gy
139
+ let bucket = grid.get(key)
140
+ if (!bucket) {
141
+ bucket = []
142
+ grid.set(key, bucket)
143
+ }
144
+ bucket.push(c)
145
  kept.push(d)
146
  }
147
  }