Khunndev commited on
Commit
b505c60
·
1 Parent(s): e3b60de

Reduce over-count with median-NN dedup, IOS NMS, shape filter, and per-step report.

Browse files
.gitignore CHANGED
@@ -14,3 +14,4 @@ frontend/public/images/touch/*.png
14
  frontend/public/images/touch/*.ico
15
  node_modules/
16
  dist/
 
 
14
  frontend/public/images/touch/*.ico
15
  node_modules/
16
  dist/
17
+ training/
detect.py CHANGED
@@ -227,16 +227,22 @@ def detect_bytes(
227
  boxes, scores = _decode(out, meta, w, h)
228
  mode = "single frame"
229
 
230
- if boxes:
231
- keep = _nms(boxes, scores, iou_thres=select_nms_iou(len(boxes)))
232
- boxes = [boxes[i] for i in keep]
233
- scores = [scores[i] for i in keep]
234
- boxes, scores = apply_detection_postprocess(
235
- boxes,
236
- scores,
237
- extra_outlier_filter=filter_outliers_flag,
238
- filter_outliers_fn=_filter_outliers,
239
- )
 
 
 
 
 
 
240
 
241
  ms = (time.perf_counter() - t0) * 1000
242
  detections = [
@@ -258,4 +264,5 @@ def detect_bytes(
258
  "model": model_path.name,
259
  "mode": mode,
260
  "backend": f"server-{get_active_backend()}",
 
261
  }
 
227
  boxes, scores = _decode(out, meta, w, h)
228
  mode = "single frame"
229
 
230
+ raw_count = len(boxes)
231
+ keep = _nms(boxes, scores, iou_thres=select_nms_iou(len(boxes)))
232
+ boxes = [boxes[i] for i in keep]
233
+ scores = [scores[i] for i in keep]
234
+ post_nms_count = len(boxes)
235
+ boxes, scores, report = apply_detection_postprocess(
236
+ boxes,
237
+ scores,
238
+ extra_outlier_filter=filter_outliers_flag,
239
+ filter_outliers_fn=_filter_outliers,
240
+ was_tiled=tile,
241
+ )
242
+ report["raw"] = raw_count
243
+ report["after_nms"] = post_nms_count
244
+ report["removed_by_nms"] = raw_count - post_nms_count
245
+ report["tiling_used"] = bool(tile)
246
 
247
  ms = (time.perf_counter() - t0) * 1000
248
  detections = [
 
264
  "model": model_path.name,
265
  "mode": mode,
266
  "backend": f"server-{get_active_backend()}",
267
+ "postprocess": report,
268
  }
frontend/src/App.tsx CHANGED
@@ -206,6 +206,7 @@ export default function App() {
206
  filterOutliers,
207
  autoTile: !useTiling,
208
  onProgress: setStatus,
 
209
  })
210
 
211
  const detectServer = (file: File) =>
 
206
  filterOutliers,
207
  autoTile: !useTiling,
208
  onProgress: setStatus,
209
+ onReport: (r) => console.info('[pipe-postprocess]', r),
210
  })
211
 
212
  const detectServer = (file: File) =>
frontend/src/lib/constants.ts CHANGED
@@ -12,10 +12,10 @@ export const IOU_RECALL_RAW_COUNT = 1500
12
  export const TILE_OVERLAP = 0.28
13
  export const MAX_DETECTIONS = 6000
14
  /** Median-area multipliers for uniform bundles only. */
15
- export const BOX_SIZE_LOWER_MULT = 0.35
16
  export const BOX_SIZE_UPPER_MULT = 2.8
17
  /** Loose area bounds for dense / mixed-size bundles. */
18
- export const BOX_SIZE_LOOSE_LOWER = 0.1
19
  export const BOX_SIZE_LOOSE_UPPER = 12
20
  /** Skip strict size filter when p90/p10 area ratio exceeds this. */
21
  export const MIXED_SIZE_RATIO = 3
@@ -23,6 +23,12 @@ export const MIXED_SIZE_RATIO = 3
23
  export const DENSE_DETECTION_COUNT = 500
24
  /** Merge tile duplicates only — fraction of smaller box min side. */
25
  export const CENTER_MERGE_SIZE_RATIO = 0.28
 
 
 
 
 
 
26
 
