cv-benchkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,624 @@
1
+ """Bounding-box format converters and dataset schema translators.
2
+
3
+ Supported bbox formats
4
+ ----------------------
5
+ - **xyxy**: ``[x_min, y_min, x_max, y_max]`` (absolute pixels)
6
+ - **xywh**: ``[x_min, y_min, width, height]`` (COCO-style)
7
+ - **cxcywh**: ``[center_x, center_y, width, height]``
8
+ - **normalized / YOLO**: ``[cx, cy, w, h]`` in ``[0, 1]`` relative to image size
9
+
10
+ Supported dataset schemas
11
+ -------------------------
12
+ - COCO JSON
13
+ - YOLO txt (one ``.txt`` per image)
14
+ - Pascal VOC XML
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import xml.etree.ElementTree as ET
21
+ from collections.abc import Sequence
22
+ from pathlib import Path
23
+ from typing import Any
24
+ from xml.dom import minidom
25
+
26
+ import numpy as np
27
+ from numpy.typing import NDArray
28
+ from pydantic import BaseModel, field_validator
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Pydantic models for validation
32
+ # ---------------------------------------------------------------------------
33
+
34
+
35
+ class BBox(BaseModel):
36
+ """A single bounding box with format metadata."""
37
+
38
+ coords: list[float]
39
+ fmt: str # "xyxy" | "xywh" | "cxcywh" | "normalized"
40
+
41
+ @field_validator("coords")
42
+ @classmethod
43
+ def _four_elements(cls, v: list[float]) -> list[float]:
44
+ if len(v) != 4:
45
+ msg = f"coords must have exactly 4 elements, got {len(v)}"
46
+ raise ValueError(msg)
47
+ return v
48
+
49
+ @field_validator("fmt")
50
+ @classmethod
51
+ def _valid_fmt(cls, v: str) -> str:
52
+ allowed = {"xyxy", "xywh", "cxcywh", "normalized"}
53
+ if v not in allowed:
54
+ msg = f"fmt must be one of {allowed}, got {v!r}"
55
+ raise ValueError(msg)
56
+ return v
57
+
58
+
59
+ class COCOAnnotation(BaseModel):
60
+ """Minimal COCO annotation record."""
61
+
62
+ id: int
63
+ image_id: int
64
+ category_id: int
65
+ bbox: list[float] # xywh
66
+ area: float
67
+ iscrowd: int = 0
68
+
69
+ @field_validator("bbox")
70
+ @classmethod
71
+ def _four(cls, v: list[float]) -> list[float]:
72
+ if len(v) != 4:
73
+ msg = f"bbox must have 4 elements, got {len(v)}"
74
+ raise ValueError(msg)
75
+ return v
76
+
77
+
78
+ class COCOImage(BaseModel):
79
+ """Minimal COCO image record."""
80
+
81
+ id: int
82
+ file_name: str
83
+ width: int
84
+ height: int
85
+
86
+
87
+ class COCOCategory(BaseModel):
88
+ """Minimal COCO category record."""
89
+
90
+ id: int
91
+ name: str
92
+ supercategory: str = ""
93
+
94
+
95
+ class COCODataset(BaseModel):
96
+ """Top-level COCO dataset container."""
97
+
98
+ images: list[COCOImage]
99
+ annotations: list[COCOAnnotation]
100
+ categories: list[COCOCategory]
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Bbox format conversions (vectorized NumPy)
105
+ # ---------------------------------------------------------------------------
106
+
107
+
108
+ def xyxy_to_xywh(boxes: NDArray[np.floating[Any]]) -> NDArray[np.floating[Any]]:
109
+ """Convert ``(N, 4)`` boxes from xyxy to xywh format.
110
+
111
+ Parameters
112
+ ----------
113
+ boxes : ndarray, shape ``(N, 4)``
114
+ Each row is ``[x_min, y_min, x_max, y_max]``.
115
+
116
+ Returns
117
+ -------
118
+ ndarray, shape ``(N, 4)``
119
+ Each row is ``[x_min, y_min, width, height]``.
120
+ """
121
+ boxes = np.asarray(boxes, dtype=np.float64)
122
+ if boxes.ndim == 1:
123
+ boxes = boxes.reshape(1, 4)
124
+ if boxes.shape[0] == 0:
125
+ return np.empty((0, 4), dtype=np.float64)
126
+ out = np.empty_like(boxes)
127
+ out[:, 0] = boxes[:, 0]
128
+ out[:, 1] = boxes[:, 1]
129
+ out[:, 2] = boxes[:, 2] - boxes[:, 0]
130
+ out[:, 3] = boxes[:, 3] - boxes[:, 1]
131
+ return out
132
+
133
+
134
+ def xywh_to_xyxy(boxes: NDArray[np.floating[Any]]) -> NDArray[np.floating[Any]]:
135
+ """Convert ``(N, 4)`` boxes from xywh to xyxy format.
136
+
137
+ Parameters
138
+ ----------
139
+ boxes : ndarray, shape ``(N, 4)``
140
+ Each row is ``[x_min, y_min, width, height]``.
141
+
142
+ Returns
143
+ -------
144
+ ndarray, shape ``(N, 4)``
145
+ Each row is ``[x_min, y_min, x_max, y_max]``.
146
+ """
147
+ boxes = np.asarray(boxes, dtype=np.float64)
148
+ if boxes.ndim == 1:
149
+ boxes = boxes.reshape(1, 4)
150
+ if boxes.shape[0] == 0:
151
+ return np.empty((0, 4), dtype=np.float64)
152
+ out = np.empty_like(boxes)
153
+ out[:, 0] = boxes[:, 0]
154
+ out[:, 1] = boxes[:, 1]
155
+ out[:, 2] = boxes[:, 0] + boxes[:, 2]
156
+ out[:, 3] = boxes[:, 1] + boxes[:, 3]
157
+ return out
158
+
159
+
160
+ def xyxy_to_cxcywh(boxes: NDArray[np.floating[Any]]) -> NDArray[np.floating[Any]]:
161
+ """Convert ``(N, 4)`` boxes from xyxy to center-x/center-y/w/h format.
162
+
163
+ Parameters
164
+ ----------
165
+ boxes : ndarray, shape ``(N, 4)``
166
+ Each row is ``[x_min, y_min, x_max, y_max]``.
167
+
168
+ Returns
169
+ -------
170
+ ndarray, shape ``(N, 4)``
171
+ Each row is ``[center_x, center_y, width, height]``.
172
+ """
173
+ boxes = np.asarray(boxes, dtype=np.float64)
174
+ if boxes.ndim == 1:
175
+ boxes = boxes.reshape(1, 4)
176
+ if boxes.shape[0] == 0:
177
+ return np.empty((0, 4), dtype=np.float64)
178
+ out = np.empty_like(boxes)
179
+ out[:, 2] = boxes[:, 2] - boxes[:, 0] # width
180
+ out[:, 3] = boxes[:, 3] - boxes[:, 1] # height
181
+ out[:, 0] = boxes[:, 0] + out[:, 2] / 2 # cx
182
+ out[:, 1] = boxes[:, 1] + out[:, 3] / 2 # cy
183
+ return out
184
+
185
+
186
+ def cxcywh_to_xyxy(boxes: NDArray[np.floating[Any]]) -> NDArray[np.floating[Any]]:
187
+ """Convert ``(N, 4)`` boxes from center-x/center-y/w/h to xyxy.
188
+
189
+ Parameters
190
+ ----------
191
+ boxes : ndarray, shape ``(N, 4)``
192
+ Each row is ``[center_x, center_y, width, height]``.
193
+
194
+ Returns
195
+ -------
196
+ ndarray, shape ``(N, 4)``
197
+ Each row is ``[x_min, y_min, x_max, y_max]``.
198
+ """
199
+ boxes = np.asarray(boxes, dtype=np.float64)
200
+ if boxes.ndim == 1:
201
+ boxes = boxes.reshape(1, 4)
202
+ if boxes.shape[0] == 0:
203
+ return np.empty((0, 4), dtype=np.float64)
204
+ out = np.empty_like(boxes)
205
+ half_w = boxes[:, 2] / 2
206
+ half_h = boxes[:, 3] / 2
207
+ out[:, 0] = boxes[:, 0] - half_w
208
+ out[:, 1] = boxes[:, 1] - half_h
209
+ out[:, 2] = boxes[:, 0] + half_w
210
+ out[:, 3] = boxes[:, 1] + half_h
211
+ return out
212
+
213
+
214
+ def xyxy_to_normalized(
215
+ boxes: NDArray[np.floating[Any]],
216
+ img_w: int,
217
+ img_h: int,
218
+ ) -> NDArray[np.floating[Any]]:
219
+ """Convert ``(N, 4)`` xyxy boxes to normalized YOLO ``[cx, cy, w, h]``.
220
+
221
+ Parameters
222
+ ----------
223
+ boxes : ndarray, shape ``(N, 4)``
224
+ Absolute-pixel xyxy boxes.
225
+ img_w : int
226
+ Image width in pixels.
227
+ img_h : int
228
+ Image height in pixels.
229
+
230
+ Returns
231
+ -------
232
+ ndarray, shape ``(N, 4)``
233
+ Normalized ``[cx, cy, w, h]`` in ``[0, 1]``.
234
+ """
235
+ if img_w <= 0 or img_h <= 0:
236
+ msg = f"img_w and img_h must be positive integers, got img_w={img_w}, img_h={img_h}"
237
+ raise ValueError(msg)
238
+ boxes = np.asarray(boxes, dtype=np.float64)
239
+ if boxes.ndim == 1:
240
+ boxes = boxes.reshape(1, 4)
241
+ if boxes.shape[0] == 0:
242
+ return np.empty((0, 4), dtype=np.float64)
243
+ cxcywh = xyxy_to_cxcywh(boxes)
244
+ cxcywh[:, 0] /= img_w
245
+ cxcywh[:, 1] /= img_h
246
+ cxcywh[:, 2] /= img_w
247
+ cxcywh[:, 3] /= img_h
248
+ return cxcywh
249
+
250
+
251
+ def normalized_to_xyxy(
252
+ boxes: NDArray[np.floating[Any]],
253
+ img_w: int,
254
+ img_h: int,
255
+ ) -> NDArray[np.floating[Any]]:
256
+ """Convert ``(N, 4)`` normalized YOLO boxes to absolute-pixel xyxy.
257
+
258
+ Parameters
259
+ ----------
260
+ boxes : ndarray, shape ``(N, 4)``
261
+ Normalized ``[cx, cy, w, h]`` in ``[0, 1]``.
262
+ img_w : int
263
+ Image width in pixels.
264
+ img_h : int
265
+ Image height in pixels.
266
+
267
+ Returns
268
+ -------
269
+ ndarray, shape ``(N, 4)``
270
+ Absolute-pixel xyxy boxes.
271
+ """
272
+ if img_w <= 0 or img_h <= 0:
273
+ msg = f"img_w and img_h must be positive integers, got img_w={img_w}, img_h={img_h}"
274
+ raise ValueError(msg)
275
+ boxes = np.asarray(boxes, dtype=np.float64)
276
+ if boxes.ndim == 1:
277
+ boxes = boxes.reshape(1, 4)
278
+ if boxes.shape[0] == 0:
279
+ return np.empty((0, 4), dtype=np.float64)
280
+ denorm = boxes.copy()
281
+ denorm[:, 0] *= img_w
282
+ denorm[:, 1] *= img_h
283
+ denorm[:, 2] *= img_w
284
+ denorm[:, 3] *= img_h
285
+ return cxcywh_to_xyxy(denorm)
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # Dataset schema translators
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ def coco_to_yolo(
294
+ coco: COCODataset,
295
+ output_dir: Path | str,
296
+ *,
297
+ category_map: dict[int, int] | None = None,
298
+ ) -> list[Path]:
299
+ """Convert a COCO dataset to YOLO txt files.
300
+
301
+ Parameters
302
+ ----------
303
+ coco : COCODataset
304
+ Validated COCO dataset.
305
+ output_dir : Path | str
306
+ Directory for output ``.txt`` files (one per image).
307
+ category_map : dict[int, int] | None
308
+ Optional mapping from COCO category ID → YOLO class index.
309
+ If ``None``, a zero-based mapping is built from ``coco.categories``.
310
+
311
+ Returns
312
+ -------
313
+ list[Path]
314
+ Paths of the written label files.
315
+ """
316
+ output_dir = Path(output_dir)
317
+ output_dir.mkdir(parents=True, exist_ok=True)
318
+
319
+ if category_map is None:
320
+ category_map = {c.id: i for i, c in enumerate(sorted(coco.categories, key=lambda c: c.id))}
321
+
322
+ {img.id: img for img in coco.images}
323
+ anns_by_image: dict[int, list[COCOAnnotation]] = {}
324
+ for ann in coco.annotations:
325
+ anns_by_image.setdefault(ann.image_id, []).append(ann)
326
+
327
+ written: list[Path] = []
328
+ for img in coco.images:
329
+ stem = Path(img.file_name).stem
330
+ txt_path = output_dir / f"{stem}.txt"
331
+ lines: list[str] = []
332
+ for ann in anns_by_image.get(img.id, []):
333
+ cls_id = category_map.get(ann.category_id, ann.category_id)
334
+ x, y, w, h = ann.bbox
335
+ cx = (x + w / 2) / img.width
336
+ cy = (y + h / 2) / img.height
337
+ nw = w / img.width
338
+ nh = h / img.height
339
+ lines.append(f"{cls_id} {cx:.6f} {cy:.6f} {nw:.6f} {nh:.6f}")
340
+ txt_path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
341
+ written.append(txt_path)
342
+ return written
343
+
344
+
345
+ def yolo_to_coco(
346
+ label_dir: Path | str,
347
+ image_sizes: dict[str, tuple[int, int]],
348
+ category_names: Sequence[str],
349
+ ) -> COCODataset:
350
+ """Convert YOLO txt labels to a COCO dataset object.
351
+
352
+ Parameters
353
+ ----------
354
+ label_dir : Path | str
355
+ Directory containing ``.txt`` label files.
356
+ image_sizes : dict[str, tuple[int, int]]
357
+ Mapping of image stem → ``(width, height)``.
358
+ category_names : Sequence[str]
359
+ Ordered list of category names (index = class id).
360
+
361
+ Returns
362
+ -------
363
+ COCODataset
364
+ Validated COCO dataset.
365
+ """
366
+ label_dir = Path(label_dir)
367
+ images: list[COCOImage] = []
368
+ annotations: list[COCOAnnotation] = []
369
+ categories = [COCOCategory(id=i, name=name) for i, name in enumerate(category_names)]
370
+
371
+ ann_id = 1
372
+ for img_id, (stem, (w, h)) in enumerate(sorted(image_sizes.items()), start=1):
373
+ images.append(COCOImage(id=img_id, file_name=f"{stem}.jpg", width=w, height=h))
374
+ txt_path = label_dir / f"{stem}.txt"
375
+ if not txt_path.exists():
376
+ continue
377
+ for line in txt_path.read_text(encoding="utf-8").strip().splitlines():
378
+ parts = line.strip().split()
379
+ if len(parts) != 5:
380
+ continue
381
+ cls_id = int(parts[0])
382
+ cx, cy, nw, nh = (float(p) for p in parts[1:])
383
+ abs_w = nw * w
384
+ abs_h = nh * h
385
+ abs_x = cx * w - abs_w / 2
386
+ abs_y = cy * h - abs_h / 2
387
+ annotations.append(
388
+ COCOAnnotation(
389
+ id=ann_id,
390
+ image_id=img_id,
391
+ category_id=cls_id,
392
+ bbox=[abs_x, abs_y, abs_w, abs_h],
393
+ area=abs_w * abs_h,
394
+ )
395
+ )
396
+ ann_id += 1
397
+
398
+ return COCODataset(images=images, annotations=annotations, categories=categories)
399
+
400
+
401
+ def coco_to_voc(
402
+ coco: COCODataset,
403
+ output_dir: Path | str,
404
+ ) -> list[Path]:
405
+ """Convert a COCO dataset to Pascal VOC XML files.
406
+
407
+ Parameters
408
+ ----------
409
+ coco : COCODataset
410
+ Validated COCO dataset.
411
+ output_dir : Path | str
412
+ Directory for output ``.xml`` files.
413
+
414
+ Returns
415
+ -------
416
+ list[Path]
417
+ Paths of the written XML files.
418
+ """
419
+ output_dir = Path(output_dir)
420
+ output_dir.mkdir(parents=True, exist_ok=True)
421
+
422
+ cat_lookup: dict[int, str] = {c.id: c.name for c in coco.categories}
423
+ anns_by_image: dict[int, list[COCOAnnotation]] = {}
424
+ for ann in coco.annotations:
425
+ anns_by_image.setdefault(ann.image_id, []).append(ann)
426
+
427
+ written: list[Path] = []
428
+ for img in coco.images:
429
+ root = ET.Element("annotation")
430
+ ET.SubElement(root, "filename").text = img.file_name
431
+
432
+ size_el = ET.SubElement(root, "size")
433
+ ET.SubElement(size_el, "width").text = str(img.width)
434
+ ET.SubElement(size_el, "height").text = str(img.height)
435
+ ET.SubElement(size_el, "depth").text = "3"
436
+
437
+ for ann in anns_by_image.get(img.id, []):
438
+ obj = ET.SubElement(root, "object")
439
+ ET.SubElement(obj, "name").text = cat_lookup.get(ann.category_id, "unknown")
440
+ ET.SubElement(obj, "difficult").text = "0"
441
+ bndbox = ET.SubElement(obj, "bndbox")
442
+ x, y, w, h = ann.bbox
443
+ ET.SubElement(bndbox, "xmin").text = str(round(x))
444
+ ET.SubElement(bndbox, "ymin").text = str(round(y))
445
+ ET.SubElement(bndbox, "xmax").text = str(round(x + w))
446
+ ET.SubElement(bndbox, "ymax").text = str(round(y + h))
447
+
448
+ xml_str = minidom.parseString(ET.tostring(root, encoding="unicode")).toprettyxml(
449
+ indent=" "
450
+ )
451
+ stem = Path(img.file_name).stem
452
+ xml_path = output_dir / f"{stem}.xml"
453
+ xml_path.write_text(xml_str, encoding="utf-8")
454
+ written.append(xml_path)
455
+ return written
456
+
457
+
458
+ def _safe_int(el: ET.Element | None, tag: str, default: int = 0) -> int:
459
+ if el is None:
460
+ return default
461
+ child = el.find(tag)
462
+ if child is None or child.text is None:
463
+ return default
464
+ try:
465
+ return int(child.text)
466
+ except ValueError:
467
+ return default
468
+
469
+
470
+ def _safe_float(el: ET.Element | None, tag: str, default: float = 0.0) -> float:
471
+ if el is None:
472
+ return default
473
+ child = el.find(tag)
474
+ if child is None or child.text is None:
475
+ return default
476
+ try:
477
+ return float(child.text)
478
+ except ValueError:
479
+ return default
480
+
481
+
482
+ def voc_to_coco(
483
+ xml_dir: Path | str,
484
+ category_names: Sequence[str],
485
+ ) -> COCODataset:
486
+ """Convert Pascal VOC XML files to a COCO dataset object.
487
+
488
+ Parameters
489
+ ----------
490
+ xml_dir : Path | str
491
+ Directory containing ``.xml`` annotation files.
492
+ category_names : Sequence[str]
493
+ Ordered list of category names. The name in VOC ``<name>`` is looked up
494
+ here to determine the ``category_id``.
495
+
496
+ Returns
497
+ -------
498
+ COCODataset
499
+ Validated COCO dataset.
500
+ """
501
+ xml_dir = Path(xml_dir)
502
+ name_to_id = {name: i for i, name in enumerate(category_names)}
503
+ categories = [COCOCategory(id=i, name=name) for i, name in enumerate(category_names)]
504
+
505
+ images: list[COCOImage] = []
506
+ annotations: list[COCOAnnotation] = []
507
+ ann_id = 1
508
+
509
+ for img_id, xml_path in enumerate(sorted(xml_dir.glob("*.xml")), start=1):
510
+ tree = ET.parse(xml_path)
511
+ root_el = tree.getroot()
512
+
513
+ filename_el = root_el.find("filename")
514
+ filename = filename_el.text if filename_el is not None and filename_el.text else ""
515
+
516
+ size_el = root_el.find("size")
517
+ w = _safe_int(size_el, "width")
518
+ h = _safe_int(size_el, "height")
519
+
520
+ images.append(COCOImage(id=img_id, file_name=filename, width=w, height=h))
521
+
522
+ for obj in root_el.findall("object"):
523
+ name_el = obj.find("name")
524
+ name = name_el.text if name_el is not None and name_el.text else "unknown"
525
+ cat_id = name_to_id.get(name, 0)
526
+
527
+ bndbox = obj.find("bndbox")
528
+ if bndbox is None:
529
+ continue
530
+ xmin = _safe_float(bndbox, "xmin")
531
+ ymin = _safe_float(bndbox, "ymin")
532
+ xmax = _safe_float(bndbox, "xmax")
533
+ ymax = _safe_float(bndbox, "ymax")
534
+
535
+ bw = xmax - xmin
536
+ bh = ymax - ymin
537
+ annotations.append(
538
+ COCOAnnotation(
539
+ id=ann_id,
540
+ image_id=img_id,
541
+ category_id=cat_id,
542
+ bbox=[xmin, ymin, bw, bh],
543
+ area=bw * bh,
544
+ )
545
+ )
546
+ ann_id += 1
547
+
548
+ return COCODataset(images=images, annotations=annotations, categories=categories)
549
+
550
+
551
+ def voc_to_yolo(
552
+ xml_dir: Path | str,
553
+ output_dir: Path | str,
554
+ category_names: Sequence[str],
555
+ ) -> list[Path]:
556
+ """Convert Pascal VOC XML annotations to YOLO txt labels.
557
+
558
+ Parameters
559
+ ----------
560
+ xml_dir : Path | str
561
+ Directory containing ``.xml`` annotation files.
562
+ output_dir : Path | str
563
+ Directory for output ``.txt`` label files.
564
+ category_names : Sequence[str]
565
+ Ordered list of category names (index = class id).
566
+
567
+ Returns
568
+ -------
569
+ list[Path]
570
+ Paths of the written label files.
571
+ """
572
+ coco = voc_to_coco(xml_dir, category_names)
573
+ return coco_to_yolo(coco, output_dir)
574
+
575
+
576
+ def yolo_to_voc(
577
+ label_dir: Path | str,
578
+ output_dir: Path | str,
579
+ image_sizes: dict[str, tuple[int, int]],
580
+ category_names: Sequence[str],
581
+ ) -> list[Path]:
582
+ """Convert YOLO txt labels to Pascal VOC XML annotations.
583
+
584
+ Parameters
585
+ ----------
586
+ label_dir : Path | str
587
+ Directory containing ``.txt`` label files.
588
+ output_dir : Path | str
589
+ Directory for output ``.xml`` files.
590
+ image_sizes : dict[str, tuple[int, int]]
591
+ Mapping of image stem → ``(width, height)``.
592
+ category_names : Sequence[str]
593
+ Ordered list of category names (index = class id).
594
+
595
+ Returns
596
+ -------
597
+ list[Path]
598
+ Paths of the written XML files.
599
+ """
600
+ coco = yolo_to_coco(label_dir, image_sizes, category_names)
601
+ return coco_to_voc(coco, output_dir)
602
+
603
+
604
+ def validate_coco_file(path: Path | str) -> COCODataset:
605
+ """Load and validate a COCO JSON file.
606
+
607
+ Parameters
608
+ ----------
609
+ path : Path | str
610
+ Path to the COCO JSON file.
611
+
612
+ Returns
613
+ -------
614
+ COCODataset
615
+ Validated COCO dataset.
616
+
617
+ Raises
618
+ ------
619
+ pydantic.ValidationError
620
+ If the JSON does not match the expected schema.
621
+ """
622
+ path = Path(path)
623
+ data: dict[str, Any] = json.loads(path.read_text(encoding="utf-8"))
624
+ return COCODataset(**data)