scorevision: push artifact
Browse files
miner.py
CHANGED
|
@@ -23,42 +23,22 @@ class TVFrameResult(BaseModel):
|
|
| 23 |
keypoints: list[tuple[int, int]]
|
| 24 |
|
| 25 |
|
| 26 |
-
SIZE = 1280
|
| 27 |
-
|
| 28 |
-
|
| 29 |
class Miner:
|
| 30 |
-
def __init__(self,
|
|
|
|
|
|
|
| 31 |
model_path = path_hf_repo / "weights.onnx"
|
| 32 |
-
|
| 33 |
-
if cn_path.is_file():
|
| 34 |
-
lines = cn_path.read_text(encoding="utf-8").splitlines()
|
| 35 |
-
self.class_names = [
|
| 36 |
-
ln.strip()
|
| 37 |
-
for ln in lines
|
| 38 |
-
if ln.strip() and not ln.strip().startswith("#")
|
| 39 |
-
]
|
| 40 |
-
else:
|
| 41 |
-
self.class_names = ["numberplate"]
|
| 42 |
print("ORT version:", ort.__version__)
|
| 43 |
|
| 44 |
try:
|
| 45 |
ort.preload_dlls()
|
| 46 |
-
print("onnxruntime.preload_dlls() success")
|
| 47 |
except Exception as e:
|
| 48 |
-
print(f"preload_dlls failed: {e}")
|
| 49 |
|
| 50 |
print("ORT available providers BEFORE session:", ort.get_available_providers())
|
| 51 |
|
| 52 |
-
try:
|
| 53 |
-
import torch
|
| 54 |
-
if torch.cuda.is_available():
|
| 55 |
-
print(f"GPU: {torch.cuda.get_device_name(0)}")
|
| 56 |
-
print(f"GPU memory: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB")
|
| 57 |
-
else:
|
| 58 |
-
print("GPU: CUDA not available via torch")
|
| 59 |
-
except Exception as e:
|
| 60 |
-
print(f"GPU detection failed: {e}")
|
| 61 |
-
|
| 62 |
sess_options = ort.SessionOptions()
|
| 63 |
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 64 |
|
|
@@ -68,9 +48,9 @@ class Miner:
|
|
| 68 |
sess_options=sess_options,
|
| 69 |
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 70 |
)
|
| 71 |
-
print("Created ORT session with preferred CUDA provider list")
|
| 72 |
except Exception as e:
|
| 73 |
-
print(f"CUDA session creation failed, falling back to CPU: {e}")
|
| 74 |
self.session = ort.InferenceSession(
|
| 75 |
str(model_path),
|
| 76 |
sess_options=sess_options,
|
|
@@ -81,35 +61,43 @@ class Miner:
|
|
| 81 |
|
| 82 |
for inp in self.session.get_inputs():
|
| 83 |
print("INPUT:", inp.name, inp.shape, inp.type)
|
|
|
|
| 84 |
for out in self.session.get_outputs():
|
| 85 |
print("OUTPUT:", out.name, out.shape, out.type)
|
| 86 |
|
| 87 |
self.input_name = self.session.get_inputs()[0].name
|
| 88 |
-
self.output_names = [
|
| 89 |
self.input_shape = self.session.get_inputs()[0].shape
|
| 90 |
|
| 91 |
-
self.input_height = self._safe_dim(self.input_shape[2], default=
|
| 92 |
-
self.input_width = self._safe_dim(self.input_shape[3], default=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
#
|
| 95 |
-
self.
|
| 96 |
-
self.iou_thres = 0.66
|
| 97 |
-
self.sigma = 0.465
|
| 98 |
-
self.max_det = 300
|
| 99 |
|
| 100 |
-
#
|
| 101 |
-
self.
|
| 102 |
-
self.tile_conf = 0.57
|
| 103 |
-
self.tile_overlap = 0.20
|
| 104 |
-
self.novelty_iou = 0.10
|
| 105 |
-
self.final_max_det = 17
|
| 106 |
-
self.tile_use_hflip = False # skip hflip tile pass to save ~4 forwards
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
self.use_tta = True
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
def __repr__(self) -> str:
|
| 115 |
return (
|
|
@@ -121,7 +109,6 @@ class Miner:
|
|
| 121 |
def _safe_dim(value, default: int) -> int:
|
| 122 |
return value if isinstance(value, int) and value > 0 else default
|
| 123 |
|
| 124 |
-
# ---------- image preprocessing ----------
|
| 125 |
def _letterbox(
|
| 126 |
self,
|
| 127 |
image: ndarray,
|
|
@@ -130,29 +117,50 @@ class Miner:
|
|
| 130 |
) -> tuple[ndarray, float, tuple[float, float]]:
|
| 131 |
h, w = image.shape[:2]
|
| 132 |
new_w, new_h = new_shape
|
|
|
|
| 133 |
ratio = min(new_w / w, new_h / h)
|
| 134 |
resized_w = int(round(w * ratio))
|
| 135 |
resized_h = int(round(h * ratio))
|
|
|
|
| 136 |
if (resized_w, resized_h) != (w, h):
|
| 137 |
interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
|
| 138 |
image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
left = int(round(dw - 0.1))
|
| 142 |
right = int(round(dw + 0.1))
|
| 143 |
top = int(round(dh - 0.1))
|
| 144 |
bottom = int(round(dh + 0.1))
|
|
|
|
| 145 |
padded = cv2.copyMakeBorder(
|
| 146 |
-
image,
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
)
|
| 149 |
return padded, ratio, (dw, dh)
|
| 150 |
|
| 151 |
-
def _preprocess(
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
img = np.transpose(img, (2, 0, 1))[None, ...]
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
|
| 157 |
@staticmethod
|
| 158 |
def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
|
|
@@ -163,244 +171,406 @@ class Miner:
|
|
| 163 |
boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
|
| 164 |
return boxes
|
| 165 |
|
| 166 |
-
# ---------- NMS primitives ----------
|
| 167 |
@staticmethod
|
| 168 |
-
def
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
return np.array([], dtype=np.intp)
|
|
|
|
| 172 |
boxes = np.asarray(boxes, dtype=np.float32)
|
| 173 |
scores = np.asarray(scores, dtype=np.float32)
|
| 174 |
-
order = np.argsort(
|
| 175 |
-
keep
|
| 176 |
-
|
| 177 |
-
|
|
|
|
| 178 |
keep.append(i)
|
| 179 |
if len(order) == 1:
|
| 180 |
break
|
|
|
|
| 181 |
rest = order[1:]
|
|
|
|
| 182 |
xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
|
| 183 |
yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
|
| 184 |
xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
|
| 185 |
yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
|
|
|
|
| 186 |
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 187 |
-
|
| 188 |
-
|
|
|
|
|
|
|
| 189 |
iou = inter / (area_i + area_r - inter + 1e-7)
|
| 190 |
order = rest[iou <= iou_thresh]
|
| 191 |
-
return np.array(keep, dtype=np.intp)
|
| 192 |
|
| 193 |
-
|
| 194 |
-
self,
|
| 195 |
-
boxes: np.ndarray,
|
| 196 |
-
scores: np.ndarray,
|
| 197 |
-
sigma: float,
|
| 198 |
-
score_thresh: float = 0.01,
|
| 199 |
-
) -> tuple[np.ndarray, np.ndarray]:
|
| 200 |
-
N = len(boxes)
|
| 201 |
-
if N == 0:
|
| 202 |
-
return np.array([], dtype=np.intp), np.array([], dtype=np.float32)
|
| 203 |
-
boxes = boxes.astype(np.float32, copy=True)
|
| 204 |
-
scores = scores.astype(np.float32, copy=True)
|
| 205 |
-
order = np.arange(N)
|
| 206 |
-
for i in range(N):
|
| 207 |
-
max_pos = i + int(np.argmax(scores[i:]))
|
| 208 |
-
boxes[[i, max_pos]] = boxes[[max_pos, i]]
|
| 209 |
-
scores[[i, max_pos]] = scores[[max_pos, i]]
|
| 210 |
-
order[[i, max_pos]] = order[[max_pos, i]]
|
| 211 |
-
if i + 1 >= N:
|
| 212 |
-
break
|
| 213 |
-
xx1 = np.maximum(boxes[i, 0], boxes[i + 1:, 0])
|
| 214 |
-
yy1 = np.maximum(boxes[i, 1], boxes[i + 1:, 1])
|
| 215 |
-
xx2 = np.minimum(boxes[i, 2], boxes[i + 1:, 2])
|
| 216 |
-
yy2 = np.minimum(boxes[i, 3], boxes[i + 1:, 3])
|
| 217 |
-
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 218 |
-
area_i = float(
|
| 219 |
-
(boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
|
| 220 |
-
)
|
| 221 |
-
areas_j = (
|
| 222 |
-
np.maximum(0.0, boxes[i + 1:, 2] - boxes[i + 1:, 0])
|
| 223 |
-
* np.maximum(0.0, boxes[i + 1:, 3] - boxes[i + 1:, 1])
|
| 224 |
-
)
|
| 225 |
-
iou = inter / (area_i + areas_j - inter + 1e-7)
|
| 226 |
-
scores[i + 1:] *= np.exp(-(iou ** 2) / sigma)
|
| 227 |
-
mask = scores > score_thresh
|
| 228 |
-
return order[mask], scores[mask]
|
| 229 |
|
| 230 |
@staticmethod
|
| 231 |
def _box_iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:
|
| 232 |
-
if len(boxes) == 0:
|
| 233 |
-
return np.zeros(0, dtype=np.float32)
|
| 234 |
xx1 = np.maximum(box[0], boxes[:, 0])
|
| 235 |
yy1 = np.maximum(box[1], boxes[:, 1])
|
| 236 |
xx2 = np.minimum(box[2], boxes[:, 2])
|
| 237 |
yy2 = np.minimum(box[3], boxes[:, 3])
|
|
|
|
| 238 |
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
|
|
|
| 239 |
area_a = max(0.0, (box[2] - box[0]) * (box[3] - box[1]))
|
| 240 |
area_b = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
|
|
|
|
| 241 |
return inter / (area_a + area_b - inter + 1e-7)
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
if
|
| 251 |
-
return
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
if len(boxes) == 0:
|
| 257 |
-
return
|
| 258 |
-
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
boxes /= ratio
|
| 261 |
-
|
| 262 |
-
boxes = self._clip_boxes(boxes, (ow, oh))
|
| 263 |
-
return np.concatenate([boxes, scores[:, None]], axis=1)
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
return merged
|
| 288 |
-
|
| 289 |
-
# ---------- conditional tile pass ----------
|
| 290 |
-
def _tile_augment(self, image: ndarray, primary: np.ndarray) -> np.ndarray:
|
| 291 |
-
"""Run 2x2 overlapping tiles + hflip, novelty-merge into primary."""
|
| 292 |
-
oh, ow = image.shape[:2]
|
| 293 |
-
tw, th = ow // 2, oh // 2
|
| 294 |
-
ox, oy = int(tw * self.tile_overlap), int(th * self.tile_overlap)
|
| 295 |
-
tiles = [
|
| 296 |
-
(0, 0, min(ow, tw + ox), min(oh, th + oy)),
|
| 297 |
-
(max(0, tw - ox), 0, ow, min(oh, th + oy)),
|
| 298 |
-
(0, max(0, th - oy), min(ow, tw + ox), oh),
|
| 299 |
-
(max(0, tw - ox), max(0, th - oy), ow, oh),
|
| 300 |
]
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
area = w * h
|
| 357 |
-
ar = np.maximum(w / np.maximum(h, 1e-6), h / np.maximum(w, 1e-6))
|
| 358 |
-
img_area = float(ow * oh)
|
| 359 |
-
ok = (w >= 7) & (h >= 7) & (area >= 85) & (area <= 0.5 * img_area) & (ar <= 10.0)
|
| 360 |
-
tile_dets = tile_dets[ok]
|
| 361 |
-
if len(tile_dets) == 0:
|
| 362 |
-
return primary
|
| 363 |
-
|
| 364 |
-
merged = np.concatenate([primary, tile_dets], axis=0)
|
| 365 |
-
keep = self._hard_nms(merged[:, :4], merged[:, 4], self.iou_thres)
|
| 366 |
-
merged = merged[keep]
|
| 367 |
-
if len(merged) > self.final_max_det:
|
| 368 |
-
merged = merged[np.argsort(-merged[:, 4])[: self.final_max_det]]
|
| 369 |
-
return merged
|
| 370 |
-
|
| 371 |
-
# ---------- single-image predict ----------
|
| 372 |
-
def _predict_single(self, image: ndarray) -> list[BoundingBox]:
|
| 373 |
-
if image is None or not isinstance(image, np.ndarray) or image.ndim != 3:
|
| 374 |
return []
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
if image.dtype != np.uint8:
|
| 378 |
image = image.astype(np.uint8)
|
| 379 |
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
continue
|
| 391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
BoundingBox(
|
| 393 |
x1=int(math.floor(x1)),
|
| 394 |
y1=int(math.floor(y1)),
|
| 395 |
x2=int(math.ceil(x2)),
|
| 396 |
y2=int(math.ceil(y2)),
|
| 397 |
cls_id=0,
|
| 398 |
-
conf=float(
|
| 399 |
)
|
| 400 |
)
|
| 401 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
|
| 403 |
-
# ---------- chute entrypoint ----------
|
| 404 |
def predict_batch(
|
| 405 |
self,
|
| 406 |
batch_images: list[ndarray],
|
|
@@ -408,12 +578,17 @@ class Miner:
|
|
| 408 |
n_keypoints: int,
|
| 409 |
) -> list[TVFrameResult]:
|
| 410 |
results: list[TVFrameResult] = []
|
|
|
|
| 411 |
for frame_number_in_batch, image in enumerate(batch_images):
|
| 412 |
try:
|
| 413 |
-
|
|
|
|
|
|
|
|
|
|
| 414 |
except Exception as e:
|
| 415 |
-
print(f"Inference failed for frame {offset + frame_number_in_batch}: {e}")
|
| 416 |
boxes = []
|
|
|
|
| 417 |
results.append(
|
| 418 |
TVFrameResult(
|
| 419 |
frame_id=offset + frame_number_in_batch,
|
|
@@ -421,4 +596,5 @@ class Miner:
|
|
| 421 |
keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
|
| 422 |
)
|
| 423 |
)
|
| 424 |
-
|
|
|
|
|
|
| 23 |
keypoints: list[tuple[int, int]]
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
class Miner:
|
| 27 |
+
def __init__(self,
|
| 28 |
+
path_hf_repo: Path
|
| 29 |
+
) -> None:
|
| 30 |
model_path = path_hf_repo / "weights.onnx"
|
| 31 |
+
self.class_names = ["person"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
print("ORT version:", ort.__version__)
|
| 33 |
|
| 34 |
try:
|
| 35 |
ort.preload_dlls()
|
| 36 |
+
print("✅ onnxruntime.preload_dlls() success")
|
| 37 |
except Exception as e:
|
| 38 |
+
print(f"⚠️ preload_dlls failed: {e}")
|
| 39 |
|
| 40 |
print("ORT available providers BEFORE session:", ort.get_available_providers())
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
sess_options = ort.SessionOptions()
|
| 43 |
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 44 |
|
|
|
|
| 48 |
sess_options=sess_options,
|
| 49 |
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 50 |
)
|
| 51 |
+
print("✅ Created ORT session with preferred CUDA provider list")
|
| 52 |
except Exception as e:
|
| 53 |
+
print(f"⚠️ CUDA session creation failed, falling back to CPU: {e}")
|
| 54 |
self.session = ort.InferenceSession(
|
| 55 |
str(model_path),
|
| 56 |
sess_options=sess_options,
|
|
|
|
| 61 |
|
| 62 |
for inp in self.session.get_inputs():
|
| 63 |
print("INPUT:", inp.name, inp.shape, inp.type)
|
| 64 |
+
|
| 65 |
for out in self.session.get_outputs():
|
| 66 |
print("OUTPUT:", out.name, out.shape, out.type)
|
| 67 |
|
| 68 |
self.input_name = self.session.get_inputs()[0].name
|
| 69 |
+
self.output_names = [output.name for output in self.session.get_outputs()]
|
| 70 |
self.input_shape = self.session.get_inputs()[0].shape
|
| 71 |
|
| 72 |
+
self.input_height = self._safe_dim(self.input_shape[2], default=1280)
|
| 73 |
+
self.input_width = self._safe_dim(self.input_shape[3], default=1280)
|
| 74 |
+
|
| 75 |
+
# ---------- Scoring-oriented thresholds ----------
|
| 76 |
+
# Low threshold for candidate generation
|
| 77 |
+
self.conf_thres = 0.68
|
| 78 |
|
| 79 |
+
# High-confidence boxes can survive without TTA confirmation
|
| 80 |
+
self.conf_high = 0.30
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# NMS threshold
|
| 83 |
+
self.iou_thres = 0.35
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
# TTA confirmation IoU
|
| 86 |
+
self.tta_match_iou = 0.68
|
| 87 |
+
|
| 88 |
+
self.max_det = 150
|
| 89 |
self.use_tta = True
|
| 90 |
|
| 91 |
+
# Box sanity filters
|
| 92 |
+
self.min_box_area = 14 * 14
|
| 93 |
+
self.min_w = 8
|
| 94 |
+
self.min_h = 8
|
| 95 |
+
self.max_aspect_ratio = 8.0
|
| 96 |
+
self.max_box_area_ratio = 0.8
|
| 97 |
+
|
| 98 |
+
print(f"✅ ONNX model loaded from: {model_path}")
|
| 99 |
+
print(f"✅ ONNX providers: {self.session.get_providers()}")
|
| 100 |
+
print(f"✅ ONNX input: name={self.input_name}, shape={self.input_shape}")
|
| 101 |
|
| 102 |
def __repr__(self) -> str:
|
| 103 |
return (
|
|
|
|
| 109 |
def _safe_dim(value, default: int) -> int:
|
| 110 |
return value if isinstance(value, int) and value > 0 else default
|
| 111 |
|
|
|
|
| 112 |
def _letterbox(
|
| 113 |
self,
|
| 114 |
image: ndarray,
|
|
|
|
| 117 |
) -> tuple[ndarray, float, tuple[float, float]]:
|
| 118 |
h, w = image.shape[:2]
|
| 119 |
new_w, new_h = new_shape
|
| 120 |
+
|
| 121 |
ratio = min(new_w / w, new_h / h)
|
| 122 |
resized_w = int(round(w * ratio))
|
| 123 |
resized_h = int(round(h * ratio))
|
| 124 |
+
|
| 125 |
if (resized_w, resized_h) != (w, h):
|
| 126 |
interp = cv2.INTER_CUBIC if ratio > 1.0 else cv2.INTER_LINEAR
|
| 127 |
image = cv2.resize(image, (resized_w, resized_h), interpolation=interp)
|
| 128 |
+
|
| 129 |
+
dw = new_w - resized_w
|
| 130 |
+
dh = new_h - resized_h
|
| 131 |
+
dw /= 2.0
|
| 132 |
+
dh /= 2.0
|
| 133 |
+
|
| 134 |
left = int(round(dw - 0.1))
|
| 135 |
right = int(round(dw + 0.1))
|
| 136 |
top = int(round(dh - 0.1))
|
| 137 |
bottom = int(round(dh + 0.1))
|
| 138 |
+
|
| 139 |
padded = cv2.copyMakeBorder(
|
| 140 |
+
image,
|
| 141 |
+
top,
|
| 142 |
+
bottom,
|
| 143 |
+
left,
|
| 144 |
+
right,
|
| 145 |
+
borderType=cv2.BORDER_CONSTANT,
|
| 146 |
+
value=color,
|
| 147 |
)
|
| 148 |
return padded, ratio, (dw, dh)
|
| 149 |
|
| 150 |
+
def _preprocess(
|
| 151 |
+
self, image: ndarray
|
| 152 |
+
) -> tuple[np.ndarray, float, tuple[float, float], tuple[int, int]]:
|
| 153 |
+
orig_h, orig_w = image.shape[:2]
|
| 154 |
+
|
| 155 |
+
img, ratio, pad = self._letterbox(
|
| 156 |
+
image, (self.input_width, self.input_height)
|
| 157 |
+
)
|
| 158 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 159 |
+
img = img.astype(np.float32) / 255.0
|
| 160 |
img = np.transpose(img, (2, 0, 1))[None, ...]
|
| 161 |
+
img = np.ascontiguousarray(img, dtype=np.float32)
|
| 162 |
+
|
| 163 |
+
return img, ratio, pad, (orig_w, orig_h)
|
| 164 |
|
| 165 |
@staticmethod
|
| 166 |
def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
|
|
|
|
| 171 |
boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
|
| 172 |
return boxes
|
| 173 |
|
|
|
|
| 174 |
@staticmethod
|
| 175 |
+
def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray:
|
| 176 |
+
out = np.empty_like(boxes)
|
| 177 |
+
out[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0
|
| 178 |
+
out[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0
|
| 179 |
+
out[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0
|
| 180 |
+
out[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0
|
| 181 |
+
return out
|
| 182 |
+
|
| 183 |
+
@staticmethod
|
| 184 |
+
def _hard_nms(
|
| 185 |
+
boxes: np.ndarray,
|
| 186 |
+
scores: np.ndarray,
|
| 187 |
+
iou_thresh: float,
|
| 188 |
+
) -> np.ndarray:
|
| 189 |
+
if len(boxes) == 0:
|
| 190 |
return np.array([], dtype=np.intp)
|
| 191 |
+
|
| 192 |
boxes = np.asarray(boxes, dtype=np.float32)
|
| 193 |
scores = np.asarray(scores, dtype=np.float32)
|
| 194 |
+
order = np.argsort(scores)[::-1]
|
| 195 |
+
keep = []
|
| 196 |
+
|
| 197 |
+
while len(order) > 0:
|
| 198 |
+
i = order[0]
|
| 199 |
keep.append(i)
|
| 200 |
if len(order) == 1:
|
| 201 |
break
|
| 202 |
+
|
| 203 |
rest = order[1:]
|
| 204 |
+
|
| 205 |
xx1 = np.maximum(boxes[i, 0], boxes[rest, 0])
|
| 206 |
yy1 = np.maximum(boxes[i, 1], boxes[rest, 1])
|
| 207 |
xx2 = np.minimum(boxes[i, 2], boxes[rest, 2])
|
| 208 |
yy2 = np.minimum(boxes[i, 3], boxes[rest, 3])
|
| 209 |
+
|
| 210 |
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 211 |
+
|
| 212 |
+
area_i = np.maximum(0.0, (boxes[i, 2] - boxes[i, 0])) * np.maximum(0.0, (boxes[i, 3] - boxes[i, 1]))
|
| 213 |
+
area_r = np.maximum(0.0, (boxes[rest, 2] - boxes[rest, 0])) * np.maximum(0.0, (boxes[rest, 3] - boxes[rest, 1]))
|
| 214 |
+
|
| 215 |
iou = inter / (area_i + area_r - inter + 1e-7)
|
| 216 |
order = rest[iou <= iou_thresh]
|
|
|
|
| 217 |
|
| 218 |
+
return np.array(keep, dtype=np.intp)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
@staticmethod
|
| 221 |
def _box_iou_one_to_many(box: np.ndarray, boxes: np.ndarray) -> np.ndarray:
|
|
|
|
|
|
|
| 222 |
xx1 = np.maximum(box[0], boxes[:, 0])
|
| 223 |
yy1 = np.maximum(box[1], boxes[:, 1])
|
| 224 |
xx2 = np.minimum(box[2], boxes[:, 2])
|
| 225 |
yy2 = np.minimum(box[3], boxes[:, 3])
|
| 226 |
+
|
| 227 |
inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
|
| 228 |
+
|
| 229 |
area_a = max(0.0, (box[2] - box[0]) * (box[3] - box[1]))
|
| 230 |
area_b = np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) * np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
|
| 231 |
+
|
| 232 |
return inter / (area_a + area_b - inter + 1e-7)
|
| 233 |
|
| 234 |
+
def _filter_sane_boxes(
|
| 235 |
+
self,
|
| 236 |
+
boxes: np.ndarray,
|
| 237 |
+
scores: np.ndarray,
|
| 238 |
+
cls_ids: np.ndarray,
|
| 239 |
+
orig_size: tuple[int, int],
|
| 240 |
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 241 |
+
if len(boxes) == 0:
|
| 242 |
+
return boxes, scores, cls_ids
|
| 243 |
+
|
| 244 |
+
orig_w, orig_h = orig_size
|
| 245 |
+
image_area = float(orig_w * orig_h)
|
| 246 |
+
|
| 247 |
+
keep = []
|
| 248 |
+
for i, box in enumerate(boxes):
|
| 249 |
+
x1, y1, x2, y2 = box.tolist()
|
| 250 |
+
bw = x2 - x1
|
| 251 |
+
bh = y2 - y1
|
| 252 |
+
|
| 253 |
+
if bw <= 0 or bh <= 0:
|
| 254 |
+
continue
|
| 255 |
+
if bw < self.min_w or bh < self.min_h:
|
| 256 |
+
continue
|
| 257 |
+
|
| 258 |
+
area = bw * bh
|
| 259 |
+
if area < self.min_box_area:
|
| 260 |
+
continue
|
| 261 |
+
if area > self.max_box_area_ratio * image_area:
|
| 262 |
+
continue
|
| 263 |
+
|
| 264 |
+
ar = max(bw / max(bh, 1e-6), bh / max(bw, 1e-6))
|
| 265 |
+
if ar > self.max_aspect_ratio:
|
| 266 |
+
continue
|
| 267 |
+
|
| 268 |
+
keep.append(i)
|
| 269 |
+
|
| 270 |
+
if not keep:
|
| 271 |
+
return (
|
| 272 |
+
np.empty((0, 4), dtype=np.float32),
|
| 273 |
+
np.empty((0,), dtype=np.float32),
|
| 274 |
+
np.empty((0,), dtype=np.int32),
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
keep = np.array(keep, dtype=np.intp)
|
| 278 |
+
return boxes[keep], scores[keep], cls_ids[keep]
|
| 279 |
+
|
| 280 |
+
def _decode_final_dets(
|
| 281 |
+
self,
|
| 282 |
+
preds: np.ndarray,
|
| 283 |
+
ratio: float,
|
| 284 |
+
pad: tuple[float, float],
|
| 285 |
+
orig_size: tuple[int, int],
|
| 286 |
+
) -> list[BoundingBox]:
|
| 287 |
+
if preds.ndim == 3 and preds.shape[0] == 1:
|
| 288 |
+
preds = preds[0]
|
| 289 |
+
|
| 290 |
+
if preds.ndim != 2 or preds.shape[1] < 6:
|
| 291 |
+
raise ValueError(f"Unexpected ONNX final-det output shape: {preds.shape}")
|
| 292 |
+
|
| 293 |
+
boxes = preds[:, :4].astype(np.float32)
|
| 294 |
+
scores = preds[:, 4].astype(np.float32)
|
| 295 |
+
cls_ids = preds[:, 5].astype(np.int32)
|
| 296 |
+
|
| 297 |
+
# person only
|
| 298 |
+
keep = cls_ids == 0
|
| 299 |
+
boxes = boxes[keep]
|
| 300 |
+
scores = scores[keep]
|
| 301 |
+
cls_ids = cls_ids[keep]
|
| 302 |
+
|
| 303 |
+
# candidate threshold
|
| 304 |
+
keep = scores >= self.conf_thres
|
| 305 |
+
boxes = boxes[keep]
|
| 306 |
+
scores = scores[keep]
|
| 307 |
+
cls_ids = cls_ids[keep]
|
| 308 |
+
|
| 309 |
if len(boxes) == 0:
|
| 310 |
+
return []
|
| 311 |
+
|
| 312 |
+
pad_w, pad_h = pad
|
| 313 |
+
orig_w, orig_h = orig_size
|
| 314 |
+
|
| 315 |
+
boxes[:, [0, 2]] -= pad_w
|
| 316 |
+
boxes[:, [1, 3]] -= pad_h
|
| 317 |
boxes /= ratio
|
| 318 |
+
boxes = self._clip_boxes(boxes, (orig_w, orig_h))
|
|
|
|
|
|
|
| 319 |
|
| 320 |
+
boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
|
| 321 |
+
if len(boxes) == 0:
|
| 322 |
+
return []
|
| 323 |
+
|
| 324 |
+
keep_idx = self._hard_nms(boxes, scores, self.iou_thres)
|
| 325 |
+
keep_idx = keep_idx[: self.max_det]
|
| 326 |
+
|
| 327 |
+
boxes = boxes[keep_idx]
|
| 328 |
+
scores = scores[keep_idx]
|
| 329 |
+
cls_ids = cls_ids[keep_idx]
|
| 330 |
+
|
| 331 |
+
return [
|
| 332 |
+
BoundingBox(
|
| 333 |
+
x1=int(math.floor(box[0])),
|
| 334 |
+
y1=int(math.floor(box[1])),
|
| 335 |
+
x2=int(math.ceil(box[2])),
|
| 336 |
+
y2=int(math.ceil(box[3])),
|
| 337 |
+
cls_id=int(cls_id),
|
| 338 |
+
conf=float(conf),
|
| 339 |
+
)
|
| 340 |
+
for box, conf, cls_id in zip(boxes, scores, cls_ids)
|
| 341 |
+
if box[2] > box[0] and box[3] > box[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
]
|
| 343 |
+
|
| 344 |
+
def _decode_raw_yolo(
|
| 345 |
+
self,
|
| 346 |
+
preds: np.ndarray,
|
| 347 |
+
ratio: float,
|
| 348 |
+
pad: tuple[float, float],
|
| 349 |
+
orig_size: tuple[int, int],
|
| 350 |
+
) -> list[BoundingBox]:
|
| 351 |
+
if preds.ndim != 3:
|
| 352 |
+
raise ValueError(f"Unexpected raw ONNX output shape: {preds.shape}")
|
| 353 |
+
if preds.shape[0] != 1:
|
| 354 |
+
raise ValueError(f"Unexpected batch dimension in raw output: {preds.shape}")
|
| 355 |
+
|
| 356 |
+
preds = preds[0]
|
| 357 |
+
|
| 358 |
+
# Normalize to [N, C]
|
| 359 |
+
if preds.shape[0] <= 16 and preds.shape[1] > preds.shape[0]:
|
| 360 |
+
preds = preds.T
|
| 361 |
+
|
| 362 |
+
if preds.ndim != 2 or preds.shape[1] < 5:
|
| 363 |
+
raise ValueError(f"Unexpected normalized raw output shape: {preds.shape}")
|
| 364 |
+
|
| 365 |
+
boxes_xywh = preds[:, :4].astype(np.float32)
|
| 366 |
+
tail = preds[:, 4:].astype(np.float32)
|
| 367 |
+
|
| 368 |
+
# Supports:
|
| 369 |
+
# [x,y,w,h,score] single-class
|
| 370 |
+
# [x,y,w,h,obj,cls] YOLO standard single-class
|
| 371 |
+
# [x,y,w,h,obj,cls1,cls2,...] multi-class
|
| 372 |
+
if tail.shape[1] == 1:
|
| 373 |
+
scores = tail[:, 0]
|
| 374 |
+
cls_ids = np.zeros(len(scores), dtype=np.int32)
|
| 375 |
+
elif tail.shape[1] == 2:
|
| 376 |
+
obj = tail[:, 0]
|
| 377 |
+
cls_prob = tail[:, 1]
|
| 378 |
+
scores = obj * cls_prob
|
| 379 |
+
cls_ids = np.zeros(len(scores), dtype=np.int32)
|
| 380 |
+
else:
|
| 381 |
+
obj = tail[:, 0]
|
| 382 |
+
class_probs = tail[:, 1:]
|
| 383 |
+
cls_ids = np.argmax(class_probs, axis=1).astype(np.int32)
|
| 384 |
+
cls_scores = class_probs[np.arange(len(class_probs)), cls_ids]
|
| 385 |
+
scores = obj * cls_scores
|
| 386 |
+
|
| 387 |
+
keep = cls_ids == 0
|
| 388 |
+
boxes_xywh = boxes_xywh[keep]
|
| 389 |
+
scores = scores[keep]
|
| 390 |
+
cls_ids = cls_ids[keep]
|
| 391 |
+
|
| 392 |
+
keep = scores >= self.conf_thres
|
| 393 |
+
boxes_xywh = boxes_xywh[keep]
|
| 394 |
+
scores = scores[keep]
|
| 395 |
+
cls_ids = cls_ids[keep]
|
| 396 |
+
|
| 397 |
+
if len(boxes_xywh) == 0:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
return []
|
| 399 |
+
|
| 400 |
+
boxes = self._xywh_to_xyxy(boxes_xywh)
|
| 401 |
+
|
| 402 |
+
pad_w, pad_h = pad
|
| 403 |
+
orig_w, orig_h = orig_size
|
| 404 |
+
|
| 405 |
+
boxes[:, [0, 2]] -= pad_w
|
| 406 |
+
boxes[:, [1, 3]] -= pad_h
|
| 407 |
+
boxes /= ratio
|
| 408 |
+
boxes = self._clip_boxes(boxes, (orig_w, orig_h))
|
| 409 |
+
|
| 410 |
+
boxes, scores, cls_ids = self._filter_sane_boxes(boxes, scores, cls_ids, orig_size)
|
| 411 |
+
if len(boxes) == 0:
|
| 412 |
return []
|
| 413 |
+
|
| 414 |
+
keep_idx = self._hard_nms(boxes, scores, self.iou_thres)
|
| 415 |
+
keep_idx = keep_idx[: self.max_det]
|
| 416 |
+
|
| 417 |
+
boxes = boxes[keep_idx]
|
| 418 |
+
scores = scores[keep_idx]
|
| 419 |
+
cls_ids = cls_ids[keep_idx]
|
| 420 |
+
|
| 421 |
+
return [
|
| 422 |
+
BoundingBox(
|
| 423 |
+
x1=int(math.floor(box[0])),
|
| 424 |
+
y1=int(math.floor(box[1])),
|
| 425 |
+
x2=int(math.ceil(box[2])),
|
| 426 |
+
y2=int(math.ceil(box[3])),
|
| 427 |
+
cls_id=int(cls_id),
|
| 428 |
+
conf=float(conf),
|
| 429 |
+
)
|
| 430 |
+
for box, conf, cls_id in zip(boxes, scores, cls_ids)
|
| 431 |
+
if box[2] > box[0] and box[3] > box[1]
|
| 432 |
+
]
|
| 433 |
+
|
| 434 |
+
def _postprocess(
|
| 435 |
+
self,
|
| 436 |
+
output: np.ndarray,
|
| 437 |
+
ratio: float,
|
| 438 |
+
pad: tuple[float, float],
|
| 439 |
+
orig_size: tuple[int, int],
|
| 440 |
+
) -> list[BoundingBox]:
|
| 441 |
+
if output.ndim == 2 and output.shape[1] >= 6:
|
| 442 |
+
return self._decode_final_dets(output, ratio, pad, orig_size)
|
| 443 |
+
|
| 444 |
+
if output.ndim == 3 and output.shape[0] == 1 and output.shape[2] >= 6:
|
| 445 |
+
return self._decode_final_dets(output, ratio, pad, orig_size)
|
| 446 |
+
|
| 447 |
+
return self._decode_raw_yolo(output, ratio, pad, orig_size)
|
| 448 |
+
|
| 449 |
+
def _predict_single(self, image: np.ndarray) -> list[BoundingBox]:
|
| 450 |
+
if image is None:
|
| 451 |
+
raise ValueError("Input image is None")
|
| 452 |
+
if not isinstance(image, np.ndarray):
|
| 453 |
+
raise TypeError(f"Input is not numpy array: {type(image)}")
|
| 454 |
+
if image.ndim != 3:
|
| 455 |
+
raise ValueError(f"Expected HWC image, got shape={image.shape}")
|
| 456 |
+
if image.shape[0] <= 0 or image.shape[1] <= 0:
|
| 457 |
+
raise ValueError(f"Invalid image shape={image.shape}")
|
| 458 |
+
if image.shape[2] != 3:
|
| 459 |
+
raise ValueError(f"Expected 3 channels, got shape={image.shape}")
|
| 460 |
+
|
| 461 |
if image.dtype != np.uint8:
|
| 462 |
image = image.astype(np.uint8)
|
| 463 |
|
| 464 |
+
input_tensor, ratio, pad, orig_size = self._preprocess(image)
|
| 465 |
+
|
| 466 |
+
expected_shape = (1, 3, self.input_height, self.input_width)
|
| 467 |
+
if input_tensor.shape != expected_shape:
|
| 468 |
+
raise ValueError(
|
| 469 |
+
f"Bad input tensor shape={input_tensor.shape}, expected={expected_shape}"
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
outputs = self.session.run(self.output_names, {self.input_name: input_tensor})
|
| 473 |
+
det_output = outputs[0]
|
| 474 |
+
return self._postprocess(det_output, ratio, pad, orig_size)
|
| 475 |
|
| 476 |
+
def _merge_tta_consensus(
|
| 477 |
+
self,
|
| 478 |
+
boxes_orig: list[BoundingBox],
|
| 479 |
+
boxes_flip: list[BoundingBox],
|
| 480 |
+
) -> list[BoundingBox]:
|
| 481 |
+
"""
|
| 482 |
+
Keep:
|
| 483 |
+
- any box with conf >= conf_high
|
| 484 |
+
- low/medium-conf boxes only if confirmed across TTA views
|
| 485 |
+
Then run final hard NMS.
|
| 486 |
+
"""
|
| 487 |
+
if not boxes_orig and not boxes_flip:
|
| 488 |
+
return []
|
| 489 |
+
|
| 490 |
+
coords_o = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0, 4), dtype=np.float32)
|
| 491 |
+
scores_o = np.array([b.conf for b in boxes_orig], dtype=np.float32) if boxes_orig else np.empty((0,), dtype=np.float32)
|
| 492 |
+
|
| 493 |
+
coords_f = np.array([[b.x1, b.y1, b.x2, b.y2] for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0, 4), dtype=np.float32)
|
| 494 |
+
scores_f = np.array([b.conf for b in boxes_flip], dtype=np.float32) if boxes_flip else np.empty((0,), dtype=np.float32)
|
| 495 |
+
|
| 496 |
+
accepted_boxes = []
|
| 497 |
+
accepted_scores = []
|
| 498 |
+
|
| 499 |
+
# Original view candidates
|
| 500 |
+
for i in range(len(coords_o)):
|
| 501 |
+
score = scores_o[i]
|
| 502 |
+
if score >= self.conf_high:
|
| 503 |
+
accepted_boxes.append(coords_o[i])
|
| 504 |
+
accepted_scores.append(score)
|
| 505 |
+
elif len(coords_f) > 0:
|
| 506 |
+
ious = self._box_iou_one_to_many(coords_o[i], coords_f)
|
| 507 |
+
j = int(np.argmax(ious))
|
| 508 |
+
if ious[j] >= self.tta_match_iou:
|
| 509 |
+
fused_score = max(score, scores_f[j])
|
| 510 |
+
accepted_boxes.append(coords_o[i])
|
| 511 |
+
accepted_scores.append(fused_score)
|
| 512 |
+
|
| 513 |
+
# Flipped-view high-confidence boxes that original missed
|
| 514 |
+
for i in range(len(coords_f)):
|
| 515 |
+
score = scores_f[i]
|
| 516 |
+
if score < self.conf_high:
|
| 517 |
continue
|
| 518 |
+
|
| 519 |
+
if len(coords_o) == 0:
|
| 520 |
+
accepted_boxes.append(coords_f[i])
|
| 521 |
+
accepted_scores.append(score)
|
| 522 |
+
continue
|
| 523 |
+
|
| 524 |
+
ious = self._box_iou_one_to_many(coords_f[i], coords_o)
|
| 525 |
+
if np.max(ious) < self.tta_match_iou:
|
| 526 |
+
accepted_boxes.append(coords_f[i])
|
| 527 |
+
accepted_scores.append(score)
|
| 528 |
+
|
| 529 |
+
if not accepted_boxes:
|
| 530 |
+
return []
|
| 531 |
+
|
| 532 |
+
boxes = np.array(accepted_boxes, dtype=np.float32)
|
| 533 |
+
scores = np.array(accepted_scores, dtype=np.float32)
|
| 534 |
+
|
| 535 |
+
keep = self._hard_nms(boxes, scores, self.iou_thres)
|
| 536 |
+
keep = keep[: self.max_det]
|
| 537 |
+
|
| 538 |
+
out = []
|
| 539 |
+
for idx in keep:
|
| 540 |
+
x1, y1, x2, y2 = boxes[idx].tolist()
|
| 541 |
+
out.append(
|
| 542 |
BoundingBox(
|
| 543 |
x1=int(math.floor(x1)),
|
| 544 |
y1=int(math.floor(y1)),
|
| 545 |
x2=int(math.ceil(x2)),
|
| 546 |
y2=int(math.ceil(y2)),
|
| 547 |
cls_id=0,
|
| 548 |
+
conf=float(scores[idx]),
|
| 549 |
)
|
| 550 |
)
|
| 551 |
+
return out
|
| 552 |
+
|
| 553 |
+
def _predict_tta(self, image: np.ndarray) -> list[BoundingBox]:
|
| 554 |
+
boxes_orig = self._predict_single(image)
|
| 555 |
+
|
| 556 |
+
flipped = cv2.flip(image, 1)
|
| 557 |
+
boxes_flip_raw = self._predict_single(flipped)
|
| 558 |
+
|
| 559 |
+
w = image.shape[1]
|
| 560 |
+
boxes_flip = [
|
| 561 |
+
BoundingBox(
|
| 562 |
+
x1=w - b.x2,
|
| 563 |
+
y1=b.y1,
|
| 564 |
+
x2=w - b.x1,
|
| 565 |
+
y2=b.y2,
|
| 566 |
+
cls_id=b.cls_id,
|
| 567 |
+
conf=b.conf,
|
| 568 |
+
)
|
| 569 |
+
for b in boxes_flip_raw
|
| 570 |
+
]
|
| 571 |
+
|
| 572 |
+
return self._merge_tta_consensus(boxes_orig, boxes_flip)
|
| 573 |
|
|
|
|
| 574 |
def predict_batch(
|
| 575 |
self,
|
| 576 |
batch_images: list[ndarray],
|
|
|
|
| 578 |
n_keypoints: int,
|
| 579 |
) -> list[TVFrameResult]:
|
| 580 |
results: list[TVFrameResult] = []
|
| 581 |
+
|
| 582 |
for frame_number_in_batch, image in enumerate(batch_images):
|
| 583 |
try:
|
| 584 |
+
if self.use_tta:
|
| 585 |
+
boxes = self._predict_tta(image)
|
| 586 |
+
else:
|
| 587 |
+
boxes = self._predict_single(image)
|
| 588 |
except Exception as e:
|
| 589 |
+
print(f"⚠️ Inference failed for frame {offset + frame_number_in_batch}: {e}")
|
| 590 |
boxes = []
|
| 591 |
+
|
| 592 |
results.append(
|
| 593 |
TVFrameResult(
|
| 594 |
frame_id=offset + frame_number_in_batch,
|
|
|
|
| 596 |
keypoints=[(0, 0) for _ in range(max(0, int(n_keypoints)))],
|
| 597 |
)
|
| 598 |
)
|
| 599 |
+
|
| 600 |
+
return results
|