ArthurSword commited on
Commit
a4cfdf9
Β·
verified Β·
1 Parent(s): d95f44e

scorevision: push artifact

Browse files
Files changed (1) hide show
  1. miner.py +461 -0
miner.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import math
3
+
4
+ import cv2
5
+ import numpy as np
6
+ import onnxruntime as ort
7
+ from numpy import ndarray
8
+ from pydantic import BaseModel
9
+
10
+
11
+ class BoundingBox(BaseModel):
12
+ x1: int
13
+ y1: int
14
+ x2: int
15
+ y2: int
16
+ cls_id: int
17
+ conf: float
18
+
19
+
20
+ class TVFrameResult(BaseModel):
21
+ frame_id: int
22
+ boxes: list[BoundingBox]
23
+ keypoints: list[tuple[int, int]]
24
+
25
+
26
+ class Miner:
27
+ """
28
+ YOLO (NMS-free) ONNX miner for road-sign detection. One forward pass per
29
+ frame β€” no TTA.
30
+
31
+ Class: single 'road sign'.
32
+
33
+ Pipeline per frame: preprocess -> ONNX -> decode -> conf threshold (+ rescue
34
+ bonus) -> un-letterbox -> sanity filter -> per-class NMS -> cross-class dedup
35
+ -> same-class cluster score boost -> results.
36
+
37
+ Speed: the detection pipeline runs exactly ONCE per frame (the old redundant
38
+ second NMS/dedup pass is gone), and the cluster boost is a single vectorized
39
+ IoU matrix, so cost stays flat as the number of detected objects grows.
40
+ """
41
+
42
+ class_names = ['road sign']
43
+ input_size = 1536
44
+ cross_iou_thresh = 0.8
45
+ max_det = 300
46
+ # NMS is O(n^2); if a frame yields a huge candidate list, keep the top-K by
47
+ # score before NMS. Set high enough never to touch real detections.
48
+ pre_nms_topk = 1000
49
+ #overlap_suppress_threshold = 0.85
50
+
51
+ # Per-class confidence threshold
52
+ _conf_thres_array = np.array([0.31], dtype=np.float32)
53
+
54
+ # Per-class IoU threshold for same-class NMS
55
+ _iou_thres_array = np.array([0.85], dtype=np.float32)
56
+
57
+ # Per-class rescue bonus
58
+ _bonus_array = np.array([0.2], dtype=np.float32)
59
+
60
+ # Per-class minimum box area (index 0 = road sign)
61
+ _min_box_area_array = np.array([9.0], dtype=np.float32)
62
+
63
+ def __init__(self, path_hf_repo: Path) -> None:
64
+ self.path_hf_repo = path_hf_repo
65
+
66
+ print("ORT version:", ort.__version__)
67
+
68
+ try:
69
+ ort.preload_dlls()
70
+ print("preload_dlls success")
71
+ except Exception as e:
72
+ print(f"preload_dlls failed: {e}")
73
+
74
+ print("ORT available providers BEFORE session:", ort.get_available_providers())
75
+
76
+ sess_options = ort.SessionOptions()
77
+ sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
78
+
79
+ self.session = ort.InferenceSession(
80
+ str(path_hf_repo / "weights.onnx"),
81
+ sess_options=sess_options,
82
+ providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
83
+ )
84
+ print("Created ORT session with preferred CUDA provider list")
85
+ print("ORT session providers:", self.session.get_providers())
86
+
87
+ self.input_name = self.session.get_inputs()[0].name
88
+ input_shape = self.session.get_inputs()[0].shape
89
+
90
+ self.input_h = self._safe_dim(input_shape[2], default=self.input_size)
91
+ self.input_w = self._safe_dim(input_shape[3], default=self.input_size)
92
+
93
+ # Same-class cluster score boost (raises overlapping same-class survivors
94
+ # to their cluster max). Part of the current tuned behaviour; for a single
95
+ # class it is nearly a no-op. Set False to disable.
96
+ self.use_cluster_boost = True
97
+ self._avg_iou = float(np.mean(self._iou_thres_array))
98
+
99
+ self._warmup()
100
+
101
+ def _warmup(self, iters: int = 3) -> None:
102
+ try:
103
+ dummy = np.zeros((720, 1280, 3), dtype=np.uint8)
104
+ for _ in range(max(1, iters)):
105
+ self.predict_batch(batch_images=[dummy], offset=0, n_keypoints=0)
106
+ print(f"warmup: {iters} dummy predict_batch call(s) done")
107
+ except Exception as e:
108
+ print(f"warmup skipped: {e}")
109
+
110
+ def __repr__(self) -> str:
111
+ return f"road sign Miner classes={len(self.class_names)}"
112
+
113
+ @staticmethod
114
+ def _safe_dim(value, default: int) -> int:
115
+ return value if isinstance(value, int) and value > 0 else default
116
+
117
+ # ─── Preprocessing ────────────────────────────────────────────
118
+
119
+ def _letterbox(
120
+ self, image: ndarray, new_shape: tuple[int, int],
121
+ color: tuple[int, int, int] = (114, 114, 114),
122
+ ) -> tuple[ndarray, float, float, float]:
123
+ orig_h, orig_w = image.shape[:2]
124
+ target_w, target_h = new_shape
125
+
126
+ r = min(target_w / orig_w, target_h / orig_h)
127
+ new_unpad_w = int(round(orig_w * r))
128
+ new_unpad_h = int(round(orig_h * r))
129
+
130
+ resized = cv2.resize(image, (new_unpad_w, new_unpad_h), interpolation=cv2.INTER_LINEAR)
131
+
132
+ dw = target_w - new_unpad_w
133
+ dh = target_h - new_unpad_h
134
+ pad_w = dw / 2.0
135
+ pad_h = dh / 2.0
136
+
137
+ left = int(round(pad_w - 0.1))
138
+ right = int(round(pad_w + 0.1))
139
+ top = int(round(pad_h - 0.1))
140
+ bottom = int(round(pad_h + 0.1))
141
+
142
+ out = cv2.copyMakeBorder(
143
+ resized, top, bottom, left, right,
144
+ cv2.BORDER_CONSTANT, value=color,
145
+ )
146
+ return out, r, pad_w, pad_h
147
+
148
+ def _preprocess(self, image_bgr: ndarray) -> tuple[np.ndarray, dict]:
149
+ orig_h, orig_w = image_bgr.shape[:2]
150
+ rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
151
+ img, ratio, pad_w, pad_h = self._letterbox(rgb, (self.input_w, self.input_h))
152
+ x = img.astype(np.float32) / 255.0
153
+ x = np.transpose(x, (2, 0, 1))[None, ...]
154
+ x = np.ascontiguousarray(x)
155
+ return x, {
156
+ "orig_h": orig_h,
157
+ "orig_w": orig_w,
158
+ "ratio": ratio,
159
+ "pad_w": pad_w,
160
+ "pad_h": pad_h,
161
+ }
162
+
163
+ # ─── Vectorized box operations ───────────────────────────────
164
+
165
+ @staticmethod
166
+ def _clip_boxes(boxes: np.ndarray, image_size: tuple[int, int]) -> np.ndarray:
167
+ w, h = image_size
168
+ boxes[:, 0] = np.clip(boxes[:, 0], 0, w - 1)
169
+ boxes[:, 1] = np.clip(boxes[:, 1], 0, h - 1)
170
+ boxes[:, 2] = np.clip(boxes[:, 2], 0, w - 1)
171
+ boxes[:, 3] = np.clip(boxes[:, 3], 0, h - 1)
172
+ return boxes
173
+
174
+ @staticmethod
175
+ def _hard_nms(boxes: np.ndarray, scores: np.ndarray,
176
+ iou_thresh: float) -> np.ndarray:
177
+ """Vectorized greedy NMS. Areas precomputed once. Returns indices to keep."""
178
+ n = len(boxes)
179
+ if n == 0:
180
+ return np.array([], dtype=np.intp)
181
+ x1, y1 = boxes[:, 0], boxes[:, 1]
182
+ x2, y2 = boxes[:, 2], boxes[:, 3]
183
+ areas = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
184
+ order = np.argsort(-scores)
185
+ keep = []
186
+ while order.size > 0:
187
+ i = int(order[0])
188
+ keep.append(i)
189
+ if order.size == 1:
190
+ break
191
+ rest = order[1:]
192
+ xx1 = np.maximum(x1[i], x1[rest])
193
+ yy1 = np.maximum(y1[i], y1[rest])
194
+ xx2 = np.minimum(x2[i], x2[rest])
195
+ yy2 = np.minimum(y2[i], y2[rest])
196
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
197
+ iou = inter / (areas[i] + areas[rest] - inter + 1e-7)
198
+ order = rest[iou <= iou_thresh]
199
+ return np.array(keep, dtype=np.intp)
200
+
201
+ def _per_class_hard_nms(self, boxes: np.ndarray, scores: np.ndarray,
202
+ cls_ids: np.ndarray) -> np.ndarray:
203
+ """Per-class NMS using per-class IoU thresholds."""
204
+ if len(boxes) == 0:
205
+ return np.array([], dtype=np.intp)
206
+ all_keep = []
207
+ for c in np.unique(cls_ids):
208
+ mask = cls_ids == c
209
+ indices = np.where(mask)[0]
210
+ cls_iou = float(self._iou_thres_array[c]) # per-class IoU threshold
211
+ keep = self._hard_nms(boxes[mask], scores[mask], cls_iou)
212
+ all_keep.extend(indices[keep].tolist())
213
+ all_keep.sort()
214
+ return np.array(all_keep, dtype=np.intp)
215
+
216
+ def _cross_class_dedup_op(self, boxes: np.ndarray, scores: np.ndarray,
217
+ cls_ids: np.ndarray, iou_thresh: float
218
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
219
+ n = len(boxes)
220
+ if n <= 1:
221
+ return boxes, scores, cls_ids
222
+ boxes = np.asarray(boxes, dtype=np.float32)
223
+ scores = np.asarray(scores, dtype=np.float32)
224
+ cls_ids = np.asarray(cls_ids, dtype=np.int32)
225
+ areas = (np.maximum(0.0, boxes[:, 2] - boxes[:, 0]) *
226
+ np.maximum(0.0, boxes[:, 3] - boxes[:, 1]))
227
+ margins = scores - self._conf_thres_array[cls_ids]
228
+ order = np.lexsort((-areas, -margins))
229
+ suppressed = np.zeros(n, dtype=bool)
230
+ keep = []
231
+ for i in order:
232
+ if suppressed[i]:
233
+ continue
234
+ keep.append(int(i))
235
+ bi = boxes[i]
236
+ xx1 = np.maximum(bi[0], boxes[:, 0])
237
+ yy1 = np.maximum(bi[1], boxes[:, 1])
238
+ xx2 = np.minimum(bi[2], boxes[:, 2])
239
+ yy2 = np.minimum(bi[3], boxes[:, 3])
240
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
241
+ a_i = max(1e-7, float((bi[2] - bi[0]) * (bi[3] - bi[1])))
242
+ iou = inter / (a_i + areas - inter + 1e-7)
243
+ dup = iou > iou_thresh
244
+ dup[i] = False
245
+ suppressed |= dup
246
+ keep_idx = np.array(keep, dtype=np.intp)
247
+ return boxes[keep_idx], scores[keep_idx], cls_ids[keep_idx]
248
+
249
+ def _filter_sane_boxes(self, boxes: np.ndarray, scores: np.ndarray,
250
+ cls_ids: np.ndarray, orig_size: tuple[int, int]
251
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
252
+ """Filter by per-class min area and max area ratio."""
253
+ if len(boxes) == 0:
254
+ return boxes, scores, cls_ids
255
+
256
+ orig_w, orig_h = orig_size
257
+ image_area = float(orig_w * orig_h)
258
+ bw = np.maximum(0.0, boxes[:, 2] - boxes[:, 0])
259
+ bh = np.maximum(0.0, boxes[:, 3] - boxes[:, 1])
260
+ area = bw * bh
261
+
262
+ class_min_area = self._min_box_area_array[cls_ids]
263
+
264
+ keep = (
265
+ (area >= class_min_area) &
266
+ (area <= 0.95 * image_area)
267
+ )
268
+ return boxes[keep], scores[keep], cls_ids[keep]
269
+
270
+ def _max_score_per_cluster(self, post_boxes: np.ndarray,
271
+ post_cls: np.ndarray,
272
+ full_boxes: np.ndarray,
273
+ full_scores: np.ndarray,
274
+ full_cls: np.ndarray,
275
+ iou_thresh: float) -> np.ndarray:
276
+ """For each kept box, confidence = max score in its SAME-CLASS IoU cluster.
277
+ Vectorized: single (n_post x n_full) IoU matrix, no per-box Python loop."""
278
+ n = len(post_boxes)
279
+ if n == 0:
280
+ return np.empty(0, dtype=np.float32)
281
+ m = len(full_boxes)
282
+ if m == 0:
283
+ return np.zeros(n, dtype=np.float32)
284
+ pa = (np.maximum(0.0, post_boxes[:, 2] - post_boxes[:, 0]) *
285
+ np.maximum(0.0, post_boxes[:, 3] - post_boxes[:, 1]))
286
+ fa = (np.maximum(0.0, full_boxes[:, 2] - full_boxes[:, 0]) *
287
+ np.maximum(0.0, full_boxes[:, 3] - full_boxes[:, 1]))
288
+ xx1 = np.maximum(post_boxes[:, 0][:, None], full_boxes[:, 0][None, :])
289
+ yy1 = np.maximum(post_boxes[:, 1][:, None], full_boxes[:, 1][None, :])
290
+ xx2 = np.minimum(post_boxes[:, 2][:, None], full_boxes[:, 2][None, :])
291
+ yy2 = np.minimum(post_boxes[:, 3][:, None], full_boxes[:, 3][None, :])
292
+ inter = np.maximum(0.0, xx2 - xx1) * np.maximum(0.0, yy2 - yy1)
293
+ iou = inter / (pa[:, None] + fa[None, :] - inter + 1e-7)
294
+ mask = (iou >= iou_thresh) & (post_cls[:, None] == full_cls[None, :])
295
+ tiled = np.where(mask, full_scores[None, :], -np.inf)
296
+ out = tiled.max(axis=1)
297
+ out[~np.isfinite(out)] = 0.0
298
+ return out.astype(np.float32)
299
+
300
+ def _conf_filter_mask(self, scores: np.ndarray,
301
+ cls_ids: np.ndarray) -> np.ndarray:
302
+ """Per-class threshold with rescue bonus for missed classes."""
303
+ if len(scores) == 0:
304
+ return np.zeros(0, dtype=bool)
305
+ thr = self._conf_thres_array[cls_ids]
306
+ keep = scores >= thr
307
+ for c in np.unique(cls_ids):
308
+ b = float(self._bonus_array[c])
309
+ if b <= 0.0:
310
+ continue
311
+ cm = cls_ids == c
312
+ if keep[cm].any():
313
+ continue
314
+ idx = np.where(cm)[0]
315
+ top = int(idx[int(np.argmax(scores[idx]))])
316
+ if scores[top] >= self._conf_thres_array[c] - b:
317
+ keep[top] = True
318
+ return keep
319
+
320
+ def _per_view_pipeline(self, boxes: np.ndarray, scores: np.ndarray,
321
+ cls_ids: np.ndarray, orig_size: tuple[int, int]
322
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
323
+ """Sanity filter -> (top-k cap) -> per-class NMS -> cap -> cross-class dedup."""
324
+ boxes, scores, cls_ids = self._filter_sane_boxes(
325
+ boxes, scores, cls_ids, orig_size
326
+ )
327
+ if len(boxes) == 0:
328
+ return boxes, scores, cls_ids
329
+ if len(scores) > self.pre_nms_topk:
330
+ top = np.argpartition(-scores, self.pre_nms_topk)[: self.pre_nms_topk]
331
+ boxes, scores, cls_ids = boxes[top], scores[top], cls_ids[top]
332
+ if len(boxes) > 1:
333
+ keep = self._per_class_hard_nms(boxes, scores, cls_ids)
334
+ boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
335
+ if len(scores) > self.max_det:
336
+ top = np.argsort(-scores)[: self.max_det]
337
+ boxes, scores, cls_ids = boxes[top], scores[top], cls_ids[top]
338
+ if len(boxes) > 1:
339
+ boxes, scores, cls_ids = self._cross_class_dedup_op(
340
+ boxes, scores, cls_ids, self.cross_iou_thresh
341
+ )
342
+ return boxes, scores, cls_ids
343
+
344
+ # ─── Decoding ─────────────────────────────────────────────────
345
+
346
+ def _decode_yolo_output(self, preds: np.ndarray, ratio: float,
347
+ pad: tuple[float, float],
348
+ orig_size: tuple[int, int]
349
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
350
+ """Decode NMS-free output [1,N,6]=(x1,y1,x2,y2,conf,cls) -> conf filter ->
351
+ un-letterbox -> sanity+NMS+dedup. Returns arrays in ORIGINAL coords."""
352
+ empty = (np.empty((0, 4), np.float32), np.empty(0, np.float32),
353
+ np.empty(0, np.int32))
354
+ if preds.ndim == 3 and preds.shape[0] == 1:
355
+ preds = preds[0]
356
+ if preds.ndim != 2 or preds.shape[1] < 6:
357
+ print(f"Warning: Unexpected output shape: {preds.shape}")
358
+ return empty
359
+
360
+ boxes = preds[:, :4].astype(np.float32)
361
+ scores = preds[:, 4].astype(np.float32)
362
+ cls_ids = preds[:, 5].astype(np.int32)
363
+
364
+ n_cls = len(self.class_names)
365
+ valid = (cls_ids >= 0) & (cls_ids < n_cls)
366
+ boxes, scores, cls_ids = boxes[valid], scores[valid], cls_ids[valid]
367
+ if len(boxes) == 0:
368
+ return empty
369
+
370
+ keep = self._conf_filter_mask(scores, cls_ids)
371
+ boxes, scores, cls_ids = boxes[keep], scores[keep], cls_ids[keep]
372
+ if len(boxes) == 0:
373
+ return empty
374
+
375
+ pad_w, pad_h = pad
376
+ boxes[:, [0, 2]] -= pad_w
377
+ boxes[:, [1, 3]] -= pad_h
378
+ boxes /= ratio
379
+ boxes = self._clip_boxes(boxes, orig_size)
380
+
381
+ return self._per_view_pipeline(boxes, scores, cls_ids, orig_size)
382
+
383
+ @staticmethod
384
+ def _build_results(boxes: np.ndarray, scores: np.ndarray,
385
+ cls_ids: np.ndarray,
386
+ orig_size: tuple[int, int]) -> list[BoundingBox]:
387
+ results = []
388
+ orig_w, orig_h = orig_size
389
+ for box, conf, cls_id in zip(boxes, scores, cls_ids):
390
+ x1, y1, x2, y2 = box.tolist() if hasattr(box, "tolist") else box
391
+ if x2 <= x1 or y2 <= y1:
392
+ continue
393
+ results.append(
394
+ BoundingBox(
395
+ x1=max(0, min(orig_w, int(math.floor(x1)))),
396
+ y1=max(0, min(orig_h, int(math.floor(y1)))),
397
+ x2=max(0, min(orig_w, int(math.ceil(x2)))),
398
+ y2=max(0, min(orig_h, int(math.ceil(y2)))),
399
+ cls_id=int(cls_id),
400
+ conf=float(max(0.0, min(1.0, conf))),
401
+ )
402
+ )
403
+ return results
404
+
405
+ # ─── Inference (single view, no TTA) ──────────────────────────
406
+
407
+ def _predict_single(self, image_bgr: np.ndarray
408
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
409
+ """One forward pass -> decoded (boxes, scores, cls_ids) in original coords."""
410
+ if image_bgr is None or not isinstance(image_bgr, np.ndarray):
411
+ raise ValueError("Invalid image input")
412
+ if image_bgr.dtype != np.uint8:
413
+ image_bgr = image_bgr.astype(np.uint8)
414
+
415
+ inp, meta = self._preprocess(image_bgr)
416
+ outputs = self.session.run(None, {self.input_name: inp})
417
+
418
+ ratio = float(meta["ratio"])
419
+ pad = (float(meta["pad_w"]), float(meta["pad_h"]))
420
+ orig_size = (int(meta["orig_w"]), int(meta["orig_h"]))
421
+
422
+ return self._decode_yolo_output(outputs[0], ratio, pad, orig_size)
423
+
424
+ def _infer_single(self, image_bgr: ndarray) -> list[BoundingBox]:
425
+ orig_h, orig_w = image_bgr.shape[:2]
426
+ orig_size = (orig_w, orig_h)
427
+
428
+ boxes, scores, cls_ids = self._predict_single(image_bgr)
429
+ if len(boxes) == 0:
430
+ return []
431
+
432
+ if self.use_cluster_boost and len(boxes) > 1:
433
+ scores = self._max_score_per_cluster(
434
+ boxes, cls_ids, boxes, scores, cls_ids, self._avg_iou)
435
+
436
+ return self._build_results(boxes, scores, cls_ids, orig_size)
437
+
438
+ # ─── Public API ───────────────────────────────────────────────
439
+
440
+ def predict_batch(
441
+ self,
442
+ batch_images: list[ndarray],
443
+ offset: int,
444
+ n_keypoints: int,
445
+ ) -> list[TVFrameResult]:
446
+ results: list[TVFrameResult] = []
447
+ for idx, image in enumerate(batch_images):
448
+ try:
449
+ boxes = self._infer_single(image)
450
+ except Exception as e:
451
+ print(f"Inference failed for frame {offset + idx}: {e}")
452
+ boxes = []
453
+ keypoints = [(0, 0) for _ in range(max(0, int(n_keypoints)))]
454
+ results.append(
455
+ TVFrameResult(
456
+ frame_id=offset + idx,
457
+ boxes=boxes,
458
+ keypoints=keypoints,
459
+ )
460
+ )
461
+ return results