File size: 5,734 Bytes
74a73b0
 
3afb9ba
 
74a73b0
 
 
 
 
 
 
 
 
 
 
 
3afb9ba
74a73b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3afb9ba
 
74a73b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
"""Fallen-person detector for Score (Bittensor SN44, public track).

One class: "fallen person" (cls_id 0).  weights.onnx is a YOLO26n detector, input 832 x 832, output
[1, 5, candidates] = centre x, centre y, width, height, confidence per candidate, in input pixels.

Built to never fail a call: the model is checked with a test image at start-up (GPU first, CPU if the GPU run
fails), and an image that cannot be processed gets an empty answer instead of an error."""
import os
from pathlib import Path

import cv2
import numpy as np
import onnxruntime as ort
from numpy import ndarray
from pydantic import BaseModel

CONF = 0.40          # boxes below this confidence are dropped
NMS_IOU = 0.7        # of two boxes overlapping more than this, the weaker one is dropped
MAX_BOXES = 30       # safety cap; the busiest image seen has 10 fallen people
WEIGHTS = "weights.onnx"


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:
        path = str(Path(path_hf_repo) / WEIGHTS)
        so = ort.SessionOptions()
        so.intra_op_num_threads = 2
        so.inter_op_num_threads = 1
        so.log_severity_level = 3
        test = np.full((1024, 1024, 3), 114, np.uint8)
        self.session = None
        tries = [] if os.environ.get("MINER_FORCE_CPU") == "1" else [["CUDAExecutionProvider", "CPUExecutionProvider"]]
        for providers in tries + [["CPUExecutionProvider"]]:
            try:
                if "CUDAExecutionProvider" in providers:
                    try:
                        ort.preload_dlls()
                    except Exception:
                        pass
                s = ort.InferenceSession(path, sess_options=so, providers=providers)
                self._bind(s)
                self._detect(test)                      # a real run: a broken GPU set-up fails here, not on a challenge
                self._detect(test)
                break
            except Exception as e:
                print(f"model start with {providers} failed: {e}")
                self.session = None
        if self.session is None:
            raise RuntimeError("could not start the model on GPU or CPU")
        print("model ready on", self.session.get_providers()[0])

    def _bind(self, session) -> None:
        self.session = session
        i = session.get_inputs()[0]
        self.input_name = i.name
        self.h = i.shape[2] if isinstance(i.shape[2], int) else 832
        self.w = i.shape[3] if isinstance(i.shape[3], int) else 832

    def __repr__(self) -> str:
        return f"fallen-person YOLO26n {self.w}x{self.h} on {self.session.get_providers()[0]}, conf {CONF}"

    def _detect(self, image: ndarray) -> list[BoundingBox]:
        if image.ndim == 2:
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
        elif image.shape[2] == 4:
            image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
        H, W = image.shape[:2]
        r = min(self.w / W, self.h / H)
        rw, rh = max(1, int(round(W * r))), max(1, int(round(H * r)))
        img = image if (rw, rh) == (W, H) else cv2.resize(image, (rw, rh), interpolation=cv2.INTER_CUBIC if r > 1 else cv2.INTER_LINEAR)
        dw, dh = (self.w - rw) / 2, (self.h - rh) / 2
        img = cv2.copyMakeBorder(img, int(round(dh - 0.1)), int(round(dh + 0.1)), int(round(dw - 0.1)), int(round(dw + 0.1)),
                                 cv2.BORDER_CONSTANT, value=(114, 114, 114))
        x = np.ascontiguousarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB).transpose(2, 0, 1)[None], dtype=np.float32) / 255
        p = self.session.run(None, {self.input_name: x})[0][0].astype(np.float32).T        # [candidates, 5]
        p = p[np.isfinite(p).all(1) & (p[:, 4] >= CONF)]
        p = p[np.argsort(-p[:, 4])]
        d = np.stack([p[:, 0] - p[:, 2] / 2, p[:, 1] - p[:, 3] / 2, p[:, 0] + p[:, 2] / 2, p[:, 1] + p[:, 3] / 2, p[:, 4]], 1)
        keep = []
        for b in d:                                     # strongest first
            if len(keep) >= MAX_BOXES:
                break
            if all(self._iou(b, k) <= NMS_IOU for k in keep):
                keep.append(b)
        boxes = []
        for x1, y1, x2, y2, conf in keep:
            x1 = int(np.floor(min(max((x1 - dw) / r, 0), W - 1)))
            y1 = int(np.floor(min(max((y1 - dh) / r, 0), H - 1)))
            x2 = int(np.ceil(min(max((x2 - dw) / r, 0), W - 1)))
            y2 = int(np.ceil(min(max((y2 - dh) / r, 0), H - 1)))
            if x2 > x1 and y2 > y1:
                boxes.append(BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2, cls_id=0, conf=min(max(float(conf), 0.0), 1.0)))
        return boxes

    @staticmethod
    def _iou(a, b) -> float:
        iw = min(a[2], b[2]) - max(a[0], b[0])
        ih = min(a[3], b[3]) - max(a[1], b[1])
        if iw <= 0 or ih <= 0:
            return 0.0
        return float(iw * ih / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - iw * ih + 1e-7))

    def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]:
        results = []
        for k, image in enumerate(batch_images):
            try:
                boxes = self._detect(image)
            except Exception as e:              # an empty answer still scores on an image with nobody fallen; an error scores 0
                print(f"frame {offset + k} failed: {e}")
                boxes = []
            results.append(TVFrameResult(frame_id=offset + k, boxes=boxes, keypoints=[(0, 0)] * int(n_keypoints or 0)))
        return results