Download preprocess_data.py from TLMHoang/mmdet_code: direct link, hf CLI and curl.
- Browser
- Download file 19.1 kB
-
https://huggingface.co/datasets/TLMHoang/mmdet_code/resolve/6ef2ae3e7c596046e37ae2a0e4e659b345afe705/preprocess_data.py
- Command line
-
hf download hf://datasets/TLMHoang/mmdet_code@6ef2ae3e7c596046e37ae2a0e4e659b345afe705/preprocess_data.py
-
curl -L -o preprocess_data.py https://huggingface.co/datasets/TLMHoang/mmdet_code/resolve/6ef2ae3e7c596046e37ae2a0e4e659b345afe705/preprocess_data.py
19.1 kB
| #!/usr/bin/env python3 | |
| """Validate LEVIR-Ship, create leakage-safe splits, and export COCO JSON. | |
| Expected input layout:: | |
| DATA_ROOT/ | |
| ├── All Images/ # PNG images | |
| └── All Annotations/ # YOLO TXT labels with matching basenames | |
| The script does not copy images. COCO ``file_name`` values remain basenames, so | |
| MMDetection should point ``data_prefix.img`` at ``DATA_ROOT/All Images``. | |
| Typical live-marimo usage after downloading the dataset into ``/marimo``:: | |
| cd /marimo | |
| python preprocess_data.py --data-root . --verify-only | |
| python preprocess_data.py --data-root . | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import random | |
| import re | |
| from collections import defaultdict | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Iterable | |
| from PIL import Image | |
| SPLIT_NAMES = ("train", "val", "test") | |
| SCENE_RE = re.compile(r"^(.*)_(-?\d+)_(-?\d+)$") | |
| PRODUCT_VARIANT_RE = re.compile(r"-\d+$") | |
| class Sample: | |
| image_path: Path | |
| annotation_path: Path | |
| scene: str | |
| product: str | |
| width: int | |
| height: int | |
| boxes: tuple[tuple[float, float, float, float], ...] | |
| def is_positive(self) -> bool: | |
| return bool(self.boxes) | |
| class GroupStats: | |
| images: int | |
| positives: int | |
| boxes: int | |
| def __add__(self, other: "GroupStats") -> "GroupStats": | |
| return GroupStats( | |
| images=self.images + other.images, | |
| positives=self.positives + other.positives, | |
| boxes=self.boxes + other.boxes, | |
| ) | |
| ZERO_STATS = GroupStats(images=0, positives=0, boxes=0) | |
| def resolve_path(value: str | Path) -> Path: | |
| """Resolve CLI paths relative to the current working directory.""" | |
| path = Path(value).expanduser() | |
| return path.resolve() if path.is_absolute() else (Path.cwd() / path).resolve() | |
| def parse_scene_and_product(image_path: Path) -> tuple[str, str]: | |
| """Return the tile's scene variant and core source-product identifier.""" | |
| match = SCENE_RE.match(image_path.stem) | |
| if not match: | |
| raise ValueError( | |
| "Cannot extract source scene and tile coordinates from " | |
| f"{image_path.name}" | |
| ) | |
| scene = match.group(1) | |
| product = PRODUCT_VARIANT_RE.sub("", scene) | |
| return scene, product | |
| def parse_yolo_boxes( | |
| annotation_path: Path, width: int, height: int | |
| ) -> tuple[tuple[float, float, float, float], ...]: | |
| """Parse one single-class YOLO file into float COCO ``xywh`` boxes.""" | |
| boxes: list[tuple[float, float, float, float]] = [] | |
| seen: set[tuple[float, float, float, float, float]] = set() | |
| for line_number, raw_line in enumerate( | |
| annotation_path.read_text(encoding="utf-8").splitlines(), 1 | |
| ): | |
| line = raw_line.strip() | |
| if not line: | |
| continue | |
| parts = line.split() | |
| if len(parts) != 5: | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: expected 5 YOLO values, " | |
| f"got {len(parts)}" | |
| ) | |
| try: | |
| class_id, cx, cy, box_width, box_height = map(float, parts) | |
| except ValueError as exc: | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: non-numeric YOLO value" | |
| ) from exc | |
| values = (class_id, cx, cy, box_width, box_height) | |
| if not all(math.isfinite(value) for value in values): | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: non-finite YOLO value" | |
| ) | |
| if class_id != 0: | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: expected class 0, " | |
| f"got {class_id:g}" | |
| ) | |
| if not (0.0 <= cx <= 1.0 and 0.0 <= cy <= 1.0): | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: center is outside [0, 1]" | |
| ) | |
| if box_width <= 0.0 or box_height <= 0.0: | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: width and height must be positive" | |
| ) | |
| x1_raw = (cx - box_width / 2.0) * width | |
| y1_raw = (cy - box_height / 2.0) * height | |
| x2_raw = (cx + box_width / 2.0) * width | |
| y2_raw = (cy + box_height / 2.0) * height | |
| tolerance = 1e-6 | |
| if ( | |
| x1_raw < -tolerance | |
| or y1_raw < -tolerance | |
| or x2_raw > width + tolerance | |
| or y2_raw > height + tolerance | |
| ): | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: bounding box exceeds image bounds" | |
| ) | |
| x1 = max(0.0, x1_raw) | |
| y1 = max(0.0, y1_raw) | |
| x2 = min(float(width), x2_raw) | |
| y2 = min(float(height), y2_raw) | |
| if x2 <= x1 or y2 <= y1: | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: invalid bounding box" | |
| ) | |
| if values in seen: | |
| raise ValueError( | |
| f"{annotation_path}:{line_number}: duplicate annotation line" | |
| ) | |
| seen.add(values) | |
| boxes.append((x1, y1, x2 - x1, y2 - y1)) | |
| return tuple(boxes) | |
| def discover_samples( | |
| data_root: Path, | |
| image_dir_name: str = "All Images", | |
| annotation_dir_name: str = "All Annotations", | |
| ) -> list[Sample]: | |
| """Validate all image-label pairs and return parsed samples.""" | |
| image_dir = data_root / image_dir_name | |
| annotation_dir = data_root / annotation_dir_name | |
| if not image_dir.is_dir() or not annotation_dir.is_dir(): | |
| raise FileNotFoundError( | |
| f"Expected '{image_dir_name}' and '{annotation_dir_name}' under " | |
| f"{data_root}" | |
| ) | |
| image_paths = sorted(image_dir.glob("*.png"), key=lambda path: path.name) | |
| annotation_paths = sorted( | |
| annotation_dir.glob("*.txt"), key=lambda path: path.name | |
| ) | |
| if not image_paths: | |
| raise ValueError(f"No PNG images found in {image_dir}") | |
| image_stems = {path.stem for path in image_paths} | |
| annotation_stems = {path.stem for path in annotation_paths} | |
| missing_annotations = sorted(image_stems - annotation_stems) | |
| orphan_annotations = sorted(annotation_stems - image_stems) | |
| if missing_annotations or orphan_annotations: | |
| details = [] | |
| if missing_annotations: | |
| details.append( | |
| f"{len(missing_annotations)} images without labels " | |
| f"(first: {missing_annotations[0]}.png)" | |
| ) | |
| if orphan_annotations: | |
| details.append( | |
| f"{len(orphan_annotations)} labels without images " | |
| f"(first: {orphan_annotations[0]}.txt)" | |
| ) | |
| raise ValueError("; ".join(details)) | |
| samples: list[Sample] = [] | |
| for image_path in image_paths: | |
| annotation_path = annotation_dir / f"{image_path.stem}.txt" | |
| scene, product = parse_scene_and_product(image_path) | |
| try: | |
| with Image.open(image_path) as image: | |
| width, height = image.size | |
| mode = image.mode | |
| image.verify() | |
| except Exception as exc: | |
| raise ValueError(f"Cannot verify image {image_path}") from exc | |
| if mode != "RGB": | |
| raise ValueError(f"Expected RGB image, got {mode} for {image_path}") | |
| boxes = parse_yolo_boxes(annotation_path, width, height) | |
| samples.append( | |
| Sample( | |
| image_path=image_path, | |
| annotation_path=annotation_path, | |
| scene=scene, | |
| product=product, | |
| width=width, | |
| height=height, | |
| boxes=boxes, | |
| ) | |
| ) | |
| return samples | |
| def sample_stats(samples: Iterable[Sample]) -> GroupStats: | |
| sample_list = list(samples) | |
| return GroupStats( | |
| images=len(sample_list), | |
| positives=sum(sample.is_positive for sample in sample_list), | |
| boxes=sum(len(sample.boxes) for sample in sample_list), | |
| ) | |
| def validate_ratios(ratios: dict[str, float]) -> None: | |
| if set(ratios) != set(SPLIT_NAMES): | |
| raise ValueError(f"Ratios must define exactly: {', '.join(SPLIT_NAMES)}") | |
| if any(value <= 0.0 for value in ratios.values()): | |
| raise ValueError("All split ratios must be positive") | |
| if not math.isclose(sum(ratios.values()), 1.0, rel_tol=0.0, abs_tol=1e-9): | |
| raise ValueError(f"Split ratios must sum to 1, got {sum(ratios.values())}") | |
| def split_samples( | |
| samples: list[Sample], | |
| *, | |
| ratios: dict[str, float], | |
| seed: int, | |
| group_level: str = "product", | |
| ) -> dict[str, list[Sample]]: | |
| """Greedily balance images, positives, and boxes without group leakage.""" | |
| validate_ratios(ratios) | |
| if group_level not in {"product", "scene"}: | |
| raise ValueError("group_level must be 'product' or 'scene'") | |
| groups: dict[str, list[Sample]] = defaultdict(list) | |
| for sample in samples: | |
| key = sample.product if group_level == "product" else sample.scene | |
| groups[key].append(sample) | |
| if len(groups) < len(SPLIT_NAMES): | |
| raise ValueError( | |
| f"Need at least {len(SPLIT_NAMES)} groups, found {len(groups)}" | |
| ) | |
| total = sample_stats(samples) | |
| targets = { | |
| split: GroupStats( | |
| images=max(1.0, total.images * ratios[split]), | |
| positives=max(1.0, total.positives * ratios[split]), | |
| boxes=max(1.0, total.boxes * ratios[split]), | |
| ) | |
| for split in SPLIT_NAMES | |
| } | |
| group_items = [(name, group, sample_stats(group)) for name, group in groups.items()] | |
| rng = random.Random(seed) | |
| rng.shuffle(group_items) | |
| group_items.sort( | |
| key=lambda item: ( | |
| item[2].images / max(total.images, 1), | |
| item[2].positives / max(total.positives, 1), | |
| item[2].boxes / max(total.boxes, 1), | |
| ), | |
| reverse=True, | |
| ) | |
| counts = {split: ZERO_STATS for split in SPLIT_NAMES} | |
| raw_capacities = { | |
| split: len(groups) * ratios[split] for split in SPLIT_NAMES | |
| } | |
| group_capacities = { | |
| split: math.floor(raw_capacities[split]) for split in SPLIT_NAMES | |
| } | |
| unassigned_slots = len(groups) - sum(group_capacities.values()) | |
| capacity_order = sorted( | |
| SPLIT_NAMES, | |
| key=lambda split: ( | |
| raw_capacities[split] - group_capacities[split], | |
| -SPLIT_NAMES.index(split), | |
| ), | |
| reverse=True, | |
| ) | |
| for split in capacity_order[:unassigned_slots]: | |
| group_capacities[split] += 1 | |
| assigned_group_counts = {split: 0 for split in SPLIT_NAMES} | |
| assignments: dict[str, str] = {} | |
| def objective(candidate: str, group_stats: GroupStats) -> float: | |
| projected = dict(counts) | |
| projected[candidate] = projected[candidate] + group_stats | |
| score = 0.0 | |
| for split in SPLIT_NAMES: | |
| for metric, weight in ( | |
| ("images", 1.0), | |
| ("positives", 1.0), | |
| ("boxes", 0.5), | |
| ): | |
| target = float(getattr(targets[split], metric)) | |
| delta = (getattr(projected[split], metric) - target) / target | |
| score += weight * delta * delta | |
| return score | |
| for group_name, _, group_stats in group_items: | |
| eligible_splits = [ | |
| split | |
| for split in SPLIT_NAMES | |
| if assigned_group_counts[split] < group_capacities[split] | |
| ] | |
| split = min( | |
| eligible_splits, | |
| key=lambda name: (objective(name, group_stats), SPLIT_NAMES.index(name)), | |
| ) | |
| assignments[group_name] = split | |
| counts[split] = counts[split] + group_stats | |
| assigned_group_counts[split] += 1 | |
| output = {split: [] for split in SPLIT_NAMES} | |
| for group_name, group, _ in group_items: | |
| output[assignments[group_name]].extend(group) | |
| for split in SPLIT_NAMES: | |
| output[split].sort(key=lambda sample: sample.image_path.name) | |
| if not output[split]: | |
| raise AssertionError(f"Split '{split}' is empty") | |
| assert_no_group_leakage(output, group_level) | |
| return output | |
| def assert_no_group_leakage( | |
| split_samples: dict[str, list[Sample]], group_level: str | |
| ) -> None: | |
| group_sets = {} | |
| for split, samples in split_samples.items(): | |
| group_sets[split] = { | |
| sample.product if group_level == "product" else sample.scene | |
| for sample in samples | |
| } | |
| for index, left in enumerate(SPLIT_NAMES): | |
| for right in SPLIT_NAMES[index + 1 :]: | |
| overlap = group_sets[left] & group_sets[right] | |
| if overlap: | |
| example = sorted(overlap)[0] | |
| raise AssertionError( | |
| f"{group_level} leakage between {left} and {right}: {example}" | |
| ) | |
| def build_coco_payload( | |
| samples: list[Sample], *, seed: int, group_level: str | |
| ) -> dict[str, object]: | |
| images: list[dict[str, object]] = [] | |
| annotations: list[dict[str, object]] = [] | |
| annotation_id = 1 | |
| for image_id, sample in enumerate(samples, 1): | |
| images.append( | |
| { | |
| "id": image_id, | |
| "file_name": sample.image_path.name, | |
| "width": sample.width, | |
| "height": sample.height, | |
| } | |
| ) | |
| for x, y, width, height in sample.boxes: | |
| annotations.append( | |
| { | |
| "id": annotation_id, | |
| "image_id": image_id, | |
| "category_id": 1, | |
| "bbox": [x, y, width, height], | |
| "area": width * height, | |
| "iscrowd": 0, | |
| "segmentation": [], | |
| } | |
| ) | |
| annotation_id += 1 | |
| return { | |
| "info": { | |
| "description": "LEVIR-Ship converted from YOLO to COCO", | |
| "version": "1.0", | |
| "source_format": "YOLO normalized xywh", | |
| "split_seed": seed, | |
| "split_group": group_level, | |
| }, | |
| "licenses": [], | |
| "images": images, | |
| "annotations": annotations, | |
| "categories": [{"id": 1, "name": "ship", "supercategory": "ship"}], | |
| } | |
| def atomic_write_json(path: Path, payload: object) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| temporary.write_text( | |
| json.dumps(payload, ensure_ascii=False, indent=2) + "\n", | |
| encoding="utf-8", | |
| ) | |
| temporary.replace(path) | |
| def split_summary(samples: list[Sample]) -> dict[str, object]: | |
| stats = sample_stats(samples) | |
| return { | |
| "images": stats.images, | |
| "scenes": len({sample.scene for sample in samples}), | |
| "products": len({sample.product for sample in samples}), | |
| "positive_images": stats.positives, | |
| "negative_images": stats.images - stats.positives, | |
| "boxes": stats.boxes, | |
| "files": [sample.image_path.name for sample in samples], | |
| } | |
| def preprocess(args: argparse.Namespace) -> tuple[Path, Path]: | |
| data_root = resolve_path(args.data_root) | |
| dataset_out = resolve_path(args.dataset_out) | |
| ratios = { | |
| "train": args.train_ratio, | |
| "val": args.val_ratio, | |
| "test": args.test_ratio, | |
| } | |
| samples = discover_samples( | |
| data_root, | |
| image_dir_name=args.image_dir, | |
| annotation_dir_name=args.annotation_dir, | |
| ) | |
| split_data = split_samples( | |
| samples, | |
| ratios=ratios, | |
| seed=args.seed, | |
| group_level=args.group_level, | |
| ) | |
| if args.limit > 0: | |
| split_data = { | |
| split: split_samples_for_name[: args.limit] | |
| for split, split_samples_for_name in split_data.items() | |
| } | |
| summary = { | |
| "version": 1, | |
| "source": { | |
| "data_root": str(data_root), | |
| "image_dir": args.image_dir, | |
| "annotation_dir": args.annotation_dir, | |
| }, | |
| "seed": args.seed, | |
| "group_level": args.group_level, | |
| "ratios": ratios, | |
| "class_map": {"yolo_0": "ship", "coco_1": "ship"}, | |
| "splits": { | |
| split: split_summary(split_data[split]) for split in SPLIT_NAMES | |
| }, | |
| } | |
| total_stats = sample_stats(samples) | |
| print( | |
| f"Validated {total_stats.images} images, {total_stats.positives} positives, " | |
| f"{total_stats.boxes} boxes" | |
| ) | |
| for split in SPLIT_NAMES: | |
| stats = summary["splits"][split] | |
| print( | |
| f"{split}: images={stats['images']} scenes={stats['scenes']} " | |
| f"products={stats['products']} positives={stats['positive_images']} " | |
| f"negatives={stats['negative_images']} boxes={stats['boxes']}" | |
| ) | |
| if args.verify_only: | |
| print("Verification complete; no files written") | |
| return dataset_out, data_root / args.image_dir | |
| annotation_out = dataset_out / "annotations" | |
| for split in SPLIT_NAMES: | |
| atomic_write_json( | |
| annotation_out / f"{split}.json", | |
| build_coco_payload( | |
| split_data[split], seed=args.seed, group_level=args.group_level | |
| ), | |
| ) | |
| atomic_write_json(dataset_out / "split_manifest.json", summary) | |
| print(f"COCO annotations: {annotation_out}") | |
| print(f"Split manifest: {dataset_out / 'split_manifest.json'}") | |
| print(f"Image directory (not copied): {data_root / args.image_dir}") | |
| return dataset_out, data_root / args.image_dir | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument( | |
| "--data-root", | |
| default=".", | |
| help="Directory containing 'All Images' and 'All Annotations'.", | |
| ) | |
| parser.add_argument( | |
| "--dataset-out", | |
| default="mmdetection/data/levir_ship_coco", | |
| help="Output directory for COCO annotations and the split manifest.", | |
| ) | |
| parser.add_argument("--image-dir", default="All Images") | |
| parser.add_argument("--annotation-dir", default="All Annotations") | |
| parser.add_argument( | |
| "--group-level", | |
| choices=("product", "scene"), | |
| default="product", | |
| help=( | |
| "Leakage boundary. 'product' also keeps -1/-2/-3 scene variants " | |
| "together and is the research-safe default." | |
| ), | |
| ) | |
| parser.add_argument("--train-ratio", type=float, default=0.70) | |
| parser.add_argument("--val-ratio", type=float, default=0.15) | |
| parser.add_argument("--test-ratio", type=float, default=0.15) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument( | |
| "--limit", | |
| type=int, | |
| default=0, | |
| help="Smoke-test cap per split after splitting; 0 keeps all images.", | |
| ) | |
| parser.add_argument( | |
| "--verify-only", | |
| action="store_true", | |
| help="Validate and calculate the split without writing output files.", | |
| ) | |
| args = parser.parse_args() | |
| if args.limit < 0: | |
| parser.error("--limit must be >= 0") | |
| return args | |
| def main() -> None: | |
| preprocess(parse_args()) | |
| if __name__ == "__main__": | |
| main() | |