|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from pathlib import Path |
| 5 | +from typing import Any, cast |
| 6 | + |
| 7 | +from luxonis_ml.data.exporters.exporter_utils import ExporterUtils, PreparedLDF |
| 8 | + |
| 9 | +from .base_exporter import BaseExporter |
| 10 | + |
| 11 | + |
| 12 | +class YoloV8InstanceSegmentationExporter(BaseExporter): |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + dataset_identifier: str, |
| 16 | + output_path: Path, |
| 17 | + max_partition_size_gb: float | None, |
| 18 | + ): |
| 19 | + super().__init__( |
| 20 | + dataset_identifier, output_path, max_partition_size_gb |
| 21 | + ) |
| 22 | + self.class_to_id: dict[str, int] = {} |
| 23 | + self.class_names: list[str] = [] |
| 24 | + |
| 25 | + def get_split_names(self) -> dict[str, str]: |
| 26 | + return {"train": "train", "val": "val", "test": "test"} |
| 27 | + |
| 28 | + def _yaml_filename(self) -> str: |
| 29 | + return "dataset.yaml" |
| 30 | + |
| 31 | + def supported_ann_types(self) -> list[str]: |
| 32 | + return ["instance_segmentation"] |
| 33 | + |
| 34 | + def transform(self, prepared_ldf: PreparedLDF) -> None: |
| 35 | + ExporterUtils.check_group_file_correspondence(prepared_ldf) |
| 36 | + ExporterUtils.exporter_specific_annotation_warning( |
| 37 | + prepared_ldf, self.supported_ann_types() |
| 38 | + ) |
| 39 | + |
| 40 | + annotation_splits: dict[str, dict[str, list[str]]] = { |
| 41 | + k: {} for k in self.get_split_names().values() |
| 42 | + } |
| 43 | + |
| 44 | + df = prepared_ldf.processed_df |
| 45 | + grouped = df.group_by(["file", "group_id"], maintain_order=True) |
| 46 | + copied_files: set[Path] = set() |
| 47 | + |
| 48 | + for key, group_df in grouped: |
| 49 | + file_name, group_id = cast(tuple[str, Any], key) |
| 50 | + logical_split = ExporterUtils.split_of_group( |
| 51 | + prepared_ldf, group_id |
| 52 | + ) |
| 53 | + split = self.get_split_names()[logical_split] |
| 54 | + |
| 55 | + file_path = Path(str(file_name)) |
| 56 | + idx = self.image_indices.setdefault( |
| 57 | + file_path, len(self.image_indices) |
| 58 | + ) |
| 59 | + new_name = f"{idx}{file_path.suffix}" |
| 60 | + |
| 61 | + label_lines: list[str] = [] |
| 62 | + |
| 63 | + for row in group_df.iter_rows(named=True): |
| 64 | + ttype = row["task_type"] |
| 65 | + ann_str = row["annotation"] |
| 66 | + cname = row["class_name"] |
| 67 | + |
| 68 | + if ann_str is None: |
| 69 | + continue |
| 70 | + if ttype != "instance_segmentation": |
| 71 | + continue |
| 72 | + |
| 73 | + if cname and cname not in self.class_to_id: |
| 74 | + self.class_to_id[cname] = len(self.class_to_id) |
| 75 | + self.class_names.append(cname) |
| 76 | + if not cname or cname not in self.class_to_id: |
| 77 | + continue |
| 78 | + |
| 79 | + ann = json.loads(ann_str) |
| 80 | + |
| 81 | + cid = self.class_to_id[cname] |
| 82 | + polygons = ExporterUtils.annotation_to_polygons(ann, file_path) |
| 83 | + |
| 84 | + for poly in polygons: |
| 85 | + if len(poly) < 3: |
| 86 | + continue |
| 87 | + parts = [] |
| 88 | + for x, y in poly: |
| 89 | + x_ = 0.0 if x < 0 else 1.0 if x > 1 else x |
| 90 | + y_ = 0.0 if y < 0 else 1.0 if y > 1 else y |
| 91 | + parts.append(f"{x_:.12f} {y_:.12f}") |
| 92 | + line = f"{cid} " + " ".join(parts) |
| 93 | + label_lines.append(line) |
| 94 | + |
| 95 | + annotation_splits[split][new_name] = label_lines |
| 96 | + |
| 97 | + ann_size_estimate = sum(len(s) + 1 for s in label_lines) |
| 98 | + img_size = file_path.stat().st_size |
| 99 | + annotation_splits = self._maybe_roll_partition( |
| 100 | + annotation_splits, ann_size_estimate + img_size |
| 101 | + ) |
| 102 | + |
| 103 | + data_path = self._get_data_path(self.output_path, split, self.part) |
| 104 | + data_path.mkdir(parents=True, exist_ok=True) |
| 105 | + dest = data_path / new_name |
| 106 | + if file_path not in copied_files: |
| 107 | + copied_files.add(file_path) |
| 108 | + if dest != file_path: |
| 109 | + dest.write_bytes(file_path.read_bytes()) |
| 110 | + self.current_size += img_size |
| 111 | + |
| 112 | + self._dump_annotations(annotation_splits, self.output_path, self.part) |
| 113 | + |
| 114 | + def _maybe_roll_partition( |
| 115 | + self, |
| 116 | + annotation_splits: dict[str, dict[str, list[str]]], |
| 117 | + additional_size: int, |
| 118 | + ) -> dict[str, dict[str, list[str]]]: |
| 119 | + if ( |
| 120 | + self.max_partition_size |
| 121 | + and self.part is not None |
| 122 | + and (self.current_size + additional_size) > self.max_partition_size |
| 123 | + ): |
| 124 | + self._dump_annotations( |
| 125 | + annotation_splits, self.output_path, self.part |
| 126 | + ) |
| 127 | + self.current_size = 0 |
| 128 | + self.part += 1 |
| 129 | + return {k: {} for k in self.get_split_names().values()} |
| 130 | + return annotation_splits |
| 131 | + |
| 132 | + def _dump_annotations( |
| 133 | + self, |
| 134 | + annotation_splits: dict[str, dict[str, list[str]]], |
| 135 | + output_path: Path, |
| 136 | + part: int | None = None, |
| 137 | + ) -> None: |
| 138 | + base = ( |
| 139 | + output_path / f"{self.dataset_identifier}_part{part}" |
| 140 | + if part is not None |
| 141 | + else output_path / self.dataset_identifier |
| 142 | + ) |
| 143 | + |
| 144 | + for split_name in self.get_split_names().values(): |
| 145 | + labels_dir = base / "labels" / split_name |
| 146 | + labels_dir.mkdir(parents=True, exist_ok=True) |
| 147 | + images_dir = base / "images" / split_name |
| 148 | + images_dir.mkdir(parents=True, exist_ok=True) |
| 149 | + |
| 150 | + for img_name, lines in annotation_splits.get( |
| 151 | + split_name, {} |
| 152 | + ).items(): |
| 153 | + (labels_dir / f"{Path(img_name).stem}.txt").write_text( |
| 154 | + "\n".join(lines), encoding="utf-8" |
| 155 | + ) |
| 156 | + |
| 157 | + yaml_filename = self._yaml_filename() |
| 158 | + if yaml_filename: |
| 159 | + split_dirs = self.get_split_names() |
| 160 | + yaml_obj = { |
| 161 | + "train": str(Path("images") / split_dirs["train"]), |
| 162 | + "val": str(Path("images") / split_dirs["val"]), |
| 163 | + "test": str(Path("images") / split_dirs["test"]), |
| 164 | + "nc": len(self.class_names), |
| 165 | + "names": self.class_names, |
| 166 | + } |
| 167 | + (base / yaml_filename).write_text( |
| 168 | + self._to_yaml(yaml_obj), encoding="utf-8" |
| 169 | + ) |
| 170 | + |
| 171 | + def _get_data_path( |
| 172 | + self, output_path: Path, split: str, part: int | None = None |
| 173 | + ) -> Path: |
| 174 | + base = ( |
| 175 | + output_path / f"{self.dataset_identifier}_part{part}" |
| 176 | + if part is not None |
| 177 | + else output_path / self.dataset_identifier |
| 178 | + ) |
| 179 | + return base / "images" / split |
| 180 | + |
| 181 | + @staticmethod |
| 182 | + def _to_yaml(d: dict[str, Any]) -> str: |
| 183 | + lines: list[str] = [] |
| 184 | + for k, v in d.items(): |
| 185 | + lines.append(f"{k}: {v}") |
| 186 | + return "\n".join(lines) + "\n" |
0 commit comments