from pathlib import Path import json import cv2 import numpy as np import onnxruntime as ort from numpy import ndarray from pydantic import BaseModel class BoundingBox(BaseModel): x1: int y1: int x2: int y2: int cls_id: int conf: float class TVFrameResult(BaseModel): frame_id: int boxes: list[BoundingBox] keypoints: list[tuple[int, int]] class Miner: def __init__(self, path_hf_repo: Path) -> None: root = Path(path_hf_repo) cfg = json.loads((root / "config.json").read_text()) if (root / "config.json").exists() else {} self.conf = [float(c) for c in cfg.get("conf", [0.3, 0.3, 0.3])] self.rescue = float(cfg.get("rescue", 1.0)) self.max_det = int(cfg.get("max_det", 100)) self.nms_iou = float(cfg.get("nms_iou", 0.5)) self.cnt = cfg.get("count_adaptive") # [a, b]: per-class thr = a + b*ln(1 + #boxes of that class with conf >= 0.3) so = ort.SessionOptions() so.intra_op_num_threads = 2 so.inter_op_num_threads = 1 so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL so.add_session_config_entry("session.intra_op.allow_spinning", "0") so.add_session_config_entry("session.inter_op.allow_spinning", "0") self.session = ort.InferenceSession(str(root / "weights.onnx"), so, providers=["CPUExecutionProvider"]) self.input_name = self.session.get_inputs()[0].name self.size = int(self.session.get_inputs()[0].shape[-1]) self.buf = np.full((1, 3, self.size, self.size), 114 / 255, dtype=np.float32) cv2.setNumThreads(1) def __repr__(self) -> str: return f"ONNX {self.size}" def _detect(self, image: ndarray) -> list[BoundingBox]: h, w = image.shape[:2] s = self.size scale = min(s / h, s / w) nw, nh = round(w * scale), round(h * scale) dx, dy = (s - nw) / 2, (s - nh) / 2 top, left = round(dy - 0.1), round(dx - 0.1) r = cv2.resize(image, (nw, nh), interpolation=cv2.INTER_LINEAR) if (nw, nh) != (w, h) else image inp = self.buf inp.fill(114 / 255) k = np.float32(1 / 255) for c in range(3): # BGR (cv2.imdecode) -> RGB np.multiply(r[:, :, 2 - c], k, out=inp[0, c, top:top + nh, left:left + nw], dtype=np.float32) out = self.session.run(None, {self.input_name: inp})[0][0] if out.shape[-1] != 6: # raw head (4+nc, N): cx cy w h scores -> class-wise NMS raw = out.T sc = raw[:, 4:] cl = sc.argmax(1) cf = sc[np.arange(len(sc)), cl] keep = cf >= min(min(self.conf), self.rescue) raw, cf, cl = raw[keep], cf[keep], cl[keep] if len(raw): xywh = raw[:, :4].copy() xywh[:, :2] -= xywh[:, 2:] / 2 idx = np.array(cv2.dnn.NMSBoxesBatched(xywh.tolist(), cf.tolist(), cl.tolist(), 0.0, self.nms_iou), dtype=np.int64).reshape(-1) xyxy = np.concatenate([xywh[:, :2], xywh[:, :2] + xywh[:, 2:]], 1) out = np.concatenate([xyxy[idx], cf[idx, None], cl[idx, None].astype(np.float32)], 1) else: out = np.zeros((0, 6), dtype=np.float32) conf = out[:, 4] cls = out[:, 5].astype(np.int64) if self.cnt: n = np.bincount(cls[conf >= 0.3], minlength=len(self.conf))[: len(self.conf)] per = np.array([self.cnt[0] + self.cnt[1] * np.log1p(k) for k in n], dtype=np.float32) else: per = np.array(self.conf, dtype=np.float32) th = per[np.clip(cls, 0, len(per) - 1)] sel = list(np.nonzero(conf >= th)[0]) if self.rescue < 1.0: for c in range(len(self.conf)): if not any(cls[i] == c for i in sel): cand = np.nonzero((cls == c) & (conf >= self.rescue))[0] if len(cand): sel.append(int(cand[np.argmax(conf[cand])])) sel = sorted(sel, key=lambda i: -conf[i])[: self.max_det] res = [] for i in sel: x1 = int(np.clip((out[i, 0] - dx) / scale, 0, w)) y1 = int(np.clip((out[i, 1] - dy) / scale, 0, h)) x2 = int(np.clip((out[i, 2] - dx) / scale, 0, w)) y2 = int(np.clip((out[i, 3] - dy) / scale, 0, h)) if x2 > x1 and y2 > y1: res.append(BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2, cls_id=int(cls[i]), conf=round(float(conf[i]), 4))) return res def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]: return [ TVFrameResult(frame_id=offset + i, boxes=self._detect(im), keypoints=[(0, 0)] * n_keypoints) for i, im in enumerate(batch_images) ]