pipecountapp-dev / frontend /src /lib /postprocess.ts
Khunndev
Sisyphus
Make client NMS and centroid dedup O(n) with a spatial grid for dense bundles.
4608266
Raw History Blame Contribute Delete
9.37 kB
/**
* 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}` }))
}