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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Validate LEVIR-Ship, create leakage-safe splits, and export COCO JSON.
|
| 3 |
+
|
| 4 |
+
Expected input layout::
|
| 5 |
+
|
| 6 |
+
DATA_ROOT/
|
| 7 |
+
├── All Images/ # PNG images
|
| 8 |
+
└── All Annotations/ # YOLO TXT labels with matching basenames
|
| 9 |
+
|
| 10 |
+
The script does not copy images. COCO ``file_name`` values remain basenames, so
|
| 11 |
+
MMDetection should point ``data_prefix.img`` at ``DATA_ROOT/All Images``.
|
| 12 |
+
|
| 13 |
+
Typical live-marimo usage after downloading the dataset into ``/marimo``::
|
| 14 |
+
|
| 15 |
+
cd /marimo
|
| 16 |
+
python preprocess_data.py --data-root . --verify-only
|
| 17 |
+
python preprocess_data.py --data-root .
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import math
|
| 25 |
+
import random
|
| 26 |
+
import re
|
| 27 |
+
from collections import defaultdict
|
| 28 |
+
from dataclasses import dataclass
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
from typing import Iterable
|
| 31 |
+
|
| 32 |
+
from PIL import Image
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
SPLIT_NAMES = ("train", "val", "test")
|
| 36 |
+
SCENE_RE = re.compile(r"^(.*)_(-?\d+)_(-?\d+)$")
|
| 37 |
+
PRODUCT_VARIANT_RE = re.compile(r"-\d+$")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass(frozen=True)
|
| 41 |
+
class Sample:
|
| 42 |
+
image_path: Path
|
| 43 |
+
annotation_path: Path
|
| 44 |
+
scene: str
|
| 45 |
+
product: str
|
| 46 |
+
width: int
|
| 47 |
+
height: int
|
| 48 |
+
boxes: tuple[tuple[float, float, float, float], ...]
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def is_positive(self) -> bool:
|
| 52 |
+
return bool(self.boxes)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass(frozen=True)
|
| 56 |
+
class GroupStats:
|
| 57 |
+
images: int
|
| 58 |
+
positives: int
|
| 59 |
+
boxes: int
|
| 60 |
+
|
| 61 |
+
def __add__(self, other: "GroupStats") -> "GroupStats":
|
| 62 |
+
return GroupStats(
|
| 63 |
+
images=self.images + other.images,
|
| 64 |
+
positives=self.positives + other.positives,
|
| 65 |
+
boxes=self.boxes + other.boxes,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
ZERO_STATS = GroupStats(images=0, positives=0, boxes=0)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def resolve_path(value: str | Path) -> Path:
|
| 73 |
+
"""Resolve CLI paths relative to the current working directory."""
|
| 74 |
+
path = Path(value).expanduser()
|
| 75 |
+
return path.resolve() if path.is_absolute() else (Path.cwd() / path).resolve()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def parse_scene_and_product(image_path: Path) -> tuple[str, str]:
|
| 79 |
+
"""Return the tile's scene variant and core source-product identifier."""
|
| 80 |
+
match = SCENE_RE.match(image_path.stem)
|
| 81 |
+
if not match:
|
| 82 |
+
raise ValueError(
|
| 83 |
+
"Cannot extract source scene and tile coordinates from "
|
| 84 |
+
f"{image_path.name}"
|
| 85 |
+
)
|
| 86 |
+
scene = match.group(1)
|
| 87 |
+
product = PRODUCT_VARIANT_RE.sub("", scene)
|
| 88 |
+
return scene, product
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def parse_yolo_boxes(
|
| 92 |
+
annotation_path: Path, width: int, height: int
|
| 93 |
+
) -> tuple[tuple[float, float, float, float], ...]:
|
| 94 |
+
"""Parse one single-class YOLO file into float COCO ``xywh`` boxes."""
|
| 95 |
+
boxes: list[tuple[float, float, float, float]] = []
|
| 96 |
+
seen: set[tuple[float, float, float, float, float]] = set()
|
| 97 |
+
|
| 98 |
+
for line_number, raw_line in enumerate(
|
| 99 |
+
annotation_path.read_text(encoding="utf-8").splitlines(), 1
|
| 100 |
+
):
|
| 101 |
+
line = raw_line.strip()
|
| 102 |
+
if not line:
|
| 103 |
+
continue
|
| 104 |
+
parts = line.split()
|
| 105 |
+
if len(parts) != 5:
|
| 106 |
+
raise ValueError(
|
| 107 |
+
f"{annotation_path}:{line_number}: expected 5 YOLO values, "
|
| 108 |
+
f"got {len(parts)}"
|
| 109 |
+
)
|
| 110 |
+
try:
|
| 111 |
+
class_id, cx, cy, box_width, box_height = map(float, parts)
|
| 112 |
+
except ValueError as exc:
|
| 113 |
+
raise ValueError(
|
| 114 |
+
f"{annotation_path}:{line_number}: non-numeric YOLO value"
|
| 115 |
+
) from exc
|
| 116 |
+
|
| 117 |
+
values = (class_id, cx, cy, box_width, box_height)
|
| 118 |
+
if not all(math.isfinite(value) for value in values):
|
| 119 |
+
raise ValueError(
|
| 120 |
+
f"{annotation_path}:{line_number}: non-finite YOLO value"
|
| 121 |
+
)
|
| 122 |
+
if class_id != 0:
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"{annotation_path}:{line_number}: expected class 0, "
|
| 125 |
+
f"got {class_id:g}"
|
| 126 |
+
)
|
| 127 |
+
if not (0.0 <= cx <= 1.0 and 0.0 <= cy <= 1.0):
|
| 128 |
+
raise ValueError(
|
| 129 |
+
f"{annotation_path}:{line_number}: center is outside [0, 1]"
|
| 130 |
+
)
|
| 131 |
+
if box_width <= 0.0 or box_height <= 0.0:
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"{annotation_path}:{line_number}: width and height must be positive"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
x1_raw = (cx - box_width / 2.0) * width
|
| 137 |
+
y1_raw = (cy - box_height / 2.0) * height
|
| 138 |
+
x2_raw = (cx + box_width / 2.0) * width
|
| 139 |
+
y2_raw = (cy + box_height / 2.0) * height
|
| 140 |
+
tolerance = 1e-6
|
| 141 |
+
if (
|
| 142 |
+
x1_raw < -tolerance
|
| 143 |
+
or y1_raw < -tolerance
|
| 144 |
+
or x2_raw > width + tolerance
|
| 145 |
+
or y2_raw > height + tolerance
|
| 146 |
+
):
|
| 147 |
+
raise ValueError(
|
| 148 |
+
f"{annotation_path}:{line_number}: bounding box exceeds image bounds"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
x1 = max(0.0, x1_raw)
|
| 152 |
+
y1 = max(0.0, y1_raw)
|
| 153 |
+
x2 = min(float(width), x2_raw)
|
| 154 |
+
y2 = min(float(height), y2_raw)
|
| 155 |
+
if x2 <= x1 or y2 <= y1:
|
| 156 |
+
raise ValueError(
|
| 157 |
+
f"{annotation_path}:{line_number}: invalid bounding box"
|
| 158 |
+
)
|
| 159 |
+
if values in seen:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"{annotation_path}:{line_number}: duplicate annotation line"
|
| 162 |
+
)
|
| 163 |
+
seen.add(values)
|
| 164 |
+
boxes.append((x1, y1, x2 - x1, y2 - y1))
|
| 165 |
+
|
| 166 |
+
return tuple(boxes)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def discover_samples(
|
| 170 |
+
data_root: Path,
|
| 171 |
+
image_dir_name: str = "All Images",
|
| 172 |
+
annotation_dir_name: str = "All Annotations",
|
| 173 |
+
) -> list[Sample]:
|
| 174 |
+
"""Validate all image-label pairs and return parsed samples."""
|
| 175 |
+
image_dir = data_root / image_dir_name
|
| 176 |
+
annotation_dir = data_root / annotation_dir_name
|
| 177 |
+
if not image_dir.is_dir() or not annotation_dir.is_dir():
|
| 178 |
+
raise FileNotFoundError(
|
| 179 |
+
f"Expected '{image_dir_name}' and '{annotation_dir_name}' under "
|
| 180 |
+
f"{data_root}"
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
image_paths = sorted(image_dir.glob("*.png"), key=lambda path: path.name)
|
| 184 |
+
annotation_paths = sorted(
|
| 185 |
+
annotation_dir.glob("*.txt"), key=lambda path: path.name
|
| 186 |
+
)
|
| 187 |
+
if not image_paths:
|
| 188 |
+
raise ValueError(f"No PNG images found in {image_dir}")
|
| 189 |
+
|
| 190 |
+
image_stems = {path.stem for path in image_paths}
|
| 191 |
+
annotation_stems = {path.stem for path in annotation_paths}
|
| 192 |
+
missing_annotations = sorted(image_stems - annotation_stems)
|
| 193 |
+
orphan_annotations = sorted(annotation_stems - image_stems)
|
| 194 |
+
if missing_annotations or orphan_annotations:
|
| 195 |
+
details = []
|
| 196 |
+
if missing_annotations:
|
| 197 |
+
details.append(
|
| 198 |
+
f"{len(missing_annotations)} images without labels "
|
| 199 |
+
f"(first: {missing_annotations[0]}.png)"
|
| 200 |
+
)
|
| 201 |
+
if orphan_annotations:
|
| 202 |
+
details.append(
|
| 203 |
+
f"{len(orphan_annotations)} labels without images "
|
| 204 |
+
f"(first: {orphan_annotations[0]}.txt)"
|
| 205 |
+
)
|
| 206 |
+
raise ValueError("; ".join(details))
|
| 207 |
+
|
| 208 |
+
samples: list[Sample] = []
|
| 209 |
+
for image_path in image_paths:
|
| 210 |
+
annotation_path = annotation_dir / f"{image_path.stem}.txt"
|
| 211 |
+
scene, product = parse_scene_and_product(image_path)
|
| 212 |
+
try:
|
| 213 |
+
with Image.open(image_path) as image:
|
| 214 |
+
width, height = image.size
|
| 215 |
+
mode = image.mode
|
| 216 |
+
image.verify()
|
| 217 |
+
except Exception as exc:
|
| 218 |
+
raise ValueError(f"Cannot verify image {image_path}") from exc
|
| 219 |
+
if mode != "RGB":
|
| 220 |
+
raise ValueError(f"Expected RGB image, got {mode} for {image_path}")
|
| 221 |
+
boxes = parse_yolo_boxes(annotation_path, width, height)
|
| 222 |
+
samples.append(
|
| 223 |
+
Sample(
|
| 224 |
+
image_path=image_path,
|
| 225 |
+
annotation_path=annotation_path,
|
| 226 |
+
scene=scene,
|
| 227 |
+
product=product,
|
| 228 |
+
width=width,
|
| 229 |
+
height=height,
|
| 230 |
+
boxes=boxes,
|
| 231 |
+
)
|
| 232 |
+
)
|
| 233 |
+
return samples
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def sample_stats(samples: Iterable[Sample]) -> GroupStats:
|
| 237 |
+
sample_list = list(samples)
|
| 238 |
+
return GroupStats(
|
| 239 |
+
images=len(sample_list),
|
| 240 |
+
positives=sum(sample.is_positive for sample in sample_list),
|
| 241 |
+
boxes=sum(len(sample.boxes) for sample in sample_list),
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def validate_ratios(ratios: dict[str, float]) -> None:
|
| 246 |
+
if set(ratios) != set(SPLIT_NAMES):
|
| 247 |
+
raise ValueError(f"Ratios must define exactly: {', '.join(SPLIT_NAMES)}")
|
| 248 |
+
if any(value <= 0.0 for value in ratios.values()):
|
| 249 |
+
raise ValueError("All split ratios must be positive")
|
| 250 |
+
if not math.isclose(sum(ratios.values()), 1.0, rel_tol=0.0, abs_tol=1e-9):
|
| 251 |
+
raise ValueError(f"Split ratios must sum to 1, got {sum(ratios.values())}")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def split_samples(
|
| 255 |
+
samples: list[Sample],
|
| 256 |
+
*,
|
| 257 |
+
ratios: dict[str, float],
|
| 258 |
+
seed: int,
|
| 259 |
+
group_level: str = "product",
|
| 260 |
+
) -> dict[str, list[Sample]]:
|
| 261 |
+
"""Greedily balance images, positives, and boxes without group leakage."""
|
| 262 |
+
validate_ratios(ratios)
|
| 263 |
+
if group_level not in {"product", "scene"}:
|
| 264 |
+
raise ValueError("group_level must be 'product' or 'scene'")
|
| 265 |
+
|
| 266 |
+
groups: dict[str, list[Sample]] = defaultdict(list)
|
| 267 |
+
for sample in samples:
|
| 268 |
+
key = sample.product if group_level == "product" else sample.scene
|
| 269 |
+
groups[key].append(sample)
|
| 270 |
+
if len(groups) < len(SPLIT_NAMES):
|
| 271 |
+
raise ValueError(
|
| 272 |
+
f"Need at least {len(SPLIT_NAMES)} groups, found {len(groups)}"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
total = sample_stats(samples)
|
| 276 |
+
targets = {
|
| 277 |
+
split: GroupStats(
|
| 278 |
+
images=max(1.0, total.images * ratios[split]),
|
| 279 |
+
positives=max(1.0, total.positives * ratios[split]),
|
| 280 |
+
boxes=max(1.0, total.boxes * ratios[split]),
|
| 281 |
+
)
|
| 282 |
+
for split in SPLIT_NAMES
|
| 283 |
+
}
|
| 284 |
+
group_items = [(name, group, sample_stats(group)) for name, group in groups.items()]
|
| 285 |
+
rng = random.Random(seed)
|
| 286 |
+
rng.shuffle(group_items)
|
| 287 |
+
group_items.sort(
|
| 288 |
+
key=lambda item: (
|
| 289 |
+
item[2].images / max(total.images, 1),
|
| 290 |
+
item[2].positives / max(total.positives, 1),
|
| 291 |
+
item[2].boxes / max(total.boxes, 1),
|
| 292 |
+
),
|
| 293 |
+
reverse=True,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
counts = {split: ZERO_STATS for split in SPLIT_NAMES}
|
| 297 |
+
raw_capacities = {
|
| 298 |
+
split: len(groups) * ratios[split] for split in SPLIT_NAMES
|
| 299 |
+
}
|
| 300 |
+
group_capacities = {
|
| 301 |
+
split: math.floor(raw_capacities[split]) for split in SPLIT_NAMES
|
| 302 |
+
}
|
| 303 |
+
unassigned_slots = len(groups) - sum(group_capacities.values())
|
| 304 |
+
capacity_order = sorted(
|
| 305 |
+
SPLIT_NAMES,
|
| 306 |
+
key=lambda split: (
|
| 307 |
+
raw_capacities[split] - group_capacities[split],
|
| 308 |
+
-SPLIT_NAMES.index(split),
|
| 309 |
+
),
|
| 310 |
+
reverse=True,
|
| 311 |
+
)
|
| 312 |
+
for split in capacity_order[:unassigned_slots]:
|
| 313 |
+
group_capacities[split] += 1
|
| 314 |
+
assigned_group_counts = {split: 0 for split in SPLIT_NAMES}
|
| 315 |
+
assignments: dict[str, str] = {}
|
| 316 |
+
|
| 317 |
+
def objective(candidate: str, group_stats: GroupStats) -> float:
|
| 318 |
+
projected = dict(counts)
|
| 319 |
+
projected[candidate] = projected[candidate] + group_stats
|
| 320 |
+
score = 0.0
|
| 321 |
+
for split in SPLIT_NAMES:
|
| 322 |
+
for metric, weight in (
|
| 323 |
+
("images", 1.0),
|
| 324 |
+
("positives", 1.0),
|
| 325 |
+
("boxes", 0.5),
|
| 326 |
+
):
|
| 327 |
+
target = float(getattr(targets[split], metric))
|
| 328 |
+
delta = (getattr(projected[split], metric) - target) / target
|
| 329 |
+
score += weight * delta * delta
|
| 330 |
+
return score
|
| 331 |
+
|
| 332 |
+
for group_name, _, group_stats in group_items:
|
| 333 |
+
eligible_splits = [
|
| 334 |
+
split
|
| 335 |
+
for split in SPLIT_NAMES
|
| 336 |
+
if assigned_group_counts[split] < group_capacities[split]
|
| 337 |
+
]
|
| 338 |
+
split = min(
|
| 339 |
+
eligible_splits,
|
| 340 |
+
key=lambda name: (objective(name, group_stats), SPLIT_NAMES.index(name)),
|
| 341 |
+
)
|
| 342 |
+
assignments[group_name] = split
|
| 343 |
+
counts[split] = counts[split] + group_stats
|
| 344 |
+
assigned_group_counts[split] += 1
|
| 345 |
+
|
| 346 |
+
output = {split: [] for split in SPLIT_NAMES}
|
| 347 |
+
for group_name, group, _ in group_items:
|
| 348 |
+
output[assignments[group_name]].extend(group)
|
| 349 |
+
for split in SPLIT_NAMES:
|
| 350 |
+
output[split].sort(key=lambda sample: sample.image_path.name)
|
| 351 |
+
if not output[split]:
|
| 352 |
+
raise AssertionError(f"Split '{split}' is empty")
|
| 353 |
+
|
| 354 |
+
assert_no_group_leakage(output, group_level)
|
| 355 |
+
return output
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def assert_no_group_leakage(
|
| 359 |
+
split_samples: dict[str, list[Sample]], group_level: str
|
| 360 |
+
) -> None:
|
| 361 |
+
group_sets = {}
|
| 362 |
+
for split, samples in split_samples.items():
|
| 363 |
+
group_sets[split] = {
|
| 364 |
+
sample.product if group_level == "product" else sample.scene
|
| 365 |
+
for sample in samples
|
| 366 |
+
}
|
| 367 |
+
for index, left in enumerate(SPLIT_NAMES):
|
| 368 |
+
for right in SPLIT_NAMES[index + 1 :]:
|
| 369 |
+
overlap = group_sets[left] & group_sets[right]
|
| 370 |
+
if overlap:
|
| 371 |
+
example = sorted(overlap)[0]
|
| 372 |
+
raise AssertionError(
|
| 373 |
+
f"{group_level} leakage between {left} and {right}: {example}"
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def build_coco_payload(
|
| 378 |
+
samples: list[Sample], *, seed: int, group_level: str
|
| 379 |
+
) -> dict[str, object]:
|
| 380 |
+
images: list[dict[str, object]] = []
|
| 381 |
+
annotations: list[dict[str, object]] = []
|
| 382 |
+
annotation_id = 1
|
| 383 |
+
for image_id, sample in enumerate(samples, 1):
|
| 384 |
+
images.append(
|
| 385 |
+
{
|
| 386 |
+
"id": image_id,
|
| 387 |
+
"file_name": sample.image_path.name,
|
| 388 |
+
"width": sample.width,
|
| 389 |
+
"height": sample.height,
|
| 390 |
+
}
|
| 391 |
+
)
|
| 392 |
+
for x, y, width, height in sample.boxes:
|
| 393 |
+
annotations.append(
|
| 394 |
+
{
|
| 395 |
+
"id": annotation_id,
|
| 396 |
+
"image_id": image_id,
|
| 397 |
+
"category_id": 1,
|
| 398 |
+
"bbox": [x, y, width, height],
|
| 399 |
+
"area": width * height,
|
| 400 |
+
"iscrowd": 0,
|
| 401 |
+
"segmentation": [],
|
| 402 |
+
}
|
| 403 |
+
)
|
| 404 |
+
annotation_id += 1
|
| 405 |
+
return {
|
| 406 |
+
"info": {
|
| 407 |
+
"description": "LEVIR-Ship converted from YOLO to COCO",
|
| 408 |
+
"version": "1.0",
|
| 409 |
+
"source_format": "YOLO normalized xywh",
|
| 410 |
+
"split_seed": seed,
|
| 411 |
+
"split_group": group_level,
|
| 412 |
+
},
|
| 413 |
+
"licenses": [],
|
| 414 |
+
"images": images,
|
| 415 |
+
"annotations": annotations,
|
| 416 |
+
"categories": [{"id": 1, "name": "ship", "supercategory": "ship"}],
|
| 417 |
+
}
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def atomic_write_json(path: Path, payload: object) -> None:
|
| 421 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 422 |
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 423 |
+
temporary.write_text(
|
| 424 |
+
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
| 425 |
+
encoding="utf-8",
|
| 426 |
+
)
|
| 427 |
+
temporary.replace(path)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def split_summary(samples: list[Sample]) -> dict[str, object]:
|
| 431 |
+
stats = sample_stats(samples)
|
| 432 |
+
return {
|
| 433 |
+
"images": stats.images,
|
| 434 |
+
"scenes": len({sample.scene for sample in samples}),
|
| 435 |
+
"products": len({sample.product for sample in samples}),
|
| 436 |
+
"positive_images": stats.positives,
|
| 437 |
+
"negative_images": stats.images - stats.positives,
|
| 438 |
+
"boxes": stats.boxes,
|
| 439 |
+
"files": [sample.image_path.name for sample in samples],
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def preprocess(args: argparse.Namespace) -> tuple[Path, Path]:
|
| 444 |
+
data_root = resolve_path(args.data_root)
|
| 445 |
+
dataset_out = resolve_path(args.dataset_out)
|
| 446 |
+
ratios = {
|
| 447 |
+
"train": args.train_ratio,
|
| 448 |
+
"val": args.val_ratio,
|
| 449 |
+
"test": args.test_ratio,
|
| 450 |
+
}
|
| 451 |
+
samples = discover_samples(
|
| 452 |
+
data_root,
|
| 453 |
+
image_dir_name=args.image_dir,
|
| 454 |
+
annotation_dir_name=args.annotation_dir,
|
| 455 |
+
)
|
| 456 |
+
split_data = split_samples(
|
| 457 |
+
samples,
|
| 458 |
+
ratios=ratios,
|
| 459 |
+
seed=args.seed,
|
| 460 |
+
group_level=args.group_level,
|
| 461 |
+
)
|
| 462 |
+
if args.limit > 0:
|
| 463 |
+
split_data = {
|
| 464 |
+
split: split_samples_for_name[: args.limit]
|
| 465 |
+
for split, split_samples_for_name in split_data.items()
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
summary = {
|
| 469 |
+
"version": 1,
|
| 470 |
+
"source": {
|
| 471 |
+
"data_root": str(data_root),
|
| 472 |
+
"image_dir": args.image_dir,
|
| 473 |
+
"annotation_dir": args.annotation_dir,
|
| 474 |
+
},
|
| 475 |
+
"seed": args.seed,
|
| 476 |
+
"group_level": args.group_level,
|
| 477 |
+
"ratios": ratios,
|
| 478 |
+
"class_map": {"yolo_0": "ship", "coco_1": "ship"},
|
| 479 |
+
"splits": {
|
| 480 |
+
split: split_summary(split_data[split]) for split in SPLIT_NAMES
|
| 481 |
+
},
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
total_stats = sample_stats(samples)
|
| 485 |
+
print(
|
| 486 |
+
f"Validated {total_stats.images} images, {total_stats.positives} positives, "
|
| 487 |
+
f"{total_stats.boxes} boxes"
|
| 488 |
+
)
|
| 489 |
+
for split in SPLIT_NAMES:
|
| 490 |
+
stats = summary["splits"][split]
|
| 491 |
+
print(
|
| 492 |
+
f"{split}: images={stats['images']} scenes={stats['scenes']} "
|
| 493 |
+
f"products={stats['products']} positives={stats['positive_images']} "
|
| 494 |
+
f"negatives={stats['negative_images']} boxes={stats['boxes']}"
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
if args.verify_only:
|
| 498 |
+
print("Verification complete; no files written")
|
| 499 |
+
return dataset_out, data_root / args.image_dir
|
| 500 |
+
|
| 501 |
+
annotation_out = dataset_out / "annotations"
|
| 502 |
+
for split in SPLIT_NAMES:
|
| 503 |
+
atomic_write_json(
|
| 504 |
+
annotation_out / f"{split}.json",
|
| 505 |
+
build_coco_payload(
|
| 506 |
+
split_data[split], seed=args.seed, group_level=args.group_level
|
| 507 |
+
),
|
| 508 |
+
)
|
| 509 |
+
atomic_write_json(dataset_out / "split_manifest.json", summary)
|
| 510 |
+
print(f"COCO annotations: {annotation_out}")
|
| 511 |
+
print(f"Split manifest: {dataset_out / 'split_manifest.json'}")
|
| 512 |
+
print(f"Image directory (not copied): {data_root / args.image_dir}")
|
| 513 |
+
return dataset_out, data_root / args.image_dir
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def parse_args() -> argparse.Namespace:
|
| 517 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 518 |
+
parser.add_argument(
|
| 519 |
+
"--data-root",
|
| 520 |
+
default=".",
|
| 521 |
+
help="Directory containing 'All Images' and 'All Annotations'.",
|
| 522 |
+
)
|
| 523 |
+
parser.add_argument(
|
| 524 |
+
"--dataset-out",
|
| 525 |
+
default="mmdetection/data/levir_ship_coco",
|
| 526 |
+
help="Output directory for COCO annotations and the split manifest.",
|
| 527 |
+
)
|
| 528 |
+
parser.add_argument("--image-dir", default="All Images")
|
| 529 |
+
parser.add_argument("--annotation-dir", default="All Annotations")
|
| 530 |
+
parser.add_argument(
|
| 531 |
+
"--group-level",
|
| 532 |
+
choices=("product", "scene"),
|
| 533 |
+
default="product",
|
| 534 |
+
help=(
|
| 535 |
+
"Leakage boundary. 'product' also keeps -1/-2/-3 scene variants "
|
| 536 |
+
"together and is the research-safe default."
|
| 537 |
+
),
|
| 538 |
+
)
|
| 539 |
+
parser.add_argument("--train-ratio", type=float, default=0.70)
|
| 540 |
+
parser.add_argument("--val-ratio", type=float, default=0.15)
|
| 541 |
+
parser.add_argument("--test-ratio", type=float, default=0.15)
|
| 542 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 543 |
+
parser.add_argument(
|
| 544 |
+
"--limit",
|
| 545 |
+
type=int,
|
| 546 |
+
default=0,
|
| 547 |
+
help="Smoke-test cap per split after splitting; 0 keeps all images.",
|
| 548 |
+
)
|
| 549 |
+
parser.add_argument(
|
| 550 |
+
"--verify-only",
|
| 551 |
+
action="store_true",
|
| 552 |
+
help="Validate and calculate the split without writing output files.",
|
| 553 |
+
)
|
| 554 |
+
args = parser.parse_args()
|
| 555 |
+
if args.limit < 0:
|
| 556 |
+
parser.error("--limit must be >= 0")
|
| 557 |
+
return args
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def main() -> None:
|
| 561 |
+
preprocess(parse_args())
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
if __name__ == "__main__":
|
| 565 |
+
main()
|