File size: 5,986 Bytes
a359afd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | #!/usr/bin/env python3
"""Split rgb/seg/depth into train/val/test splits.
Default split: 400 / 80 / 20 (80% / 16% / 4% of 500)
All modalities share exactly the same random stems.
Usage:
python split_train_val.py # default 400/80/20, copy
python split_train_val.py --n-train 400 --n-val 80 --n-test 20
python split_train_val.py --move --force # move files, overwrite existing
python split_train_val.py --dry-run # print counts only
"""
import argparse
import random
import shutil
from pathlib import Path
MODALITIES = ("rgb", "depth", "seg")
SPLITS = ("train", "val", "test")
IMAGE_SUFFIXES = {".tif", ".tiff", ".png", ".jpg", ".jpeg", ".bmp", ".webp", ".jp2", ".gif"}
def list_images(folder: Path):
return [p for p in folder.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES]
def build_stem_map(folder: Path):
mapping = {}
for p in list_images(folder):
if p.stem in mapping:
raise RuntimeError(f"Duplicate stem in {folder}: {p.stem}")
mapping[p.stem] = p
return mapping
def ensure_dirs(root: Path):
for split in SPLITS:
for m in MODALITIES:
(root / split / m).mkdir(parents=True, exist_ok=True)
def clear_split_dirs(root: Path):
for split in SPLITS:
d = root / split
if d.exists():
shutil.rmtree(d)
def copy_or_move(src: Path, dst: Path, do_move: bool):
if do_move:
shutil.move(str(src), str(dst))
else:
shutil.copy2(src, dst)
def main():
parser = argparse.ArgumentParser(
description="Split rgb/depth/seg into train/val/test splits."
)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent,
help="Dataset root containing rgb/depth/seg. Default: script dir.")
parser.add_argument("--n-train", type=int, default=400,
help="Number of train samples. Default: 400")
parser.add_argument("--n-val", type=int, default=80,
help="Number of val samples. Default: 80")
parser.add_argument("--n-test", type=int, default=20,
help="Number of test samples. Default: 20")
parser.add_argument("--seed", type=int, default=42,
help="Random seed for reproducibility. Default: 42")
parser.add_argument("--move", action="store_true",
help="Move files instead of copying.")
parser.add_argument("--force", action="store_true",
help="Remove existing train/val/test folders before split.")
parser.add_argument("--dry-run", action="store_true",
help="Only print split summary without writing files.")
args = parser.parse_args()
root = args.root.resolve()
# Build stem maps for each modality
source_maps = {}
for m in MODALITIES:
folder = root / m
if not folder.exists() or not folder.is_dir():
raise FileNotFoundError(f"Missing folder: {folder}")
source_maps[m] = build_stem_map(folder)
# Intersection of stems across all modalities
common_stems = set(source_maps[MODALITIES[0]].keys())
for m in MODALITIES[1:]:
common_stems &= set(source_maps[m].keys())
if not common_stems:
raise RuntimeError("No common stems across rgb/depth/seg")
for m in MODALITIES:
missing = set(source_maps[m].keys()) - common_stems
if missing:
print(f"[WARN] {m}: {len(missing)} files excluded (no match in other modalities)")
n_total = len(common_stems)
n_train = args.n_train
n_val = args.n_val
n_test = args.n_test
n_requested = n_train + n_val + n_test
if n_requested > n_total:
raise ValueError(
f"Requested {n_train}+{n_val}+{n_test}={n_requested} samples "
f"but only {n_total} common stems available."
)
if n_requested < n_total:
print(f"[WARN] {n_total - n_requested} samples will be left unassigned "
f"(total={n_total}, requested={n_requested}). They will be ignored.")
# Shuffle deterministically then slice
stems = sorted(common_stems)
rnd = random.Random(args.seed)
rnd.shuffle(stems)
train_stems = set(stems[:n_train])
val_stems = set(stems[n_train:n_train + n_val])
test_stems = set(stems[n_train + n_val:n_train + n_val + n_test])
print(f"[INFO] root : {root}")
print(f"[INFO] total : {n_total} common stems")
print(f"[INFO] split : train={n_train}, val={n_val}, test={n_test}")
print(f"[INFO] mode : {'move' if args.move else 'copy'}")
print(f"[INFO] seed : {args.seed}")
if args.dry_run:
print("[INFO] dry-run only — no files written")
return
if args.force:
clear_split_dirs(root)
else:
for split in SPLITS:
split_dir = root / split
if split_dir.exists() and any(split_dir.rglob("*")):
raise RuntimeError(
f"{split_dir} already exists and is non-empty. Use --force to overwrite."
)
ensure_dirs(root)
stem_to_split = {}
for s in train_stems:
stem_to_split[s] = "train"
for s in val_stems:
stem_to_split[s] = "val"
for s in test_stems:
stem_to_split[s] = "test"
written = {"train": 0, "val": 0, "test": 0}
for m in MODALITIES:
for stem, src in source_maps[m].items():
split = stem_to_split.get(stem)
if split is None:
continue # unassigned surplus
dst = root / split / m / src.name
copy_or_move(src, dst, args.move)
written[split] += 1
total_written = sum(written.values())
print(f"[OK] written : {total_written} files total "
f"(train={written['train']}, val={written['val']}, test={written['test']})")
print("[OK] done.")
if __name__ == "__main__":
main()
|