File size: 9,367 Bytes
190dbf0
 
e3b60de
b505c60
190dbf0
 
b505c60
 
190dbf0
e3b60de
 
190dbf0
 
b505c60
e3b60de
b505c60
 
e3b60de
190dbf0
e3b60de
190dbf0
e3b60de
190dbf0
 
b505c60
190dbf0
e3b60de
 
 
 
 
 
 
 
190dbf0
 
e3b60de
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
 
 
 
 
 
 
b505c60
 
 
 
 
 
190dbf0
b505c60
 
 
4608266
 
 
 
 
 
 
190dbf0
b505c60
4608266
 
b505c60
 
190dbf0
b505c60
 
 
 
190dbf0
4608266
 
 
 
 
 
 
b505c60
4608266
 
 
 
 
 
b505c60
4608266
b505c60
4608266
 
b505c60
 
4608266
 
 
 
 
b505c60
 
 
 
 
 
4608266
 
190dbf0
4608266
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
4608266
 
 
 
 
 
 
b505c60
190dbf0
 
 
b505c60
190dbf0
 
b505c60
 
 
 
 
 
 
 
 
 
190dbf0
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
b505c60
 
 
 
 
 
 
 
 
 
 
c9976d7
 
 
 
 
 
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
/**
 * Shared detection post-processing (no retrain).
 * Adaptive for dense / mixed-size bundles: looser NMS, skip median size filter,
 * median-NN centroid dedup, IOS NMS for tiling overlaps, end-on shape filter.
 */
import type { RawDetection } from './nms'
import { filterOutliers, nonMaxSuppression, nmsIOS } from './nms'
import type { PostProcessReport } from './types'
import {
  BOX_SIZE_LOOSE_LOWER,
  BOX_SIZE_LOOSE_UPPER,
  BOX_SIZE_LOWER_MULT,
  BOX_SIZE_UPPER_MULT,
  CENTROID_MERGE_NN_FACTOR,
  DENSE_DETECTION_COUNT,
  END_ASPECT_RATIO_MAX,
  IOS_NMS_THRESHOLD,
  IOU_RECALL_RAW_COUNT,
  IOU_THRESHOLD,
  IOU_THRESHOLD_DENSE,
  MAX_DETECTIONS,
  MIXED_SIZE_RATIO,
} from './constants'

export { nonMaxSuppression, nmsIOS }

export function sizeDiversityRatio(detections: RawDetection[]): number {
  if (detections.length < 10) return 1
  const areas = detections
    .map((d) => (d.xmax - d.xmin) * (d.ymax - d.ymin))
    .sort((a, b) => a - b)
  const p10 = areas[Math.floor(areas.length * 0.1)]
  const p90 = areas[Math.floor(areas.length * 0.9)]
  return p90 / Math.max(p10, 1)
}

export function selectNmsIou(rawCount: number): number {
  if (rawCount >= IOU_RECALL_RAW_COUNT) return IOU_THRESHOLD_DENSE
  if (rawCount >= 600) return 0.48
  return IOU_THRESHOLD
}

function shouldApplyStrictBoxFilter(detections: RawDetection[]): boolean {
  if (detections.length >= DENSE_DETECTION_COUNT) return false
  if (sizeDiversityRatio(detections) >= MIXED_SIZE_RATIO) return false
  return true
}

/** Drop boxes much smaller/larger than the typical pipe end (uniform bundles only). */
export function filterBoxSize(
  detections: RawDetection[],
  lowerMult = BOX_SIZE_LOWER_MULT,
  upperMult = BOX_SIZE_UPPER_MULT,
): RawDetection[] {
  if (detections.length < 3) return detections
  return filterOutliers(detections, lowerMult, upperMult)
}

interface MergeByMedianNnResult {
  detections: RawDetection[]
  merged: number
  medianNn: number | null
}