27
  export const GROUP_COLORS = [
28
  '#ef4444',
 
12
  export const TILE_OVERLAP = 0.28
13
  export const MAX_DETECTIONS = 6000
14
  /** Median-area multipliers for uniform bundles only. */
15
+ export const BOX_SIZE_LOWER_MULT = 0.43
16
  export const BOX_SIZE_UPPER_MULT = 2.8
17
  /** Loose area bounds for dense / mixed-size bundles. */
18
+ export const BOX_SIZE_LOOSE_LOWER = 0.45
19
  export const BOX_SIZE_LOOSE_UPPER = 12
20
  /** Skip strict size filter when p90/p10 area ratio exceeds this. */
21
  export const MIXED_SIZE_RATIO = 3
 
23
  export const DENSE_DETECTION_COUNT = 500
24
  /** Merge tile duplicates only — fraction of smaller box min side. */
25
  export const CENTER_MERGE_SIZE_RATIO = 0.28
26
+ /** Merge boxes whose centroid distance < this x median nearest-neighbor distance. */
27
+ export const CENTROID_MERGE_NN_FACTOR = 0.5
28
+ /** IOS (intersection-over-smaller) match-metric threshold for tiling dedup. */
29
+ export const IOS_NMS_THRESHOLD = 0.5
30
+ /** Drop box if max(w,h)/min(w,h) > this (end-on pipe ends are ~square). */
31
+ export const END_ASPECT_RATIO_MAX = 2.5
32
 
33
  export const GROUP_COLORS = [
34
  '#ef4444',
frontend/src/lib/inference.ts CHANGED
@@ -9,7 +9,7 @@ import {
9
  import { selectModelForImage } from './modelSelect'
10
  import { nonMaxSuppression, postProcessPipeline, reassignDetectionIds } from './postprocess'
11
  import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess'
12
- import type { Detection, LetterboxMeta } from './types'
13
 
14
  ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/'
15
 
@@ -231,6 +231,7 @@ export async function runDetection(
231
  enhanceOptions?: EnhanceOptions
232
  filterOutliers?: boolean
233
  onProgress?: (msg: string) => void
 
234
  },
235
  ): Promise<Detection[]> {
236
  await loadModel(options?.onProgress)
@@ -254,12 +255,13 @@ export async function runDetection(
254
  enhanceImage: enhance,
255
  })
256
  }
257
-
258
  options?.onProgress?.(enhance ? 'Enhancing image...' : 'Preparing image...')
259
  const source = prepareSource(image, enhance, options?.enhanceOptions)
260
  const dets = await inferCanvas(source, session, inferenceSize, 0, 0, w, h)
261
  const processed = postProcessPipeline(dets, {
262
  extraOutlierFilter: options?.filterOutliers ?? false,
 
 
263
  })
264
  options?.onProgress?.(`Detected ${processed.length} pipes in ${Math.round(performance.now() - start)}ms`)
265
  return reassignDetectionIds(processed, 'det').map((d) => ({
@@ -278,6 +280,7 @@ async function runTiledDetection(
278
  enhanceOptions?: EnhanceOptions
279
  filterOutliers?: boolean
280
  onProgress?: (msg: string) => void
 
281
  },
282
  ): Promise<Detection[]> {
283
  const onProgress = options?.onProgress
@@ -329,6 +332,8 @@ async function runTiledDetection(
329
  const merged = reassignDetectionIds(
330
  postProcessPipeline(all, {
331
  extraOutlierFilter: options?.filterOutliers ?? false,
 
 
332
  }),
333
  'pipe',
334
  ).map((d) => ({ ...d, groupId: 0 }))
 
9
  import { selectModelForImage } from './modelSelect'
10
  import { nonMaxSuppression, postProcessPipeline, reassignDetectionIds } from './postprocess'
11
  import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess'
12
+ import type { Detection, LetterboxMeta, PostProcessReport } from './types'
13
 
14
  ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/'
15
 
 
231
  enhanceOptions?: EnhanceOptions
232
  filterOutliers?: boolean
233
  onProgress?: (msg: string) => void
234
+ onReport?: (r: PostProcessReport) => void
235
  },
236
  ): Promise<Detection[]> {
237
  await loadModel(options?.onProgress)
 
255
  enhanceImage: enhance,
256
  })
257
  }
 
258
  options?.onProgress?.(enhance ? 'Enhancing image...' : 'Preparing image...')
259
  const source = prepareSource(image, enhance, options?.enhanceOptions)
260
  const dets = await inferCanvas(source, session, inferenceSize, 0, 0, w, h)
261
  const processed = postProcessPipeline(dets, {
262
  extraOutlierFilter: options?.filterOutliers ?? false,
263
+ wasTiled: false,
264
+ onReport: options?.onReport,
265
  })
266
  options?.onProgress?.(`Detected ${processed.length} pipes in ${Math.round(performance.now() - start)}ms`)
267
  return reassignDetectionIds(processed, 'det').map((d) => ({
 
280
  enhanceOptions?: EnhanceOptions
281
  filterOutliers?: boolean
282
  onProgress?: (msg: string) => void
283
+ onReport?: (r: PostProcessReport) => void
284
  },
285
  ): Promise<Detection[]> {
286
  const onProgress = options?.onProgress
 
332
  const merged = reassignDetectionIds(
333
  postProcessPipeline(all, {
334
  extraOutlierFilter: options?.filterOutliers ?? false,
335
+ wasTiled: true,
336
+ onReport: options?.onReport,
337
  }),
338
  'pipe',
339
  ).map((d) => ({ ...d, groupId: 0 }))
frontend/src/lib/nms.ts CHANGED
@@ -41,6 +41,47 @@ export function nonMaxSuppression(
41
  return kept
42
  }
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  export function filterOutliers(
45
  detections: RawDetection[],
46
  lowerMult = 0.25,
 
41
  return kept
42
  }
43
 
44
+ /** Intersection-Over-Smaller: metric(a,b) = interArea / min(areaA, areaB). */
45
+ function ios(a: BBox, b: BBox): number {
46
+ const x1 = Math.max(a.xmin, b.xmin)
47
+ const y1 = Math.max(a.ymin, b.ymin)
48
+ const x2 = Math.min(a.xmax, b.xmax)
49
+ const y2 = Math.min(a.ymax, b.ymax)
50
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1)
51
+ const areaA = (a.xmax - a.xmin) * (a.ymax - a.ymin)
52
+ const areaB = (b.xmax - b.xmin) * (b.ymax - b.ymin)
53
+ const smaller = Math.min(areaA, areaB)
54
+ if (smaller <= 0) return 0
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,
frontend/src/lib/postprocess.ts CHANGED
@@ -1,17 +1,20 @@
1
  /**
2
  * Shared detection post-processing (no retrain).
3
  * Adaptive for dense / mixed-size bundles: looser NMS, skip median size filter,
4
- * size-aware duplicate merge (tiling only).
5
  */
6
  import type { RawDetection } from './nms'
7
- import { filterOutliers, nonMaxSuppression } from './nms'
 
8
  import {
9
  BOX_SIZE_LOOSE_LOWER,
10
  BOX_SIZE_LOOSE_UPPER,
11
  BOX_SIZE_LOWER_MULT,
12
  BOX_SIZE_UPPER_MULT,
13
- CENTER_MERGE_SIZE_RATIO,
14
  DENSE_DETECTION_COUNT,
 
 
15
  IOU_RECALL_RAW_COUNT,
16
  IOU_THRESHOLD,
17
  IOU_THRESHOLD_DENSE,
@@ -19,7 +22,7 @@ import {
19
  MIXED_SIZE_RATIO,
20
  } from './constants'
21
 
22
- export { nonMaxSuppression }
23
 
24
  export function sizeDiversityRatio(detections: RawDetection[]): number {
25
  if (detections.length < 10) return 1
@@ -53,66 +56,212 @@ export function filterBoxSize(
53
  return filterOutliers(detections, lowerMult, upperMult)
54
  }
55
 
 
 
 
 
 
 
56
  /**
57
- * Merge duplicate detections on one pipe (tiling overlap).
58
- * Uses per-box size so neighbours in dense packs are not merged.
 
59
  */
60
- export function mergeCenterClusters(detections: RawDetection[]): RawDetection[] {
61
- if (detections.length <= 1) return detections
 
 
62
 
63
- const sorted = [...detections].sort((a, b) => b.confidence - a.confidence)
64
- const kept: Array<RawDetection & { cx: number; cy: number; minDim: number }> = []
 
 
65
 
66
- for (const det of sorted) {
67
- const w = det.xmax - det.xmin
68
- const h = det.ymax - det.ymin
69
- const cx = (det.xmin + det.xmax) / 2
70
- const cy = (det.ymin + det.ymax) / 2
71
- const minDim = Math.min(w, h)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  let duplicate = false
73
- for (const k of kept) {
74
- const dx = cx - k.cx
75
- const dy = cy - k.cy
76
- const thresh = CENTER_MERGE_SIZE_RATIO * Math.min(minDim, k.minDim)
77
- if (dx * dx + dy * dy < thresh * thresh) {
78
  duplicate = true
79
  break
80
  }
81
  }
82
  if (!duplicate) {
83
- kept.push({ ...det, cx, cy, minDim })
 
84
  }
85
  }
86
 
87
- return kept.map(({ cx: _cx, cy: _cy, minDim: _m, ...det }) => det)
88
  }
89
 
90
- export function applyDetectionPostProcess(
 
 
 
 
 
 
 
 
 
91
  detections: RawDetection[],
92
- options?: { extraOutlierFilter?: boolean },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  ): RawDetection[] {
94
- let out = shouldApplyStrictBoxFilter(detections)
95
- ? filterBoxSize(detections)
96
- : filterOutliers(detections, BOX_SIZE_LOOSE_LOWER, BOX_SIZE_LOOSE_UPPER)
97
- out = mergeCenterClusters(out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  if (options?.extraOutlierFilter) {
99
  out = filterOutliers(out)
100
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  return out
102
  }
103
 
 
 
 
 
 
 
 
 
 
 
 
104
  export function reassignDetectionIds<T extends RawDetection>(
105
  detections: T[],
106
  prefix = 'pipe',
107
  ): Array<T & { id: string }> {
108
  return detections.map((d, i) => ({ ...d, id: `${prefix}-${i}` }))
109
  }
110
-
111
- export function postProcessPipeline(
112
- raw: RawDetection[],
113
- options?: { extraOutlierFilter?: boolean },
114
- ): RawDetection[] {
115
- const iou = selectNmsIou(raw.length)
116
- const nms = nonMaxSuppression(raw, iou, MAX_DETECTIONS)
117
- return applyDetectionPostProcess(nms, options)
118
- }
 
1
  /**
2
  * Shared detection post-processing (no retrain).
3
  * Adaptive for dense / mixed-size bundles: looser NMS, skip median size filter,
4
+ * median-NN centroid dedup, IOS NMS for tiling overlaps, end-on shape filter.
5
  */
6
  import type { RawDetection } from './nms'
7
+ import { filterOutliers, nonMaxSuppression, nmsIOS } from './nms'
8
+ import type { PostProcessReport } from './types'
9
  import {
10
  BOX_SIZE_LOOSE_LOWER,
11
  BOX_SIZE_LOOSE_UPPER,
12
  BOX_SIZE_LOWER_MULT,
13
  BOX_SIZE_UPPER_MULT,
14
+ CENTROID_MERGE_NN_FACTOR,
15
  DENSE_DETECTION_COUNT,
16
+ END_ASPECT_RATIO_MAX,
17
+ IOS_NMS_THRESHOLD,
18
  IOU_RECALL_RAW_COUNT,
19
  IOU_THRESHOLD,
20
  IOU_THRESHOLD_DENSE,
 
22
  MIXED_SIZE_RATIO,
23
  } from './constants'
24
 
25
+ export { nonMaxSuppression, nmsIOS }
26
 
27
  export function sizeDiversityRatio(detections: RawDetection[]): number {
28
  if (detections.length < 10) return 1
 
56
  return filterOutliers(detections, lowerMult, upperMult)
57
  }
58
 
59
+ interface MergeByMedianNnResult {
60
+ detections: RawDetection[]
61
+ merged: number
62
+ medianNn: number | null
63
+ }
64
+
65
  /**
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
 
75
+ const cs = detections.map((d) => ({
76
+ cx: (d.xmin + d.xmax) / 2,
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
  }
121
 
122
+ return { detections: kept, merged: detections.length - kept.length, medianNn }
123
  }
124
 
125
+ interface FilterEndOnShapeResult {
126
+ detections: RawDetection[]
127
+ removed: number
128
+ }
129
+
130
+ /**
131
+ * Drop boxes whose aspect ratio (max(w,h)/min(w,h)) exceeds maxAspect.
132
+ * End-on pipe ends are ~square; side-on pipes are elongated.
133
+ */
134
+ export function filterEndOnShape(
135
  detections: RawDetection[],
136
+ maxAspect = END_ASPECT_RATIO_MAX,
137
+ ): FilterEndOnShapeResult {
138
+ const kept = detections.filter((d) => {
139
+ const w = d.xmax - d.xmin
140
+ const h = d.ymax - d.ymin
141
+ const minDim = Math.min(w, h)
142
+ if (minDim <= 0) return true // guard: keep degenerate boxes
143
+ const aspect = Math.max(w, h) / minDim
144
+ return aspect <= maxAspect
145
+ })
146
+ return { detections: kept, removed: detections.length - kept.length }
147
+ }
148
+
149
+ /** Compute the median area of a set of detections (null for < 3 boxes). */
150
+ function medianArea(detections: RawDetection[]): number | null {
151
+ if (detections.length < 3) return null
152
+ const areas = detections
153
+ .map((d) => (d.xmax - d.xmin) * (d.ymax - d.ymin))
154
+ .sort((a, b) => a - b)
155
+ return areas[Math.floor(areas.length / 2)]
156
+ }
157
+
158
+ export interface PostProcessOptions {
159
+ extraOutlierFilter?: boolean
160
+ wasTiled?: boolean
161
+ onReport?: (r: PostProcessReport) => void
162
+ }
163
+
164
+ /**
165
+ * Full detection post-processing pipeline (no retrain). Fixed step order:
166
+ * 1. raw count
167
+ * 2. adaptive IoU NMS
168
+ * 3. area / box-size filter (strict or loose path)
169
+ * 4. median-NN centroid dedup
170
+ * 5. IOS NMS (tiled only)
171
+ * 6. end-on aspect-ratio shape filter
172
+ * 7. optional extra outlier filter
173
+ * Emits a per-step count report via onReport before returning.
174
+ */
175
+ export function postProcessPipeline(
176
+ raw: RawDetection[],
177
+ options?: PostProcessOptions,
178
  ): RawDetection[] {
179
+ const wasTiled = options?.wasTiled === true
180
+
181
+ // Step 1: raw
182
+ const rawCount = raw.length
183
+
184
+ // Step 2: NMS
185
+ const iou = selectNmsIou(rawCount)
186
+ const nms = nonMaxSuppression(raw, iou, MAX_DETECTIONS)
187
+ const afterNms = nms.length
188
+ const removedByNms = rawCount - afterNms
189
+
190
+ // Step 3: area / box-size filter
191
+ const strict = shouldApplyStrictBoxFilter(nms)
192
+ const areaFiltered = strict
193
+ ? filterBoxSize(nms, BOX_SIZE_LOWER_MULT, BOX_SIZE_UPPER_MULT)
194
+ : filterOutliers(nms, BOX_SIZE_LOOSE_LOWER, BOX_SIZE_LOOSE_UPPER)
195
+ const medianAreaVal = medianArea(nms)
196
+ const afterAreaFilter = areaFiltered.length
197
+ const removedByArea = afterNms - afterAreaFilter
198
+
199
+ // Step 4: centroid dedup (median NN)
200
+ const dedup = mergeByMedianNn(areaFiltered)
201
+ const afterCentroidDedup = dedup.detections.length
202
+ const mergedByCentroidDedup = dedup.merged
203
+ const medianNnDistance = dedup.medianNn
204
+
205
+ // Step 5: IOS NMS (tiled only)
206
+ let iosOut: RawDetection[]
207
+ let afterIosNms: number
208
+ let removedByIosNms: number
209
+ if (wasTiled) {
210
+ iosOut = nmsIOS(dedup.detections, IOS_NMS_THRESHOLD, MAX_DETECTIONS)
211
+ afterIosNms = iosOut.length
212
+ removedByIosNms = afterCentroidDedup - afterIosNms
213
+ } else {
214
+ iosOut = dedup.detections
215
+ afterIosNms = afterCentroidDedup
216
+ removedByIosNms = 0
217
+ }
218
+
219
+ // Step 6: end-on aspect-ratio shape filter
220
+ const shaped = filterEndOnShape(iosOut)
221
+ const afterAspectFilter = shaped.detections.length
222
+ const removedByAspect = afterIosNms - afterAspectFilter
223
+ let out = shaped.detections
224
+
225
+ // Step 7: optional extra outlier filter (folded into final array, no new report field)
226
  if (options?.extraOutlierFilter) {
227
  out = filterOutliers(out)
228
  }
229
+
230
+ const report: PostProcessReport = {
231
+ raw: rawCount,
232
+ afterNms,
233
+ afterAreaFilter,
234
+ afterCentroidDedup,
235
+ afterIosNms,
236
+ afterAspectFilter,
237
+ removedByNms,
238
+ removedByArea,
239
+ mergedByCentroidDedup,
240
+ removedByIosNms,
241
+ removedByAspect,
242
+ medianNnDistance,
243
+ medianArea: medianAreaVal,
244
+ tilingUsed: wasTiled,
245
+ }
246
+ options?.onReport?.(report)
247
+
248
  return out
249
  }
250
 
251
+ /**
252
+ * Delegate to postProcessPipeline so legacy callers keep working.
253
+ * Accepts the same options and threads wasTiled + onReport through.
254
+ */
255
+ export function applyDetectionPostProcess(
256
+ detections: RawDetection[],
257
+ options?: PostProcessOptions,
258
+ ): RawDetection[] {
259
+ return postProcessPipeline(detections, options)
260
+ }
261
+
262
  export function reassignDetectionIds<T extends RawDetection>(
263
  detections: T[],
264
  prefix = 'pipe',
265
  ): Array<T & { id: string }> {
266
  return detections.map((d, i) => ({ ...d, id: `${prefix}-${i}` }))
267
  }
 
 
 
 
 
 
 
 
 
frontend/src/lib/types.ts CHANGED
@@ -35,3 +35,21 @@ export interface LetterboxMeta {
35
  padY: number
36
  inputSize: number
37
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  padY: number
36
  inputSize: number
37
  }
38
+
39
+ /** Per-step count report emitted by the post-processing pipeline. */
40
+ export interface PostProcessReport {
41
+ raw: number
42
+ afterNms: number
43
+ afterAreaFilter: number
44
+ afterCentroidDedup: number
45
+ afterIosNms: number // == afterCentroidDedup when not tiled
46
+ afterAspectFilter: number // FINAL count
47
+ removedByNms: number
48
+ removedByArea: number
49
+ mergedByCentroidDedup: number
50
+ removedByIosNms: number
51
+ removedByAspect: number
52
+ medianNnDistance: number | null
53
+ medianArea: number | null
54
+ tilingUsed: boolean
55
+ }
postprocess.py CHANGED
@@ -1,16 +1,32 @@
1
- """Detection post-processing shared by server inference (no retrain)."""
 
 
 
 
 
 
 
 
 
 
 
 
2
  from __future__ import annotations
3
 
4
- BOX_SIZE_LOWER_MULT = 0.35
5
  BOX_SIZE_UPPER_MULT = 2.8
6
- BOX_SIZE_LOOSE_LOWER = 0.1
7
  BOX_SIZE_LOOSE_UPPER = 12.0
8
  MIXED_SIZE_RATIO = 3.0
9
  DENSE_DETECTION_COUNT = 500
10
- CENTER_MERGE_SIZE_RATIO = 0.28
11
  IOU_THRESHOLD = 0.45
12
  IOU_THRESHOLD_DENSE = 0.52
13
  IOU_RECALL_RAW_COUNT = 1500
 
 
 
 
14
 
15
 
16
  def size_diversity_ratio(boxes: list) -> float:
@@ -75,39 +91,142 @@ def _filter_loose(boxes: list, scores: list) -> tuple[list, list]:
75
  return out_boxes, out_scores
76
 
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  def merge_center_clusters(
79
  boxes: list,
80
  scores: list,
81
  ) -> tuple[list, list]:
82
- if len(boxes) <= 1:
83
- return boxes, scores
 
84
 
85
- order = sorted(range(len(boxes)), key=lambda i: scores[i], reverse=True)
 
 
 
 
 
 
86
  kept_boxes: list = []
87
  kept_scores: list = []
88
- meta: list[tuple[float, float, float]] = []
89
-
90
- for i in order:
91
- b = boxes[i]
92
  w = b[2] - b[0]
93
  h = b[3] - b[1]
94
- cx = (b[0] + b[2]) / 2
95
- cy = (b[1] + b[3]) / 2
96
  min_dim = min(w, h)
97
- duplicate = False
98
- for kx, ky, kmin in meta:
99
- dx = cx - kx
100
- dy = cy - ky
101
- thresh = CENTER_MERGE_SIZE_RATIO * min(min_dim, kmin)
102
- if dx * dx + dy * dy < thresh * thresh:
103
- duplicate = True
104
- break
105
- if not duplicate:
106
  kept_boxes.append(b)
107
- kept_scores.append(scores[i])
108
- meta.append((cx, cy, min_dim))
109
-
110
- return kept_boxes, kept_scores
 
 
 
 
 
 
 
111
 
112
 
113
  def apply_detection_postprocess(
@@ -116,14 +235,75 @@ def apply_detection_postprocess(
116
  *,
117
  extra_outlier_filter: bool = False,
118
  filter_outliers_fn=None,
119
- ) -> tuple[list, list]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  if _should_apply_strict_box_filter(boxes):
121
  boxes, scores = filter_box_size(boxes, scores)
122
  else:
123
  boxes, scores = _filter_loose(boxes, scores)
124
- boxes, scores = merge_center_clusters(boxes, scores)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  if extra_outlier_filter and filter_outliers_fn and boxes:
126
  keep = filter_outliers_fn(boxes)
127
  boxes = [boxes[i] for i in keep]
128
  scores = [scores[i] for i in keep]
129
- return boxes, scores
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Detection post-processing shared by server inference (no retrain).
2
+
3
+ Mirrors the frontend TypeScript pipeline (frontend/src/lib/postprocess.ts) so
4
+ server-side results are consistent regardless of where inference runs.
5
+
6
+ Step order in ``apply_detection_postprocess`` (must match the TS mirror):
7
+ 1. NMS (performed in ``detect.py`` before this function is called)
8
+ 2. area/box-size filter (strict or loose bounds)
9
+ 3. centroid dedup via nearest-neighbour median (``merge_by_median_nn``)
10
+ 4. intersection-over-smaller NMS — tiling only (``nms_ios``)
11
+ 5. aspect-ratio shape filter (``filter_end_on_shape``)
12
+ 6. (optional) extra outlier filter — last
13
+ """
14
  from __future__ import annotations
15
 
16
+ BOX_SIZE_LOWER_MULT = 0.43
17
  BOX_SIZE_UPPER_MULT = 2.8
18
+ BOX_SIZE_LOOSE_LOWER = 0.45
19
  BOX_SIZE_LOOSE_UPPER = 12.0
20
  MIXED_SIZE_RATIO = 3.0
21
  DENSE_DETECTION_COUNT = 500
22
+ CENTER_MERGE_SIZE_RATIO = 0.28 # kept for back-compat; no longer used by merge step
23
  IOU_THRESHOLD = 0.45
24
  IOU_THRESHOLD_DENSE = 0.52
25
  IOU_RECALL_RAW_COUNT = 1500
26
+ MAX_DET = 6000
27
+ CENTROID_MERGE_NN_FACTOR = 0.5
28
+ IOS_NMS_THRESHOLD = 0.5
29
+ END_ASPECT_RATIO_MAX = 2.5
30
 
31
 
32
  def size_diversity_ratio(boxes: list) -> float:
 
91
  return out_boxes, out_scores
92
 
93
 
94
+ def nms_ios(
95
+ boxes: list,
96
+ scores: list,
97
+ ios_threshold: float = IOS_NMS_THRESHOLD,
98
+ max_det: int = MAX_DET,
99
+ ) -> list[int]:
100
+ """Intersection-Over-Smaller greedy NMS.
101
+
102
+ ``metric(a, b) = intersection / min(area_a, area_b)``.
103
+ Sort indices by score descending, greedily keep, suppress any remaining box
104
+ whose IOS vs a kept box exceeds ``ios_threshold``. Returns kept indices.
105
+ """
106
+ import numpy as np
107
+
108
+ if len(boxes) == 0:
109
+ return []
110
+
111
+ boxes_arr = np.asarray(boxes, dtype=np.float32)
112
+ scores_arr = np.asarray(scores, dtype=np.float32)
113
+ x1 = boxes_arr[:, 0]
114
+ y1 = boxes_arr[:, 1]
115
+ x2 = boxes_arr[:, 2]
116
+ y2 = boxes_arr[:, 3]
117
+ areas = (x2 - x1) * (y2 - y1)
118
+ order = scores_arr.argsort()[::-1]
119
+ keep: list[int] = []
120
+
121
+ while order.size > 0 and len(keep) < max_det:
122
+ i = int(order[0])
123
+ keep.append(i)
124
+ if order.size == 1:
125
+ break
126
+ rest = order[1:]
127
+ xx1 = np.maximum(x1[i], x1[rest])
128
+ yy1 = np.maximum(y1[i], y1[rest])
129
+ xx2 = np.minimum(x2[i], x2[rest])
130
+ yy2 = np.minimum(y2[i], y2[rest])
131
+ w = np.maximum(0.0, xx2 - xx1)
132
+ h = np.maximum(0.0, yy2 - yy1)
133
+ inter = w * h
134
+ min_area = np.minimum(areas[i], areas[rest])
135
+ ios = inter / (min_area + 1e-6)
136
+ order = rest[ios <= ios_threshold]
137
+
138
+ return keep
139
+
140
+
141
+ def merge_by_median_nn(
142
+ boxes: list,
143
+ scores: list,
144
+ ) -> tuple[list, list, dict]:
145
+ """Centroid dedup using a nearest-neighbour median threshold.
146
+
147
+ Replaces the old size-ratio ``merge_center_clusters`` behaviour. Boxes whose
148
+ centroid is within ``CENTROID_MERGE_NN_FACTOR * median_nn`` of an already
149
+ kept (higher-score) box are treated as duplicates and dropped.
150
+ """
151
+ import numpy as np
152
+
153
+ if len(boxes) < 3:
154
+ return boxes, scores, {"merged": 0, "median_nn": None}
155
+
156
+ boxes_arr = np.asarray(boxes, dtype=np.float32)
157
+ cx = (boxes_arr[:, 0] + boxes_arr[:, 2]) / 2
158
+ cy = (boxes_arr[:, 1] + boxes_arr[:, 3]) / 2
159
+ centroids = np.stack([cx, cy], axis=1)
160
+
161
+ # Pairwise squared distances (O(n^2); fine for server pipeline sizes).
162
+ diff = centroids[:, None, :] - centroids[None, :, :]
163
+ dist2 = np.sum(diff * diff, axis=2)
164
+ np.fill_diagonal(dist2, np.inf)
165
+ nn = np.sqrt(np.min(dist2, axis=1))
166
+ median_nn = float(np.median(nn))
167
+ merge_threshold = CENTROID_MERGE_NN_FACTOR * median_nn
168
+ thresh2 = merge_threshold * merge_threshold
169
+
170
+ n = len(boxes)
171
+ order = sorted(range(n), key=lambda i: scores[i], reverse=True)
172
+ kept_idx: list[int] = []
173
+ kept_centroids: list = []
174
+ for i in order:
175
+ ci = centroids[i]
176
+ duplicate = False
177
+ for kc in kept_centroids:
178
+ dx = ci[0] - kc[0]
179
+ dy = ci[1] - kc[1]
180
+ if dx * dx + dy * dy < thresh2:
181
+ duplicate = True
182
+ break
183
+ if not duplicate:
184
+ kept_idx.append(i)
185
+ kept_centroids.append(ci)
186
+
187
+ kept_boxes = [boxes[i] for i in kept_idx]
188
+ kept_scores = [scores[i] for i in kept_idx]
189
+ return (
190
+ kept_boxes,
191
+ kept_scores,
192
+ {"merged": n - len(kept_idx), "median_nn": median_nn},
193
+ )
194
+
195
+
196
  def merge_center_clusters(
197
  boxes: list,
198
  scores: list,
199
  ) -> tuple[list, list]:
200
+ """Back-compat wrapper around :func:`merge_by_median_nn`."""
201
+ boxes, scores, _meta = merge_by_median_nn(boxes, scores)
202
+ return boxes, scores
203
 
204
+
205
+ def filter_end_on_shape(
206
+ boxes: list,
207
+ scores: list,
208
+ max_aspect: float = END_ASPECT_RATIO_MAX,
209
+ ) -> tuple[list, list, dict]:
210
+ """Drop elongated boxes whose aspect ratio exceeds ``max_aspect``."""
211
  kept_boxes: list = []
212
  kept_scores: list = []
213
+ for b, s in zip(boxes, scores):
 
 
 
214
  w = b[2] - b[0]
215
  h = b[3] - b[1]
 
 
216
  min_dim = min(w, h)
217
+ if min_dim == 0:
 
 
 
 
 
 
 
 
218
  kept_boxes.append(b)
219
+ kept_scores.append(s)
220
+ continue
221
+ aspect = max(w, h) / min_dim
222
+ if aspect <= max_aspect:
223
+ kept_boxes.append(b)
224
+ kept_scores.append(s)
225
+ return (
226
+ kept_boxes,
227
+ kept_scores,
228
+ {"removed": len(boxes) - len(kept_boxes)},
229
+ )
230
 
231
 
232
  def apply_detection_postprocess(
 
235
  *,
236
  extra_outlier_filter: bool = False,
237
  filter_outliers_fn=None,
238
+ was_tiled: bool = False,
239
+ ) -> tuple[list, list, dict]:
240
+ """Server post-processing pipeline; returns ``(boxes, scores, report)``.
241
+
242
+ ``boxes``/``scores`` are assumed ALREADY NMS-filtered by ``detect.py``.
243
+ The real pre-NMS / post-NMS counts are injected by ``detect.py`` into the
244
+ returned report (``raw``, ``after_nms``, ``removed_by_nms``, ``tiling_used``).
245
+ """
246
+ raw = len(boxes)
247
+ after_nms = len(boxes)
248
+ removed_by_nms = 0
249
+
250
+ # 3. area / box-size filter — record median of areas going into this step.
251
+ if len(boxes) >= 3:
252
+ areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
253
+ sorted_areas = sorted(areas)
254
+ median_area: float | None = float(sorted_areas[len(sorted_areas) // 2])
255
+ else:
256
+ median_area = None
257
+
258
  if _should_apply_strict_box_filter(boxes):
259
  boxes, scores = filter_box_size(boxes, scores)
260
  else:
261
  boxes, scores = _filter_loose(boxes, scores)
262
+ after_area_filter = len(boxes)
263
+ removed_by_area = after_nms - after_area_filter
264
+
265
+ # 4. centroid dedup via nearest-neighbour median.
266
+ boxes, scores, merge_meta = merge_by_median_nn(boxes, scores)
267
+ after_centroid_dedup = len(boxes)
268
+ merged_by_centroid_dedup = merge_meta["merged"]
269
+ median_nn_distance = merge_meta["median_nn"]
270
+
271
+ # 5. intersection-over-smaller NMS — tiling only.
272
+ if was_tiled and len(boxes) > 0:
273
+ keep = nms_ios(boxes, scores)
274
+ boxes = [boxes[i] for i in keep]
275
+ scores = [scores[i] for i in keep]
276
+ after_ios_nms = len(boxes)
277
+ removed_by_ios_nms = after_centroid_dedup - after_ios_nms
278
+ else:
279
+ after_ios_nms = after_centroid_dedup
280
+ removed_by_ios_nms = 0
281
+
282
+ # 6. aspect-ratio shape filter (final).
283
+ boxes, scores, _shape_meta = filter_end_on_shape(boxes, scores)
284
+ after_aspect_filter = len(boxes)
285
+ removed_by_aspect = after_ios_nms - after_aspect_filter
286
+
287
+ # 7. (optional) extra outlier filter — very last step.
288
  if extra_outlier_filter and filter_outliers_fn and boxes:
289
  keep = filter_outliers_fn(boxes)
290
  boxes = [boxes[i] for i in keep]
291
  scores = [scores[i] for i in keep]
292
+
293
+ report = {
294
+ "raw": raw,
295
+ "after_nms": after_nms,
296
+ "after_area_filter": after_area_filter,
297
+ "after_centroid_dedup": after_centroid_dedup,
298
+ "after_ios_nms": after_ios_nms,
299
+ "after_aspect_filter": after_aspect_filter,
300
+ "removed_by_nms": removed_by_nms,
301
+ "removed_by_area": removed_by_area,
302
+ "merged_by_centroid_dedup": merged_by_centroid_dedup,
303
+ "removed_by_ios_nms": removed_by_ios_nms,
304
+ "removed_by_aspect": removed_by_aspect,
305
+ "median_nn_distance": median_nn_distance,
306
+ "median_area": median_area,
307
+ "tiling_used": was_tiled,
308
+ }
309
+ return boxes, scores, report