US3D-Enhanced / split_train_val.py
JasonXF's picture
Upload split_train_val.py with huggingface_hub
a359afd verified
Raw
History Blame Contribute Delete
5.99 kB
#!/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()