scorevision: push artifact
Browse files
miner.py
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from pathlib import Path
|
| 2 |
import math
|
| 3 |
|
|
@@ -8,6 +18,17 @@ from numpy import ndarray
|
|
| 8 |
from pydantic import BaseModel
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
class BoundingBox(BaseModel):
|
| 12 |
x1: int
|
| 13 |
y1: int
|
|
@@ -25,134 +46,117 @@ class TVFrameResult(BaseModel):
|
|
| 25 |
|
| 26 |
class Miner:
|
| 27 |
"""
|
| 28 |
-
|
| 29 |
-
This miner is intentionally self-contained for chute import restrictions.
|
| 30 |
"""
|
| 31 |
|
| 32 |
def __init__(self, path_hf_repo: Path) -> None:
|
| 33 |
self.path_hf_repo = path_hf_repo
|
| 34 |
-
self.class_names = ['person']
|
| 35 |
self.session = ort.InferenceSession(
|
| 36 |
str(path_hf_repo / "weights.onnx"),
|
| 37 |
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 38 |
)
|
| 39 |
self.input_name = self.session.get_inputs()[0].name
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
self.input_h = int(input_shape[2])
|
| 43 |
-
self.input_w = int(input_shape[3])
|
| 44 |
-
self.conf_threshold = 0.70 # sweep-optimised: max composite 0.65ΓmAP+0.35ΓFP_score
|
| 45 |
-
self.iou_threshold = 0.45
|
| 46 |
|
| 47 |
def __repr__(self) -> str:
|
| 48 |
-
return f"
|
| 49 |
-
|
| 50 |
-
def
|
| 51 |
-
h, w =
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
pred = raw[0]
|
| 63 |
-
if pred.ndim != 2:
|
| 64 |
-
raise ValueError(f"Unexpected prediction shape: {raw.shape}")
|
| 65 |
-
if pred.shape[0] < pred.shape[1]:
|
| 66 |
-
pred = pred.transpose(1, 0)
|
| 67 |
-
return pred
|
| 68 |
|
| 69 |
-
def
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
| 75 |
order = scores.argsort()[::-1]
|
| 76 |
-
keep = []
|
| 77 |
-
|
| 78 |
-
while order.size > 0:
|
| 79 |
i = order[0]
|
| 80 |
-
keep.append(i)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
inter = w * h
|
| 90 |
-
|
| 91 |
-
area_i = (boxes[i, 2] - boxes[i, 0]) * (boxes[i, 3] - boxes[i, 1])
|
| 92 |
-
area_rest = (boxes[order[1:], 2] - boxes[order[1:], 0]) * (boxes[order[1:], 3] - boxes[order[1:], 1])
|
| 93 |
-
union = np.maximum(area_i + area_rest - inter, 1e-6)
|
| 94 |
-
iou = inter / union
|
| 95 |
-
|
| 96 |
-
remaining = np.where(iou <= self.iou_threshold)[0]
|
| 97 |
-
order = order[remaining + 1]
|
| 98 |
-
|
| 99 |
-
return [dets[idx] for idx in keep]
|
| 100 |
|
| 101 |
def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
| 110 |
-
cls_scores = pred[:, 4:]
|
| 111 |
-
|
| 112 |
-
if cls_scores.shape[1] == 0:
|
| 113 |
-
return []
|
| 114 |
|
| 115 |
cls_ids = np.argmax(cls_scores, axis=1)
|
| 116 |
confs = np.max(cls_scores, axis=1)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
boxes = boxes[keep]
|
| 120 |
-
confs = confs[keep]
|
| 121 |
-
cls_ids = cls_ids[keep]
|
| 122 |
|
| 123 |
-
if
|
| 124 |
return []
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
|
|
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
y2 = (cy + bh / 2.0) * sy
|
| 136 |
-
dets.append((x1, y1, x2, y2, float(confs[i]), int(cls_ids[i])))
|
| 137 |
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
out_boxes: list[BoundingBox] = []
|
| 141 |
-
for
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
| 153 |
conf=max(0.0, min(1.0, conf)),
|
| 154 |
-
)
|
| 155 |
-
)
|
| 156 |
return out_boxes
|
| 157 |
|
| 158 |
def predict_batch(
|
|
@@ -165,11 +169,9 @@ class Miner:
|
|
| 165 |
for idx, image in enumerate(batch_images):
|
| 166 |
boxes = self._infer_single(image)
|
| 167 |
keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
|
| 168 |
-
results.append(
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
)
|
| 174 |
-
)
|
| 175 |
return results
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Score Vision SN44 β VehicleDetect miner. v2 (2026-03-25).
|
| 3 |
+
|
| 4 |
+
Model: YOLO11n ONNX, 4 classes trained as:
|
| 5 |
+
0 = car, 1 = bus, 2 = truck, 3 = motorcycle
|
| 6 |
+
|
| 7 |
+
Official submission order (remapped in MODEL_TO_OUT):
|
| 8 |
+
0 = bus, 1 = car, 2 = truck, 3 = motorcycle
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
from pathlib import Path
|
| 12 |
import math
|
| 13 |
|
|
|
|
| 18 |
from pydantic import BaseModel
|
| 19 |
|
| 20 |
|
| 21 |
+
# ββ Model class index β submission class index βββββββββββββββββββββββββββββββ
|
| 22 |
+
# Trained order: car=0, bus=1, truck=2, motorcycle=3
|
| 23 |
+
# Official order: bus=0, car=1, truck=2, motorcycle=3
|
| 24 |
+
MODEL_TO_OUT: dict[int, int] = {0: 1, 1: 0, 2: 2, 3: 3}
|
| 25 |
+
OUT_NAMES = ["bus", "car", "truck", "motorcycle"]
|
| 26 |
+
|
| 27 |
+
IMG_SIZE = 640
|
| 28 |
+
CONF_THRESH = 0.55 # sweep-optimised: max composite (0.60ΓmAP + 0.40ΓFP_score)
|
| 29 |
+
IOU_THRESH = 0.45
|
| 30 |
+
|
| 31 |
+
|
| 32 |
class BoundingBox(BaseModel):
|
| 33 |
x1: int
|
| 34 |
y1: int
|
|
|
|
| 46 |
|
| 47 |
class Miner:
|
| 48 |
"""
|
| 49 |
+
VehicleDetect miner for SN44. Loaded by turbovision template at startup.
|
|
|
|
| 50 |
"""
|
| 51 |
|
| 52 |
def __init__(self, path_hf_repo: Path) -> None:
|
| 53 |
self.path_hf_repo = path_hf_repo
|
|
|
|
| 54 |
self.session = ort.InferenceSession(
|
| 55 |
str(path_hf_repo / "weights.onnx"),
|
| 56 |
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 57 |
)
|
| 58 |
self.input_name = self.session.get_inputs()[0].name
|
| 59 |
+
self.conf_threshold = CONF_THRESH
|
| 60 |
+
self.iou_threshold = IOU_THRESH
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
def __repr__(self) -> str:
|
| 63 |
+
return f"VehicleDetect Miner session={type(self.session).__name__}"
|
| 64 |
+
|
| 65 |
+
def _letterbox(self, img: ndarray) -> tuple[np.ndarray, float, int, int]:
|
| 66 |
+
h, w = img.shape[:2]
|
| 67 |
+
r = min(IMG_SIZE / h, IMG_SIZE / w)
|
| 68 |
+
new_w, new_h = int(round(w * r)), int(round(h * r))
|
| 69 |
+
img_r = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
|
| 70 |
+
dw, dh = IMG_SIZE - new_w, IMG_SIZE - new_h
|
| 71 |
+
pad_l, pad_t = dw // 2, dh // 2
|
| 72 |
+
img_p = cv2.copyMakeBorder(
|
| 73 |
+
img_r, pad_t, dh - pad_t, pad_l, dw - pad_l,
|
| 74 |
+
cv2.BORDER_CONSTANT, value=(114, 114, 114),
|
| 75 |
+
)
|
| 76 |
+
return img_p, r, pad_l, pad_t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, float, int, int]:
|
| 79 |
+
img_p, ratio, pad_l, pad_t = self._letterbox(image_bgr)
|
| 80 |
+
img_rgb = cv2.cvtColor(img_p, cv2.COLOR_BGR2RGB)
|
| 81 |
+
inp = img_rgb.astype(np.float32) / 255.0
|
| 82 |
+
inp = np.ascontiguousarray(inp.transpose(2, 0, 1)[np.newaxis])
|
| 83 |
+
return inp, ratio, pad_l, pad_t
|
| 84 |
|
| 85 |
+
def _nms(self, boxes: np.ndarray, scores: np.ndarray) -> list[int]:
|
| 86 |
+
if not len(boxes):
|
| 87 |
+
return []
|
| 88 |
+
x1, y1, x2, y2 = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
|
| 89 |
+
areas = (x2 - x1) * (y2 - y1)
|
| 90 |
order = scores.argsort()[::-1]
|
| 91 |
+
keep: list[int] = []
|
| 92 |
+
while len(order):
|
|
|
|
| 93 |
i = order[0]
|
| 94 |
+
keep.append(int(i))
|
| 95 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 96 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 97 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 98 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 99 |
+
inter = np.maximum(0, xx2 - xx1) * np.maximum(0, yy2 - yy1)
|
| 100 |
+
iou = inter / (areas[i] + areas[order[1:]] - inter + 1e-7)
|
| 101 |
+
order = order[1:][iou <= self.iou_threshold]
|
| 102 |
+
return keep
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
|
| 105 |
+
orig_h, orig_w = image_bgr.shape[:2]
|
| 106 |
+
inp, ratio, pad_l, pad_t = self._preprocess(image_bgr)
|
| 107 |
+
raw = self.session.run(None, {self.input_name: inp})[0]
|
| 108 |
|
| 109 |
+
# Output: [1, 8, 8400] β pred: [8, 8400] β [8400, 8]
|
| 110 |
+
pred = raw[0]
|
| 111 |
+
if pred.shape[0] < pred.shape[1]:
|
| 112 |
+
pred = pred.T # [8400, 8]
|
| 113 |
|
| 114 |
+
bboxes_cx = pred[:, :4] # cx, cy, w, h in letterboxed coords
|
| 115 |
+
cls_scores = pred[:, 4:] # [8400, 4]
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
cls_ids = np.argmax(cls_scores, axis=1)
|
| 118 |
confs = np.max(cls_scores, axis=1)
|
| 119 |
+
mask = confs >= self.conf_threshold
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
|
| 121 |
+
if not mask.any():
|
| 122 |
return []
|
| 123 |
|
| 124 |
+
bboxes_cx = bboxes_cx[mask]
|
| 125 |
+
confs = confs[mask]
|
| 126 |
+
cls_ids = cls_ids[mask]
|
| 127 |
|
| 128 |
+
# cx,cy,w,h β x1,y1,x2,y2 (in letterboxed image coords)
|
| 129 |
+
cx, cy, bw, bh = bboxes_cx[:, 0], bboxes_cx[:, 1], bboxes_cx[:, 2], bboxes_cx[:, 3]
|
| 130 |
+
lx1 = cx - bw / 2
|
| 131 |
+
ly1 = cy - bh / 2
|
| 132 |
+
lx2 = cx + bw / 2
|
| 133 |
+
ly2 = cy + bh / 2
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
# Unletterbox back to original image coords
|
| 136 |
+
x1 = np.clip((lx1 - pad_l) / ratio, 0, orig_w)
|
| 137 |
+
y1 = np.clip((ly1 - pad_t) / ratio, 0, orig_h)
|
| 138 |
+
x2 = np.clip((lx2 - pad_l) / ratio, 0, orig_w)
|
| 139 |
+
y2 = np.clip((ly2 - pad_t) / ratio, 0, orig_h)
|
| 140 |
+
boxes = np.stack([x1, y1, x2, y2], axis=1)
|
| 141 |
|
| 142 |
out_boxes: list[BoundingBox] = []
|
| 143 |
+
for model_cls in range(4):
|
| 144 |
+
cls_mask = cls_ids == model_cls
|
| 145 |
+
if not cls_mask.any():
|
| 146 |
+
continue
|
| 147 |
+
keep = self._nms(boxes[cls_mask], confs[cls_mask])
|
| 148 |
+
sub_cls = MODEL_TO_OUT[model_cls]
|
| 149 |
+
for k in keep:
|
| 150 |
+
box = boxes[cls_mask][k]
|
| 151 |
+
conf = float(confs[cls_mask][k])
|
| 152 |
+
out_boxes.append(BoundingBox(
|
| 153 |
+
x1=max(0, min(orig_w, math.floor(box[0]))),
|
| 154 |
+
y1=max(0, min(orig_h, math.floor(box[1]))),
|
| 155 |
+
x2=max(0, min(orig_w, math.ceil(box[2]))),
|
| 156 |
+
y2=max(0, min(orig_h, math.ceil(box[3]))),
|
| 157 |
+
cls_id=sub_cls,
|
| 158 |
conf=max(0.0, min(1.0, conf)),
|
| 159 |
+
))
|
|
|
|
| 160 |
return out_boxes
|
| 161 |
|
| 162 |
def predict_batch(
|
|
|
|
| 169 |
for idx, image in enumerate(batch_images):
|
| 170 |
boxes = self._infer_single(image)
|
| 171 |
keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
|
| 172 |
+
results.append(TVFrameResult(
|
| 173 |
+
frame_id=offset + idx,
|
| 174 |
+
boxes=boxes,
|
| 175 |
+
keypoints=keypoints,
|
| 176 |
+
))
|
|
|
|
|
|
|
| 177 |
return results
|