/**
 * Merge duplicate detections using median nearest-neighbour centroid distance.
 * Boxes whose centroid is closer than CENTROID_MERGE_NN_FACTOR x median NN
 * distance to an already-kept (higher-confidence) box are dropped.
 *
 * Performance: the median NN distance is estimated from an evenly-spaced sample
 * (O(K*n) instead of an all-pairs O(n^2) scan — the median is robust to
 * sampling), and the dedup pass uses a uniform grid (cell = mergeThreshold,
 * 3x3 neighbourhood query) so each centroid only compares against nearby kept
 * centroids. Together this keeps dense bundles (2000+ pipes) from blocking the
 * UI while preserving the same dedup behaviour.
 */
export function mergeByMedianNn(detections: RawDetection[]): MergeByMedianNnResult {
  const n = detections.length
  if (n < 3) {
    return { detections, merged: 0, medianNn: null }
  }

  const cs = detections.map((d) => ({
    cx: (d.xmin + d.xmax) / 2,
    cy: (d.ymin + d.ymax) / 2,
  }))

  // Estimate the median nearest-neighbour distance from an evenly-spaced sample
  // of centroids. For n <= sample size this is the exact all-pairs median.
  const sampleK = Math.min(256, n)
  const sampleNn: number[] = []
  for (let s = 0; s < sampleK; s++) {
    const i = Math.floor((s / sampleK) * n)
    const ci = cs[i]
    let best = Infinity
    for (let j = 0; j < n; j++) {
      if (j === i) continue
      const dx = ci.cx - cs[j].cx
      const dy = ci.cy - cs[j].cy
      const dd = dx * dx + dy * dy
      if (dd < best) best = dd
    }
    sampleNn.push(Math.sqrt(best))
  }
  sampleNn.sort((a, b) => a - b)
  const medianNn = sampleNn[Math.floor(sampleNn.length / 2)]
  const mergeThreshold = CENTROID_MERGE_NN_FACTOR * medianNn

  // Dedup via a uniform grid on centroids (cell = mergeThreshold). A kept
  // centroid within mergeThreshold must sit in the candidate's cell or one of
  // its 8 neighbours, so a 3x3 query is complete and exact for this threshold.
  const gcell = Math.max(1, mergeThreshold)
  const grid = new Map<number, Array<{ cx: number; cy: number }>>()
  const paired = detections
    .map((d, i) => ({ d, c: cs[i] }))
    .sort((a, b) => b.d.confidence - a.d.confidence)

  const kept: RawDetection[] = []
  for (const { d, c } of paired) {
    const gx = Math.floor(c.cx / gcell)
    const gy = Math.floor(c.cy / gcell)
    let duplicate = false
    for (let dx = -1; dx <= 1 && !duplicate; dx++) {
      for (let dy = -1; dy <= 1 && !duplicate; dy++) {
        const bucket = grid.get((gx + dx) * 100000 + (gy + dy))
        if (!bucket) continue
        for (const k of bucket) {
          const ddx = c.cx - k.cx
          const ddy = c.cy - k.cy
          if (ddx * ddx + ddy * ddy < mergeThreshold * mergeThreshold) {
            duplicate = true
            break
          }
        }
      }
    }
    if (!duplicate) {
      const key = gx * 100000 + gy
      let bucket = grid.get(key)
      if (!bucket) {
        bucket = []
        grid.set(key, bucket)
      }
      bucket.push(c)
      kept.push(d)
    }
  }

  return { detections: kept, merged: detections.length - kept.length, medianNn }
}

interface FilterEndOnShapeResult {
  detections: RawDetection[]
  removed: number
}

/**
 * Drop boxes whose aspect ratio (max(w,h)/min(w,h)) exceeds maxAspect.
 * End-on pipe ends are ~square; side-on pipes are elongated.
 */
export function filterEndOnShape(
  detections: RawDetection[],
  maxAspect = END_ASPECT_RATIO_MAX,
): FilterEndOnShapeResult {
  const kept = detections.filter((d) => {
    const w = d.xmax - d.xmin
    const h = d.ymax - d.ymin
    const minDim = Math.min(w, h)
    if (minDim <= 0) return true // guard: keep degenerate boxes
    const aspect = Math.max(w, h) / minDim
    return aspect <= maxAspect
  })
  return { detections: kept, removed: detections.length - kept.length }
}

