"""YOLOX ONNX adapter retaining scores, classes and original image coordinates.""" from pathlib import Path import json import tempfile import uuid import numpy as np def iou(box, boxes): boxes = np.asarray(boxes, dtype=float).reshape(-1, 4) if not len(boxes): return np.empty(0) intersection = np.maximum(0, np.minimum(box[2:], boxes[:, 2:]) - np.maximum(box[:2], boxes[:, :2])).prod(axis=1) a = max(0, box[2]-box[0]) * max(0, box[3]-box[1]) b = np.maximum(0, boxes[:, 2:]-boxes[:, :2]).prod(axis=1) return intersection / np.maximum(a+b-intersection, 1e-9) def decode_yolox(raw, size=640, ratio=1.0, threshold=0.3, classes=(0, 32, 34), nms=0.45): p = np.asarray(raw, dtype=np.float32).reshape(-1, np.asarray(raw).shape[-1]).copy() if p.shape[1] == 5: if list(classes) != [0]: raise ValueError("NMS-integrated person export cannot supply COCO object classes") # The selected HumanArt export contains x1,y1,x2,y2,score after NMS. return [{"class_id": 0, "score": float(row[4]), "box": (row[:4]/ratio).tolist()} for row in p if np.isfinite(row).all() and row[4] >= threshold] expected = sum((size//stride)**2 for stride in (8, 16, 32)) if p.shape[0] != expected or p.shape[1] not in (6, 85): raise ValueError(f"Unsupported raw YOLOX schema: {p.shape}; expected {expected}x6 or x85") if p.shape[1] == 6 and list(classes) != [0]: raise ValueError("Person-only raw export cannot supply COCO bat or ball classes") grids, strides = [], [] for stride in (8, 16, 32): y, x = np.indices((size//stride, size//stride)) grids.append(np.column_stack((x.ravel(), y.ravel()))) strides.append(np.full((x.size, 1), stride)) grid, step = np.concatenate(grids), np.concatenate(strides) centers = (p[:, :2] + grid) * step wh = np.exp(np.clip(p[:, 2:4], -30, 30)) * step boxes = np.concatenate((centers-wh/2, centers+wh/2), axis=1) / ratio all_scores = p[:, 4:5] * p[:, 5:] result = [] for cls in classes: if cls >= all_scores.shape[1]: continue scores = all_scores[:, cls] order = np.flatnonzero(np.isfinite(scores) & (scores >= threshold)) order = order[np.argsort(scores[order])[::-1]] while len(order): k = order[0] if np.isfinite(boxes[k]).all(): result.append({"class_id": int(cls), "score": float(scores[k]), "box": boxes[k].tolist()}) order = order[1:][iou(boxes[k], boxes[order[1:]]) <= nms] return result def ort_session(path, device): import onnxruntime as ort if not Path(path).is_file() or Path(path).suffix != ".onnx": raise ValueError("Explicit local .onnx model required; inference never downloads artifacts") if device == "cuda" and "CUDAExecutionProvider" not in ort.get_available_providers(): raise RuntimeError("CUDA execution provider is unavailable; no silent CPU fallback") if device=="cuda" and hasattr(ort,"preload_dlls"): ort.preload_dlls() providers = [("CUDAExecutionProvider",{"use_tf32":0})] if device == "cuda" else ["CPUExecutionProvider"] options = ort.SessionOptions() options.intra_op_num_threads = 2 if device == "cuda": options.enable_profiling = True options.profile_file_prefix = str(Path(tempfile.gettempdir()) / ("batting-ort-"+uuid.uuid4().hex)) session = ort.InferenceSession(str(path), sess_options=options, providers=providers) if device == "cuda" and session.get_providers()[0] != "CUDAExecutionProvider": try: Path(session.end_profiling()).unlink(missing_ok=True) except Exception: pass raise RuntimeError(f"Requested CUDA session did not initialize on CUDA (ONNX {ort.__version__}). " "Check GPU runtime and CUDA/cuDNN libraries; rerun vision preflight.") return session def verify_cuda_nodes(session): """Provider registration alone is not proof that CUDA actually executed an operator.""" path = Path(session.end_profiling()) try: events = json.loads(path.read_text()) if not any(e.get("args", {}).get("provider") == "CUDAExecutionProvider" for e in events): raise RuntimeError("No CUDA operator execution was observed in ONNX profiling") finally: path.unlink(missing_ok=True) class YOLOXDetector: def __init__(self, path, device="cpu", threshold=0.3, classes=(0, 32, 34)): self.session = ort_session(path, device) self.providers = self.session.get_providers() self.threshold, self.classes = threshold, classes self.device, self.cuda_verified = device, False shape = self.session.get_inputs()[0].shape if shape[1:] != [3, 640, 640]: raise ValueError(f"Unexpected detector input {shape}") def __call__(self, image): import cv2 h, w = image.shape[:2] ratio = min(640/h, 640/w) canvas = np.full((640, 640, 3), 114, np.uint8) resized = cv2.resize(image, (int(w*ratio), int(h*ratio))) canvas[:resized.shape[0], :resized.shape[1]] = resized tensor = canvas.transpose(2, 0, 1)[None].astype(np.float32) raw = self.session.run(None, {self.session.get_inputs()[0].name: tensor})[0] if self.device == "cuda" and not self.cuda_verified: verify_cuda_nodes(self.session) self.cuda_verified = True return decode_yolox(raw, ratio=ratio, threshold=self.threshold, classes=self.classes) def select_person(detections, previous=None): candidates = [d for d in detections if d["class_id"] == 0] if not candidates: return None if previous is not None: overlaps = iou(np.array(previous), [d["box"] for d in candidates]) if max(overlaps) < 0.05: return None # Do not silently jump to a different person. return candidates[int(np.argmax(overlaps))] return max(candidates, key=lambda d: max(0, d["box"][2]-d["box"][0]) * max(0, d["box"][3]-d["box"][1]) * d["score"]) def relevant_people(detections, selected, image_height): """Count athlete-sized person proposals, excluding tiny background hits. The tracked athlete always counts, including a small/poor recording. The capture check rejects it separately when too small. This count is a detector heuristic, not proof that all background people have been identified. """ if selected is None: return sum(d["class_id"] == 0 for d in detections) selected_height = selected["box"][3]-selected["box"][1] minimum = max(.15*image_height, .35*selected_height) return sum(d["class_id"] == 0 and (d is selected or d["box"][3]-d["box"][1] >= minimum) for d in detections)