File size: 10,740 Bytes
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
b505c60
190dbf0
b505c60
e3b60de
 
 
b505c60
e3b60de
 
 
b505c60
1f3b2fa
 
 
190dbf0
 
e3b60de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3b60de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3b2fa
 
 
 
 
 
 
 
b505c60
 
 
1f3b2fa
 
b505c60
 
 
 
 
 
 
1f3b2fa
 
 
 
 
 
 
b505c60
 
 
 
1f3b2fa
 
 
 
 
b505c60
 
 
1f3b2fa
 
 
 
 
 
 
b505c60
 
 
 
 
 
 
 
 
 
190dbf0
 
 
 
b505c60
 
 
190dbf0
b505c60
 
 
 
 
 
 
190dbf0
 
b505c60
e3b60de
 
 
b505c60
190dbf0
b505c60
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
 
 
 
 
 
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3b60de
 
 
 
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
 
 
 
b505c60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Detection post-processing shared by server inference (no retrain).

Mirrors the frontend TypeScript pipeline (frontend/src/lib/postprocess.ts) so
server-side results are consistent regardless of where inference runs.

Step order in ``apply_detection_postprocess`` (must match the TS mirror):
  1. NMS        (performed in ``detect.py`` before this function is called)
  2. area/box-size filter (strict or loose bounds)
  3. centroid dedup via nearest-neighbour median (``merge_by_median_nn``)
  4. intersection-over-smaller NMS — tiling only (``nms_ios``)
  5. aspect-ratio shape filter (``filter_end_on_shape``)
  6. (optional) extra outlier filter — last