/** Compute the median area of a set of detections (null for < 3 boxes). */
function medianArea(detections: RawDetection[]): number | null {
  if (detections.length < 3) return null
  const areas = detections
    .map((d) => (d.xmax - d.xmin) * (d.ymax - d.ymin))
    .sort((a, b) => a - b)
  return areas[Math.floor(areas.length / 2)]
}

export interface PostProcessOptions {
  extraOutlierFilter?: boolean
  wasTiled?: boolean
  onReport?: (r: PostProcessReport) => void
}

/**
 * Full detection post-processing pipeline (no retrain). Fixed step order:
 * 1. raw count
 * 2. adaptive IoU NMS
 * 3. area / box-size filter (strict or loose path)
 * 4. median-NN centroid dedup
 * 5. IOS NMS (tiled only)
 * 6. end-on aspect-ratio shape filter
 * 7. optional extra outlier filter
 * Emits a per-step count report via onReport before returning.
 */
export function postProcessPipeline(
  raw: RawDetection[],
  options?: PostProcessOptions,
): RawDetection[] {
  const wasTiled = options?.wasTiled === true

  // Step 1: raw
  const rawCount = raw.length

  // Step 2: NMS
  const iou = selectNmsIou(rawCount)
  const nms = nonMaxSuppression(raw, iou, MAX_DETECTIONS)
  const afterNms = nms.length
  const removedByNms = rawCount - afterNms

  // Step 3: area / box-size filter
  const strict = shouldApplyStrictBoxFilter(nms)
  const areaFiltered = strict
    ? filterBoxSize(nms, BOX_SIZE_LOWER_MULT, BOX_SIZE_UPPER_MULT)
    : filterOutliers(nms, BOX_SIZE_LOOSE_LOWER, BOX_SIZE_LOOSE_UPPER)
  const medianAreaVal = medianArea(nms)
  const afterAreaFilter = areaFiltered.length
  const removedByArea = afterNms - afterAreaFilter

  // Step 4: centroid dedup (median NN)
  const dedup = mergeByMedianNn(areaFiltered)
  const afterCentroidDedup = dedup.detections.length
  const mergedByCentroidDedup = dedup.merged
  const medianNnDistance = dedup.medianNn

  // Step 5: IOS NMS (tiled only)
  let iosOut: RawDetection[]
  let afterIosNms: number
  let removedByIosNms: number
  if (wasTiled) {
    iosOut = nmsIOS(dedup.detections, IOS_NMS_THRESHOLD, MAX_DETECTIONS)
    afterIosNms = iosOut.length
    removedByIosNms = afterCentroidDedup - afterIosNms
  } else {
    iosOut = dedup.detections
    afterIosNms = afterCentroidDedup
    removedByIosNms = 0
  }

  // Step 6: end-on aspect-ratio shape filter
  const shaped = filterEndOnShape(iosOut)
  const afterAspectFilter = shaped.detections.length
  const removedByAspect = afterIosNms - afterAspectFilter
  let out = shaped.detections

  // Step 7: optional extra outlier filter (folded into final array, no new report field)
  if (options?.extraOutlierFilter) {
    out = filterOutliers(out)
  }

  const report: PostProcessReport = {
    raw: rawCount,
    afterNms,
    afterAreaFilter,
    afterCentroidDedup,
    afterIosNms,
    afterAspectFilter,
    removedByNms,
    removedByArea,
    mergedByCentroidDedup,
    removedByIosNms,
    removedByAspect,
    medianNnDistance,
    medianArea: medianAreaVal,
    tilingUsed: wasTiled,
  }
  options?.onReport?.(report)

  return out
}

/**
 * Delegate to postProcessPipeline so legacy callers keep working.
 * Accepts the same options and threads wasTiled + onReport through.
 */
export function applyDetectionPostProcess(
  detections: RawDetection[],
  options?: PostProcessOptions,
): RawDetection[] {
  return postProcessPipeline(detections, options)
}

export function reassignDetectionIds<T extends RawDetection>(
  detections: T[],
  prefix = 'pipe',
): Array<T & { id: string }> {
  return detections.map((d, i) => ({ ...d, id: `${prefix}-${i}` }))
}