Coverage for collectra/tasks/object_detection/coco_data.py: 92.23%
103 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Turning annotated images into the COCO detection dataset a trainer reads."""
3from __future__ import annotations
5import json
6import shutil
7from pathlib import Path
9from collectra.types.images import (
10 Image,
11 ImageCrop,
12 bake_orientation,
13 convert_image_to_rgb,
14 image_channel_count,
15 image_size,
16)
18from ...logger import get_logger
19from ..machine_learning.training import print_distribution_table
21logger = get_logger(__name__)
24class CocoDetectionData:
25 """Groups annotated crops by source image and writes train/valid COCO folders."""
27 def _check_distribution(
28 self,
29 classes: list[str],
30 train_samples: list[dict],
31 val_samples: list[dict],
32 ) -> None:
33 train_classes = {name: 0 for name in classes}
34 val_classes = {name: 0 for name in classes}
35 label_to_name = {index: name for index, name in enumerate(classes)}
37 for sample in train_samples:
38 for label in sample["labels"]:
39 class_name = label_to_name.get(label, "")
40 if class_name:
41 train_classes[class_name] += 1
43 for sample in val_samples:
44 for label in sample["labels"]:
45 class_name = label_to_name.get(label, "")
46 if class_name:
47 val_classes[class_name] += 1
49 def image_counts(samples: list[dict]) -> tuple[int, int]:
50 labelled = sum(1 for sample in samples if sample["labels"])
51 return labelled, len(samples) - labelled
53 print_distribution_table(
54 "Class Distribution",
55 classes,
56 train_classes,
57 val_classes,
58 train_images=image_counts(train_samples),
59 validation_images=image_counts(val_samples),
60 )
62 def _prepare_assets(
63 self,
64 classes: list[str],
65 validation_flag: str,
66 exclude_flag: str,
67 *images: ImageCrop,
68 ) -> tuple[list[dict], list[dict]]:
69 class_to_idx = {name: idx for idx, name in enumerate(classes)}
70 grouped: dict[Path, dict] = {}
72 for img in images:
73 if exclude_flag and img.partition == exclude_flag:
74 continue
76 base_img: Image | ImageCrop = img
77 if isinstance(img, ImageCrop):
78 if img.source_parent:
79 base_img = img.source_parent
80 if isinstance(img.source_parent, ImageCrop):
81 img.set_rel_to_src_parent()
83 image_path = base_img.get_path()
84 if image_path not in grouped:
85 grouped[image_path] = {
86 "image_path": image_path,
87 "partition": img.partition,
88 "boxes": [],
89 "labels": [],
90 }
92 if not isinstance(img, ImageCrop):
93 continue
94 if img.name not in class_to_idx:
95 continue
97 width, height = base_img.width, base_img.height
98 box_w = float(img.width_relative) * width
99 box_h = float(img.height_relative) * height
100 cx = float(img.x_center) * width
101 cy = float(img.y_center) * height
103 x1 = max(0.0, cx - box_w / 2.0)
104 y1 = max(0.0, cy - box_h / 2.0)
105 x2 = min(float(width), cx + box_w / 2.0)
106 y2 = min(float(height), cy + box_h / 2.0)
107 if x2 <= x1 or y2 <= y1:
108 continue
110 grouped[image_path]["boxes"].append([x1, y1, x2, y2])
111 grouped[image_path]["labels"].append(class_to_idx[img.name])
113 train_samples: list[dict] = []
114 val_samples: list[dict] = []
115 for sample in grouped.values():
116 if validation_flag and sample["partition"] == validation_flag:
117 val_samples.append(sample)
118 elif not exclude_flag or sample["partition"] != exclude_flag:
119 train_samples.append(sample)
120 return train_samples, val_samples
122 def _write_coco_dataset(
123 self,
124 train_samples: list[dict],
125 val_samples: list[dict],
126 classes: list[str],
127 dataset_dir: Path,
128 rgb: bool = False,
129 ) -> Path:
130 categories = [
131 {"id": idx, "name": name, "supercategory": "object"}
132 for idx, name in enumerate(classes)
133 ]
135 channel_counts: dict[str, int] = {}
136 for split_name, samples in [("train", train_samples), ("valid", val_samples)]:
137 split_dir = dataset_dir / split_name
138 split_dir.mkdir(parents=True, exist_ok=True)
140 images_list: list[dict] = []
141 annotations_list: list[dict] = []
142 annotation_id = 0
144 for image_id, sample in enumerate(samples):
145 src_path = Path(sample["image_path"])
146 dest_name = f"{image_id}_{src_path.name}"
147 dest_path = split_dir / dest_name
148 shutil.copy2(src_path, dest_path)
149 # RF-DETR reads raw pixels; labels are in displayed coordinates.
150 bake_orientation(dest_path)
151 if rgb:
152 convert_image_to_rgb(dest_path)
154 w, h = image_size(dest_path)
155 channel_counts[str(src_path)] = image_channel_count(dest_path)
157 images_list.append(
158 {
159 "id": image_id,
160 "file_name": dest_name,
161 "width": w,
162 "height": h,
163 }
164 )
166 for box, label in zip(sample["boxes"], sample["labels"]):
167 x1, y1, x2, y2 = box
168 coco_bbox = [x1, y1, x2 - x1, y2 - y1]
169 area = (x2 - x1) * (y2 - y1)
171 annotations_list.append(
172 {
173 "id": annotation_id,
174 "image_id": image_id,
175 "category_id": int(label),
176 "bbox": coco_bbox,
177 "area": float(area),
178 "iscrowd": 0,
179 }
180 )
181 annotation_id += 1
183 coco_json = {
184 "images": images_list,
185 "annotations": annotations_list,
186 "categories": categories,
187 }
189 annotations_path = split_dir / "_annotations.coco.json"
190 with open(annotations_path, "w") as f:
191 json.dump(coco_json, f, indent=2)
193 if len(set(channel_counts.values())) > 1:
194 details = ", ".join(
195 f"{name}: {count} channels" for name, count in channel_counts.items()
196 )
197 raise ValueError(
198 f"Inconsistent input channel counts in prepared dataset: {details}"
199 )
200 if channel_counts:
201 logger.info(
202 "Dataset images have %d channels",
203 next(iter(channel_counts.values())),
204 )
205 return dataset_dir