"""
from __future__ import annotations

BOX_SIZE_LOWER_MULT = 0.43
BOX_SIZE_UPPER_MULT = 2.8
BOX_SIZE_LOOSE_LOWER = 0.45
BOX_SIZE_LOOSE_UPPER = 12.0
MIXED_SIZE_RATIO = 3.0
DENSE_DETECTION_COUNT = 500
CENTER_MERGE_SIZE_RATIO = 0.28  # kept for back-compat; no longer used by merge step
IOU_THRESHOLD = 0.45
IOU_THRESHOLD_DENSE = 0.52
IOU_RECALL_RAW_COUNT = 1500
MAX_DET = 6000
CENTROID_MERGE_NN_FACTOR = 0.4
IOS_NMS_THRESHOLD = 0.7
END_ASPECT_RATIO_MAX = 3.5


def size_diversity_ratio(boxes: list) -> float:
    if len(boxes) < 10:
        return 1.0
    areas = sorted((b[2] - b[0]) * (b[3] - b[1]) for b in boxes)
    p10 = areas[int(len(areas) * 0.1)]
    p90 = areas[int(len(areas) * 0.9)]
    return p90 / max(p10, 1.0)


def select_nms_iou(raw_count: int) -> float:
    if raw_count >= IOU_RECALL_RAW_COUNT:
        return IOU_THRESHOLD_DENSE
    if raw_count >= 600:
        return 0.48
    return IOU_THRESHOLD


def _should_apply_strict_box_filter(boxes: list) -> bool:
    if len(boxes) >= DENSE_DETECTION_COUNT:
        return False
    if size_diversity_ratio(boxes) >= MIXED_SIZE_RATIO:
        return False
    return True


def filter_box_size(
    boxes: list,
    scores: list,
    lower_mult: float = BOX_SIZE_LOWER_MULT,
    upper_mult: float = BOX_SIZE_UPPER_MULT,
) -> tuple[list, list]:
    if len(boxes) < 3:
        return boxes, scores
    areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
    sorted_areas = sorted(areas)
    median = sorted_areas[len(sorted_areas) // 2]
    lo = median * lower_mult
    hi = median * upper_mult
    out_boxes, out_scores = [], []
    for b, s, a in zip(boxes, scores, areas):
        if lo <= a <= hi:
            out_boxes.append(b)
            out_scores.append(s)
    return out_boxes, out_scores


def _filter_loose(boxes: list, scores: list) -> tuple[list, list]:
    if len(boxes) < 3:
        return boxes, scores
    areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
    sorted_areas = sorted(areas)
    median = sorted_areas[len(sorted_areas) // 2]
    lo = median * BOX_SIZE_LOOSE_LOWER
    hi = median * BOX_SIZE_LOOSE_UPPER
    out_boxes, out_scores = [], []
    for b, s, a in zip(boxes, scores, areas):
        if lo <= a <= hi:
            out_boxes.append(b)
            out_scores.append(s)
    return out_boxes, out_scores


def nms_ios(
    boxes: list,
    scores: list,
    ios_threshold: float = IOS_NMS_THRESHOLD,
    max_det: int = MAX_DET,
) -> list[int]:
    """Intersection-Over-Smaller greedy NMS.

    ``metric(a, b) = intersection / min(area_a, area_b)``.
    Sort indices by score descending, greedily keep, suppress any remaining box
    whose IOS vs a kept box exceeds ``ios_threshold``. Returns kept indices.
    """
    import numpy as np

    if len(boxes) == 0:
        return []

    boxes_arr = np.asarray(boxes, dtype=np.float32)
    scores_arr = np.asarray(scores, dtype=np.float32)
    x1 = boxes_arr[:, 0]
    y1 = boxes_arr[:, 1]
    x2 = boxes_arr[:, 2]
    y2 = boxes_arr[:, 3]
    areas = (x2 - x1) * (y2 - y1)
    order = scores_arr.argsort()[::-1]
    keep: list[int] = []

    while order.size > 0 and len(keep) < max_det:
        i = int(order[0])
        keep.append(i)
        if order.size == 1:
            break
        rest = order[1:]
        xx1 = np.maximum(x1[i], x1[rest])
        yy1 = np.maximum(y1[i], y1[rest])
        xx2 = np.minimum(x2[i], x2[rest])
        yy2 = np.minimum(y2[i], y2[rest])
        w = np.maximum(0.0, xx2 - xx1)
        h = np.maximum(0.0, yy2 - yy1)
        inter = w * h
        min_area = np.minimum(areas[i], areas[rest])
        ios = inter / (min_area + 1e-6)
        order = rest[ios <= ios_threshold]

    return keep


def merge_by_median_nn(
    boxes: list,
    scores: list,
) -> tuple[list, list, dict]:
    """Centroid dedup using a nearest-neighbour median threshold.

    Boxes whose centroid is within ``CENTROID_MERGE_NN_FACTOR * median_nn`` of an
    already kept (higher-score) box are treated as duplicates and dropped.

    Performance: the median NN distance is estimated from an evenly-spaced sample
    of centroids (O(K*n)) instead of a full O(n^2) pairwise matrix, and the greedy
    dedup checks each candidate against all kept-so-far in a single vectorised op
    (preallocated buffer, no per-step copy). On dense bundles (2000+ pipes) the
    old pairwise matrix + Python loop took seconds; this keeps it in tens of ms.
    """
    import numpy as np

    n = len(boxes)
    if n < 3:
        return boxes, scores, {"merged": 0, "median_nn": None}

    boxes_arr = np.asarray(boxes, dtype=np.float32)
    cx = (boxes_arr[:, 0] + boxes_arr[:, 2]) / 2
    cy = (boxes_arr[:, 1] + boxes_arr[:, 3]) / 2
    centroids = np.stack([cx, cy], axis=1)

    # Median NN distance from an evenly-spaced sample -> O(K*n), no n^2 matrix.
    sample_idx = np.unique(np.linspace(0, n - 1, min(256, n)).astype(np.int32))
    k = len(sample_idx)
    diff = centroids[sample_idx][:, None, :] - centroids[None, :, :]  # (k,n,2)
    dist2 = np.sum(diff * diff, axis=2)                                # (k,n)
    dist2[np.arange(k), sample_idx] = np.inf                           # exclude self
    nn = np.sqrt(dist2.min(axis=1))
    median_nn = float(np.median(nn))
    merge_threshold = CENTROID_MERGE_NN_FACTOR * median_nn
    thresh2 = merge_threshold * merge_threshold

    # Greedy dedup in score order; each candidate checks all kept so far in ONE
    # vectorised op (preallocated buffer, no per-step copy).
    order = np.argsort(scores)[::-1]
    kept_buf = np.empty((n, 2), dtype=np.float32)
    kept_count = 0
    kept_idx: list[int] = []
    for i in order:
        ci = centroids[i]
        if kept_count:
            d = kept_buf[:kept_count] - ci
            if (d[:, 0] * d[:, 0] + d[:, 1] * d[:, 1] < thresh2).any():
                continue
        kept_buf[kept_count] = ci
        kept_count += 1
        kept_idx.append(int(i))

    kept_boxes = [boxes[i] for i in kept_idx]
    kept_scores = [scores[i] for i in kept_idx]
    return (
        kept_boxes,
        kept_scores,
        {"merged": n - len(kept_idx), "median_nn": median_nn},
    )


def merge_center_clusters(
    boxes: list,
    scores: list,
) -> tuple[list, list]:
    """Back-compat wrapper around :func:`merge_by_median_nn`."""
    boxes, scores, _meta = merge_by_median_nn(boxes, scores)
    return boxes, scores


def filter_end_on_shape(
    boxes: list,
    scores: list,
    max_aspect: float = END_ASPECT_RATIO_MAX,
) -> tuple[list, list, dict]:
    """Drop elongated boxes whose aspect ratio exceeds ``max_aspect``."""
    kept_boxes: list = []
    kept_scores: list = []
    for b, s in zip(boxes, scores):
        w = b[2] - b[0]
        h = b[3] - b[1]
        min_dim = min(w, h)
        if min_dim == 0:
            kept_boxes.append(b)
            kept_scores.append(s)
            continue
        aspect = max(w, h) / min_dim
        if aspect <= max_aspect:
            kept_boxes.append(b)
            kept_scores.append(s)
    return (
        kept_boxes,
        kept_scores,
        {"removed": len(boxes) - len(kept_boxes)},
    )


def apply_detection_postprocess(
    boxes: list,
    scores: list,
    *,
    extra_outlier_filter: bool = False,
    filter_outliers_fn=None,
    was_tiled: bool = False,
) -> tuple[list, list, dict]:
    """Server post-processing pipeline; returns ``(boxes, scores, report)``.

    ``boxes``/``scores`` are assumed ALREADY NMS-filtered by ``detect.py``.
    The real pre-NMS / post-NMS counts are injected by ``detect.py`` into the
    returned report (``raw``, ``after_nms``, ``removed_by_nms``, ``tiling_used``).
    """
    raw = len(boxes)
    after_nms = len(boxes)
    removed_by_nms = 0

    # 3. area / box-size filter — record median of areas going into this step.
    if len(boxes) >= 3:
        areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
        sorted_areas = sorted(areas)
        median_area: float | None = float(sorted_areas[len(sorted_areas) // 2])
    else:
        median_area = None

    if _should_apply_strict_box_filter(boxes):
        boxes, scores = filter_box_size(boxes, scores)
    else:
        boxes, scores = _filter_loose(boxes, scores)
    after_area_filter = len(boxes)
    removed_by_area = after_nms - after_area_filter

    # 4. centroid dedup via nearest-neighbour median.
    boxes, scores, merge_meta = merge_by_median_nn(boxes, scores)
    after_centroid_dedup = len(boxes)
    merged_by_centroid_dedup = merge_meta["merged"]
    median_nn_distance = merge_meta["median_nn"]

    # 5. intersection-over-smaller NMS — tiling only.
    if was_tiled and len(boxes) > 0:
        keep = nms_ios(boxes, scores)
        boxes = [boxes[i] for i in keep]
        scores = [scores[i] for i in keep]
        after_ios_nms = len(boxes)
        removed_by_ios_nms = after_centroid_dedup - after_ios_nms
    else:
        after_ios_nms = after_centroid_dedup
        removed_by_ios_nms = 0

    # 6. aspect-ratio shape filter (final).
    boxes, scores, _shape_meta = filter_end_on_shape(boxes, scores)
    after_aspect_filter = len(boxes)
    removed_by_aspect = after_ios_nms - after_aspect_filter

    # 7. (optional) extra outlier filter — very last step.
    if extra_outlier_filter and filter_outliers_fn and boxes:
        keep = filter_outliers_fn(boxes)
        boxes = [boxes[i] for i in keep]
        scores = [scores[i] for i in keep]

    report = {
        "raw": raw,
        "after_nms": after_nms,
        "after_area_filter": after_area_filter,
        "after_centroid_dedup": after_centroid_dedup,
        "after_ios_nms": after_ios_nms,
        "after_aspect_filter": after_aspect_filter,
        "removed_by_nms": removed_by_nms,
        "removed_by_area": removed_by_area,
        "merged_by_centroid_dedup": merged_by_centroid_dedup,
        "removed_by_ios_nms": removed_by_ios_nms,
        "removed_by_aspect": removed_by_aspect,
        "median_nn_distance": median_nn_distance,
        "median_area": median_area,
        "tiling_used": was_tiled,
    }
    return boxes, scores, report