Spaces:
Sleeping
Sleeping
Download postprocess.py from bankba/pipe-counter: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/bankba/pipe-counter/resolve/main/postprocess.py
- Command line
-
hf download hf://spaces/bankba/pipe-counter/postprocess.py
-
curl -L -o postprocess.py https://huggingface.co/spaces/bankba/pipe-counter/resolve/main/postprocess.py
10.1 kB
| """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. | |
| Replaces the old size-ratio ``merge_center_clusters`` behaviour. Boxes whose | |
| centroid is within ``CENTROID_MERGE_NN_FACTOR * median_nn`` of an already | |
| kept (higher-score) box are treated as duplicates and dropped. | |
| """ | |
| import numpy as np | |
| if len(boxes) < 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) | |
| # Pairwise squared distances (O(n^2); fine for server pipeline sizes). | |
| diff = centroids[:, None, :] - centroids[None, :, :] | |
| dist2 = np.sum(diff * diff, axis=2) | |
| np.fill_diagonal(dist2, np.inf) | |
| nn = np.sqrt(np.min(dist2, axis=1)) | |
| median_nn = float(np.median(nn)) | |
| merge_threshold = CENTROID_MERGE_NN_FACTOR * median_nn | |
| thresh2 = merge_threshold * merge_threshold | |
| n = len(boxes) | |
| order = sorted(range(n), key=lambda i: scores[i], reverse=True) | |
| kept_idx: list[int] = [] | |
| kept_centroids: list = [] | |
| for i in order: | |
| ci = centroids[i] | |
| duplicate = False | |
| for kc in kept_centroids: | |
| dx = ci[0] - kc[0] | |
| dy = ci[1] - kc[1] | |
| if dx * dx + dy * dy < thresh2: | |
| duplicate = True | |
| break | |
| if not duplicate: | |
| kept_idx.append(i) | |
| kept_centroids.append(ci) | |
| 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 | |