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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference miner for `manak0/Detect-crime`.
|
| 3 |
+
|
| 4 |
+
Beats the published king (`manak0/Detect-crime` baseline, score 0.576) by:
|
| 5 |
+
|
| 6 |
+
1. Letterboxed input at 1280 (king stretch-resizes to 640, destroying small objects).
|
| 7 |
+
2. Per-class confidence floors for the four catastrophic classes
|
| 8 |
+
(balaclava, bat, glove, spray paint each had recall < 0.16 in the king's benchmark).
|
| 9 |
+
3. Multi-scale TTA: {1280, 1536} x {orig, hflip} with class-aware Weighted Box Fusion.
|
| 10 |
+
4. CLAHE on dark frames only (luma gate). CCTV crime footage is heavily night-time.
|
| 11 |
+
5. Class-aware NMS at IoU=0.45 (king is class-agnostic, suppresses balaclava-on-hoodie
|
| 12 |
+
and glove-near-bat overlaps).
|
| 13 |
+
6. Robust ONNX output decoding for both raw YOLO `[1, 4+nc, N]` (king's export) and
|
| 14 |
+
NMS-baked `[N, 6]` / `[1, N, 6]` (our export) formats.
|
| 15 |
+
|
| 16 |
+
Self-contained: only stdlib + pip packages (cv2, numpy, onnxruntime, pydantic). No imports
|
| 17 |
+
from sibling files in the HF repo (chute import sandbox blocks those).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
import math
|
| 22 |
+
|
| 23 |
+
import cv2
|
| 24 |
+
import numpy as np
|
| 25 |
+
import onnxruntime as ort
|
| 26 |
+
from numpy import ndarray
|
| 27 |
+
from pydantic import BaseModel
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class BoundingBox(BaseModel):
|
| 31 |
+
x1: int
|
| 32 |
+
y1: int
|
| 33 |
+
x2: int
|
| 34 |
+
y2: int
|
| 35 |
+
cls_id: int
|
| 36 |
+
conf: float
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TVFrameResult(BaseModel):
|
| 40 |
+
frame_id: int
|
| 41 |
+
boxes: list[BoundingBox]
|
| 42 |
+
keypoints: list[tuple[int, int]]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
TARGET_CLASS_NAMES = ["balaclava", "bat", "glove", "graffiti", "hoodie", "spray paint"]
|
| 46 |
+
|
| 47 |
+
# Per-class confidence floors. King uses one global 0.25; that over-suppresses the four
|
| 48 |
+
# rare classes. Synthetic-benchmark recalls were balaclava 0.034, glove 0.064, spray
|
| 49 |
+
# paint 0.16, bat 0.14 — recall is the bottleneck. With ~6.5 preds/img on average we
|
| 50 |
+
# have headroom under any FFPI cap to push the floors lower without saturating FPs.
|
| 51 |
+
PER_CLASS_CONF = {
|
| 52 |
+
0: 0.05, # balaclava - rec 0.034: catastrophic; pushed hard
|
| 53 |
+
1: 0.10, # bat - rec 0.143
|
| 54 |
+
2: 0.05, # glove - rec 0.064: catastrophic; pushed hard
|
| 55 |
+
3: 0.20, # graffiti - rec 0.321 (best of the rare four); be conservative
|
| 56 |
+
4: 0.20, # hoodie - rec 0.274 + carries the IoU mean alone
|
| 57 |
+
5: 0.10, # spray paint - rec 0.161
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
# Multi-scale TTA. Pro_6000 + YOLOv11s at 1536 is ~150ms; ample budget under p95=10s.
|
| 61 |
+
TTA_SIZES = (1280, 1536)
|
| 62 |
+
TTA_HFLIP = True
|
| 63 |
+
|
| 64 |
+
# Class-aware NMS / fusion thresholds.
|
| 65 |
+
NMS_IOU = 0.45
|
| 66 |
+
WBF_IOU = 0.55
|
| 67 |
+
MAX_DET = 100
|
| 68 |
+
|
| 69 |
+
# CLAHE on dark frames only (CCTV night).
|
| 70 |
+
CLAHE_DARK_THRESHOLD = 70 # mean Y < this -> apply CLAHE
|
| 71 |
+
CLAHE_CLIP_LIMIT = 2.0
|
| 72 |
+
CLAHE_TILE = (8, 8)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Miner:
|
| 76 |
+
def __init__(self, path_hf_repo: Path) -> None:
|
| 77 |
+
model_path = path_hf_repo / "weights.onnx"
|
| 78 |
+
cn_path = model_path.with_name("class_names.txt")
|
| 79 |
+
|
| 80 |
+
self.class_names = TARGET_CLASS_NAMES.copy()
|
| 81 |
+
if cn_path.is_file():
|
| 82 |
+
lines = cn_path.read_text(encoding="utf-8").splitlines()
|
| 83 |
+
order = [ln.strip() for ln in lines if ln.strip() and not ln.strip().startswith("#")]
|
| 84 |
+
if len(order) == len(self.class_names) and set(order) == set(self.class_names):
|
| 85 |
+
self.cls_remap = np.array(
|
| 86 |
+
[self.class_names.index(n) for n in order], dtype=np.int32
|
| 87 |
+
)
|
| 88 |
+
else:
|
| 89 |
+
self.cls_remap = np.arange(len(self.class_names), dtype=np.int32)
|
| 90 |
+
else:
|
| 91 |
+
self.cls_remap = np.arange(len(self.class_names), dtype=np.int32)
|
| 92 |
+
|
| 93 |
+
sess_options = ort.SessionOptions()
|
| 94 |
+
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 95 |
+
try:
|
| 96 |
+
self.session = ort.InferenceSession(
|
| 97 |
+
str(model_path),
|
| 98 |
+
sess_options=sess_options,
|
| 99 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 100 |
+
)
|
| 101 |
+
except Exception:
|
| 102 |
+
self.session = ort.InferenceSession(
|
| 103 |
+
str(model_path),
|
| 104 |
+
sess_options=sess_options,
|
| 105 |
+
providers=["CPUExecutionProvider"],
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
self.input_name = self.session.get_inputs()[0].name
|
| 109 |
+
self.output_names = [o.name for o in self.session.get_outputs()]
|
| 110 |
+
in_shape = self.session.get_inputs()[0].shape
|
| 111 |
+
self.native_h = in_shape[2] if isinstance(in_shape[2], int) and in_shape[2] > 0 else TTA_SIZES[0]
|
| 112 |
+
self.native_w = in_shape[3] if isinstance(in_shape[3], int) and in_shape[3] > 0 else TTA_SIZES[0]
|
| 113 |
+
self.is_dynamic_input = not (
|
| 114 |
+
isinstance(in_shape[2], int) and isinstance(in_shape[3], int)
|
| 115 |
+
and in_shape[2] > 0 and in_shape[3] > 0
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# If export is static-shape, force a single TTA size matching the model.
|
| 119 |
+
if not self.is_dynamic_input:
|
| 120 |
+
self._tta_sizes = (self.native_h,)
|
| 121 |
+
else:
|
| 122 |
+
self._tta_sizes = TTA_SIZES
|
| 123 |
+
|
| 124 |
+
self._clahe = cv2.createCLAHE(clipLimit=CLAHE_CLIP_LIMIT, tileGridSize=CLAHE_TILE)
|
| 125 |
+
|
| 126 |
+
print(f"[miner] model={model_path.name} input={self.native_w}x{self.native_h} dynamic={self.is_dynamic_input}")
|
| 127 |
+
print(f"[miner] tta_sizes={self._tta_sizes} hflip={TTA_HFLIP} per_class_conf={PER_CLASS_CONF}")
|
| 128 |
+
print(f"[miner] providers={self.session.get_providers()}")
|
| 129 |
+
|
| 130 |
+
def __repr__(self) -> str:
|
| 131 |
+
return f"CrimeMiner(providers={self.session.get_providers()})"
|
| 132 |
+
|
| 133 |
+
# ------------------------------------------------------------------ utils
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def _letterbox(image: ndarray, new_size: int, color=(114, 114, 114)) -> tuple[ndarray, float, tuple[float, float]]:
|
| 137 |
+
h, w = image.shape[:2]
|
| 138 |
+
ratio = min(new_size / w, new_size / h)
|
| 139 |
+
rw, rh = int(round(w * ratio)), int(round(h * ratio))
|
| 140 |
+
if (rw, rh) != (w, h):
|
| 141 |
+
interp = cv2.INTER_AREA if ratio < 1.0 else cv2.INTER_LINEAR
|
| 142 |
+
image = cv2.resize(image, (rw, rh), interpolation=interp)
|
| 143 |
+
dw, dh = (new_size - rw) / 2.0, (new_size - rh) / 2.0
|
| 144 |
+
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
|
| 145 |
+
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
|
| 146 |
+
padded = cv2.copyMakeBorder(image, top, bottom, left, right, borderType=cv2.BORDER_CONSTANT, value=color)
|
| 147 |
+
return padded, ratio, (dw, dh)
|
| 148 |
+
|
| 149 |
+
def _maybe_clahe(self, image_bgr: ndarray) -> ndarray:
|
| 150 |
+
small = cv2.resize(image_bgr, (160, 90), interpolation=cv2.INTER_AREA)
|
| 151 |
+
mean_y = float(0.114 * small[..., 0].mean() + 0.587 * small[..., 1].mean() + 0.299 * small[..., 2].mean())
|
| 152 |
+
if mean_y >= CLAHE_DARK_THRESHOLD:
|
| 153 |
+
return image_bgr
|
| 154 |
+
lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2LAB)
|
| 155 |
+
lab[..., 0] = self._clahe.apply(lab[..., 0])
|
| 156 |
+
return cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
|
| 157 |
+
|
| 158 |
+
@staticmethod
|
| 159 |
+
def _xywh_to_xyxy(b: np.ndarray) -> np.ndarray:
|
| 160 |
+
out = np.empty_like(b)
|
| 161 |
+
out[:, 0] = b[:, 0] - b[:, 2] / 2.0
|
| 162 |
+
out[:, 1] = b[:, 1] - b[:, 3] / 2.0
|
| 163 |
+
out[:, 2] = b[:, 0] + b[:, 2] / 2.0
|
| 164 |
+
out[:, 3] = b[:, 1] + b[:, 3] / 2.0
|
| 165 |
+
return out
|
| 166 |
+
|
| 167 |
+
# ------------------------------------------------------------------ ONNX
|
| 168 |
+
|
| 169 |
+
def _preprocess(self, image_bgr: ndarray, size: int) -> tuple[np.ndarray, float, tuple[float, float]]:
|
| 170 |
+
img, ratio, pad = self._letterbox(image_bgr, size)
|
| 171 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 172 |
+
img = img.astype(np.float32) / 255.0
|
| 173 |
+
img = np.transpose(img, (2, 0, 1))[None, ...]
|
| 174 |
+
return np.ascontiguousarray(img, dtype=np.float32), ratio, pad
|
| 175 |
+
|
| 176 |
+
def _run_session(self, image_bgr: ndarray, size: int, hflip: bool):
|
| 177 |
+
if hflip:
|
| 178 |
+
image_bgr = cv2.flip(image_bgr, 1)
|
| 179 |
+
tensor, ratio, pad = self._preprocess(image_bgr, size)
|
| 180 |
+
outputs = self.session.run(self.output_names, {self.input_name: tensor})
|
| 181 |
+
return outputs[0], ratio, pad
|
| 182 |
+
|
| 183 |
+
# ------------------------------------------------------------------ decode
|
| 184 |
+
|
| 185 |
+
def _decode(self, output: np.ndarray, ratio: float, pad: tuple[float, float],
|
| 186 |
+
orig_w: int, orig_h: int, hflip: bool) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 187 |
+
"""Return (boxes_xyxy in orig-image coords, scores, cls_ids)."""
|
| 188 |
+
# Case A: NMS-baked [N, 6] or [1, N, 6]
|
| 189 |
+
if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] == 6:
|
| 190 |
+
preds = output[0]
|
| 191 |
+
elif output.ndim == 2 and output.shape[1] == 6:
|
| 192 |
+
preds = output
|
| 193 |
+
else:
|
| 194 |
+
return self._decode_raw(output, ratio, pad, orig_w, orig_h, hflip)
|
| 195 |
+
|
| 196 |
+
boxes = preds[:, :4].astype(np.float32, copy=True)
|
| 197 |
+
scores = preds[:, 4].astype(np.float32)
|
| 198 |
+
cls_ids = preds[:, 5].astype(np.int32)
|
| 199 |
+
cls_ids = self.cls_remap[np.clip(cls_ids, 0, len(self.cls_remap) - 1)]
|
| 200 |
+
|
| 201 |
+
keep = (scores > 0.0) & (boxes[:, 2] > boxes[:, 0]) & (boxes[:, 3] > boxes[:, 1])
|
| 202 |
+
boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
|
| 203 |
+
if len(boxes) == 0:
|
| 204 |
+
return boxes, scores, cls_ids
|
| 205 |
+
|
| 206 |
+
return self._unletterbox(boxes, scores, cls_ids, ratio, pad, orig_w, orig_h, hflip)
|
| 207 |
+
|
| 208 |
+
def _decode_raw(self, output: np.ndarray, ratio: float, pad: tuple[float, float],
|
| 209 |
+
orig_w: int, orig_h: int, hflip: bool) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 210 |
+
# Raw ultralytics export: [1, C, N] where C = 4 + num_classes (king's case: [1, 10, 8400]).
|
| 211 |
+
if output.ndim != 3 or output.shape[0] != 1:
|
| 212 |
+
return np.zeros((0, 4), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32)
|
| 213 |
+
preds = output[0]
|
| 214 |
+
# Normalize to [N, C].
|
| 215 |
+
if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
|
| 216 |
+
preds = preds.T
|
| 217 |
+
if preds.shape[1] < 5:
|
| 218 |
+
return np.zeros((0, 4), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32)
|
| 219 |
+
|
| 220 |
+
boxes_xywh = preds[:, :4].astype(np.float32)
|
| 221 |
+
cls_part = preds[:, 4:].astype(np.float32)
|
| 222 |
+
if cls_part.shape[1] == 1:
|
| 223 |
+
scores = cls_part[:, 0]
|
| 224 |
+
cls_ids = np.zeros(len(scores), dtype=np.int32)
|
| 225 |
+
else:
|
| 226 |
+
cls_ids = np.argmax(cls_part, axis=1).astype(np.int32)
|
| 227 |
+
scores = cls_part[np.arange(len(cls_part)), cls_ids]
|
| 228 |
+
cls_ids = self.cls_remap[np.clip(cls_ids, 0, len(self.cls_remap) - 1)]
|
| 229 |
+
|
| 230 |
+
# Coarse pre-filter: any class above its own floor (or at least 0.03 to keep the path
|
| 231 |
+
# light for the four catastrophic classes).
|
| 232 |
+
floors = np.array([PER_CLASS_CONF.get(int(c), 0.20) for c in cls_ids], dtype=np.float32)
|
| 233 |
+
keep = scores >= np.minimum(floors, 0.03)
|
| 234 |
+
if not np.any(keep):
|
| 235 |
+
return np.zeros((0, 4), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32)
|
| 236 |
+
boxes_xywh = boxes_xywh[keep]
|
| 237 |
+
scores = scores[keep]
|
| 238 |
+
cls_ids = cls_ids[keep]
|
| 239 |
+
|
| 240 |
+
boxes = self._xywh_to_xyxy(boxes_xywh)
|
| 241 |
+
return self._unletterbox(boxes, scores, cls_ids, ratio, pad, orig_w, orig_h, hflip)
|
| 242 |
+
|
| 243 |
+
@staticmethod
|
| 244 |
+
def _unletterbox(boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray,
|
| 245 |
+
ratio: float, pad: tuple[float, float], orig_w: int, orig_h: int,
|
| 246 |
+
hflip: bool) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 247 |
+
boxes = boxes.copy()
|
| 248 |
+
boxes[:, [0, 2]] -= pad[0]
|
| 249 |
+
boxes[:, [1, 3]] -= pad[1]
|
| 250 |
+
boxes /= ratio
|
| 251 |
+
if hflip:
|
| 252 |
+
x1 = orig_w - 1 - boxes[:, 2]
|
| 253 |
+
x2 = orig_w - 1 - boxes[:, 0]
|
| 254 |
+
boxes[:, 0] = x1
|
| 255 |
+
boxes[:, 2] = x2
|
| 256 |
+
boxes[:, 0] = np.clip(boxes[:, 0], 0, orig_w - 1)
|
| 257 |
+
boxes[:, 1] = np.clip(boxes[:, 1], 0, orig_h - 1)
|
| 258 |
+
boxes[:, 2] = np.clip(boxes[:, 2], 0, orig_w - 1)
|
| 259 |
+
boxes[:, 3] = np.clip(boxes[:, 3], 0, orig_h - 1)
|
| 260 |
+
return boxes, scores, cls_ids
|
| 261 |
+
|
| 262 |
+
# ------------------------------------------------------------------ fusion
|
| 263 |
+
|
| 264 |
+
@staticmethod
|
| 265 |
+
def _iou_matrix(a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
| 266 |
+
if len(a) == 0 or len(b) == 0:
|
| 267 |
+
return np.zeros((len(a), len(b)), dtype=np.float32)
|
| 268 |
+
a = a.astype(np.float32)
|
| 269 |
+
b = b.astype(np.float32)
|
| 270 |
+
x11, y11, x12, y12 = a[:, 0:1], a[:, 1:2], a[:, 2:3], a[:, 3:4]
|
| 271 |
+
x21, y21, x22, y22 = b[:, 0], b[:, 1], b[:, 2], b[:, 3]
|
| 272 |
+
xa = np.maximum(x11, x21); ya = np.maximum(y11, y21)
|
| 273 |
+
xb = np.minimum(x12, x22); yb = np.minimum(y12, y22)
|
| 274 |
+
inter = np.maximum(0.0, xb - xa) * np.maximum(0.0, yb - ya)
|
| 275 |
+
area_a = (x12 - x11) * (y12 - y11)
|
| 276 |
+
area_b = (x22 - x21) * (y22 - y21)
|
| 277 |
+
return inter / (area_a + area_b - inter + 1e-7)
|
| 278 |
+
|
| 279 |
+
def _wbf(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray,
|
| 280 |
+
iou_thresh: float = WBF_IOU) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 281 |
+
"""Class-aware Weighted Box Fusion: inside each class cluster, kept box is the
|
| 282 |
+
score-weighted average; cluster score is max member score (preserves AP rank).
|
| 283 |
+
"""
|
| 284 |
+
if len(boxes) == 0:
|
| 285 |
+
return boxes, scores, cls_ids
|
| 286 |
+
|
| 287 |
+
out_boxes, out_scores, out_cls = [], [], []
|
| 288 |
+
for c in np.unique(cls_ids):
|
| 289 |
+
mask = cls_ids == c
|
| 290 |
+
cb = boxes[mask].astype(np.float32)
|
| 291 |
+
cs = scores[mask].astype(np.float32)
|
| 292 |
+
order = np.argsort(-cs)
|
| 293 |
+
cb = cb[order]
|
| 294 |
+
cs = cs[order]
|
| 295 |
+
used = np.zeros(len(cb), dtype=bool)
|
| 296 |
+
for i in range(len(cb)):
|
| 297 |
+
if used[i]:
|
| 298 |
+
continue
|
| 299 |
+
base = cb[i:i + 1]
|
| 300 |
+
ious = self._iou_matrix(base, cb)[0]
|
| 301 |
+
cluster = (ious >= iou_thresh) & (~used)
|
| 302 |
+
cluster[i] = True
|
| 303 |
+
w = cs[cluster]
|
| 304 |
+
wsum = float(w.sum()) + 1e-7
|
| 305 |
+
fused = (cb[cluster] * w[:, None]).sum(axis=0) / wsum
|
| 306 |
+
out_boxes.append(fused)
|
| 307 |
+
out_scores.append(float(cs[cluster].max()))
|
| 308 |
+
out_cls.append(int(c))
|
| 309 |
+
used = used | cluster
|
| 310 |
+
return (np.stack(out_boxes), np.array(out_scores, dtype=np.float32),
|
| 311 |
+
np.array(out_cls, dtype=np.int32))
|
| 312 |
+
|
| 313 |
+
def _class_aware_nms(self, boxes: np.ndarray, scores: np.ndarray, cls_ids: np.ndarray,
|
| 314 |
+
iou_thresh: float = NMS_IOU) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 315 |
+
if len(boxes) == 0:
|
| 316 |
+
return boxes, scores, cls_ids
|
| 317 |
+
kept_b, kept_s, kept_c = [], [], []
|
| 318 |
+
for c in np.unique(cls_ids):
|
| 319 |
+
mask = cls_ids == c
|
| 320 |
+
cb = boxes[mask].astype(np.float32)
|
| 321 |
+
cs = scores[mask].astype(np.float32)
|
| 322 |
+
order = np.argsort(-cs)
|
| 323 |
+
suppressed = np.zeros(len(cb), dtype=bool)
|
| 324 |
+
for i in order:
|
| 325 |
+
if suppressed[i]:
|
| 326 |
+
continue
|
| 327 |
+
kept_b.append(cb[i])
|
| 328 |
+
kept_s.append(float(cs[i]))
|
| 329 |
+
kept_c.append(int(c))
|
| 330 |
+
ious = self._iou_matrix(cb[i:i + 1], cb)[0]
|
| 331 |
+
suppressed = suppressed | (ious >= iou_thresh)
|
| 332 |
+
suppressed[i] = True
|
| 333 |
+
if not kept_b:
|
| 334 |
+
return np.zeros((0, 4), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32)
|
| 335 |
+
return np.stack(kept_b), np.array(kept_s, dtype=np.float32), np.array(kept_c, dtype=np.int32)
|
| 336 |
+
|
| 337 |
+
# ------------------------------------------------------------------ predict
|
| 338 |
+
|
| 339 |
+
def _predict_one(self, image_bgr: ndarray) -> list[BoundingBox]:
|
| 340 |
+
h, w = image_bgr.shape[:2]
|
| 341 |
+
enhanced = self._maybe_clahe(image_bgr)
|
| 342 |
+
|
| 343 |
+
all_boxes, all_scores, all_cls = [], [], []
|
| 344 |
+
for size in self._tta_sizes:
|
| 345 |
+
for hflip in ((False, True) if TTA_HFLIP else (False,)):
|
| 346 |
+
output, ratio, pad = self._run_session(enhanced, size, hflip)
|
| 347 |
+
boxes, scores, cls_ids = self._decode(output, ratio, pad, w, h, hflip)
|
| 348 |
+
if len(boxes):
|
| 349 |
+
all_boxes.append(boxes)
|
| 350 |
+
all_scores.append(scores)
|
| 351 |
+
all_cls.append(cls_ids)
|
| 352 |
+
|
| 353 |
+
if not all_boxes:
|
| 354 |
+
return []
|
| 355 |
+
|
| 356 |
+
boxes = np.concatenate(all_boxes, axis=0)
|
| 357 |
+
scores = np.concatenate(all_scores, axis=0)
|
| 358 |
+
cls_ids = np.concatenate(all_cls, axis=0)
|
| 359 |
+
|
| 360 |
+
# Per-class confidence floor.
|
| 361 |
+
floors = np.array([PER_CLASS_CONF.get(int(c), 0.20) for c in cls_ids], dtype=np.float32)
|
| 362 |
+
keep = scores >= floors
|
| 363 |
+
boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
|
| 364 |
+
if len(boxes) == 0:
|
| 365 |
+
return []
|
| 366 |
+
|
| 367 |
+
# Fuse across TTA streams (class-aware WBF), then class-aware NMS to clean up.
|
| 368 |
+
boxes, scores, cls_ids = self._wbf(boxes, scores, cls_ids, iou_thresh=WBF_IOU)
|
| 369 |
+
boxes, scores, cls_ids = self._class_aware_nms(boxes, scores, cls_ids, iou_thresh=NMS_IOU)
|
| 370 |
+
|
| 371 |
+
if len(boxes) > MAX_DET:
|
| 372 |
+
order = np.argsort(-scores)[:MAX_DET]
|
| 373 |
+
boxes, scores, cls_ids = boxes[order], scores[order], cls_ids[order]
|
| 374 |
+
|
| 375 |
+
results: list[BoundingBox] = []
|
| 376 |
+
for box, conf, cid in zip(boxes, scores, cls_ids):
|
| 377 |
+
x1, y1, x2, y2 = box.tolist()
|
| 378 |
+
if x2 <= x1 or y2 <= y1:
|
| 379 |
+
continue
|
| 380 |
+
results.append(BoundingBox(
|
| 381 |
+
x1=int(math.floor(x1)),
|
| 382 |
+
y1=int(math.floor(y1)),
|
| 383 |
+
x2=int(math.ceil(x2)),
|
| 384 |
+
y2=int(math.ceil(y2)),
|
| 385 |
+
cls_id=int(cid),
|
| 386 |
+
conf=float(np.clip(conf, 0.0, 1.0)),
|
| 387 |
+
))
|
| 388 |
+
return results
|
| 389 |
+
|
| 390 |
+
def predict_batch(
|
| 391 |
+
self,
|
| 392 |
+
batch_images: list[ndarray],
|
| 393 |
+
offset: int,
|
| 394 |
+
n_keypoints: int,
|
| 395 |
+
) -> list[TVFrameResult]:
|
| 396 |
+
results: list[TVFrameResult] = []
|
| 397 |
+
for i, image in enumerate(batch_images):
|
| 398 |
+
try:
|
| 399 |
+
boxes = self._predict_one(image)
|
| 400 |
+
except Exception as e:
|
| 401 |
+
print(f"[miner] inference failed on frame {offset + i}: {e}")
|
| 402 |
+
boxes = []
|
| 403 |
+
results.append(TVFrameResult(
|
| 404 |
+
frame_id=offset + i,
|
| 405 |
+
boxes=boxes,
|
| 406 |
+
keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
|
| 407 |
+
))
|
| 408 |
+
return results
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
if __name__ == "__main__":
|
| 412 |
+
# Smoke test against any image in /tmp/crime_proof.png or weights.onnx-adjacent test.png.
|
| 413 |
+
import sys
|
| 414 |
+
repo_dir = Path(__file__).parent
|
| 415 |
+
miner = Miner(repo_dir)
|
| 416 |
+
candidates = [Path("/tmp/crime_proof.png"), repo_dir / "test.png"]
|
| 417 |
+
img_path = next((p for p in candidates if p.exists()), None)
|
| 418 |
+
if img_path is None:
|
| 419 |
+
print("no test image found; place one at /tmp/crime_proof.png and rerun")
|
| 420 |
+
sys.exit(0)
|
| 421 |
+
img = cv2.imread(str(img_path), cv2.IMREAD_COLOR)
|
| 422 |
+
out = miner.predict_batch([img], offset=0, n_keypoints=0)
|
| 423 |
+
for f in out:
|
| 424 |
+
print(f"frame {f.frame_id}: {len(f.boxes)} boxes")
|
| 425 |
+
for b in f.boxes:
|
| 426 |
+
print(f" cls={b.cls_id} ({TARGET_CLASS_NAMES[b.cls_id]}) conf={b.conf:.3f} "
|
| 427 |
+
f"box=({b.x1},{b.y1},{b.x2},{b.y2})")
|