File size: 2,921 Bytes
54ed410
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""M3ISR frame-level train/test split utility.

Hold-out rule:
    Within each RGB_images/<angle>/ folder, every N-th frame (0, N, 2N, ...)
    is reserved as a test frame; all other frames are used for training.
    With N=6 this gives an approximate 5:1 train/test ratio per scene.

The split is applied independently to each view angle and to both
MovingCameraDynamicScene and MovingCameraStaticScene subsets.

Usage:
    python Scripts/split_frames.py \\
        --dataset_root TRACKS \\
        --output_dir   splits \\
        --hold_out     6
"""
from __future__ import annotations

import argparse
import os
import re
from pathlib import Path

FRAME_NUM = re.compile(r"(\d+)")


def natural_key(name: str) -> int:
    """Extract the first integer in a filename for natural sorting."""
    m = FRAME_NUM.search(name)
    return int(m.group(1)) if m else -1


def split_view(view_dir: Path, hold_out: int) -> tuple[list[str], list[str]]:
    frames = sorted(
        (f for f in view_dir.iterdir() if f.is_file()),
        key=lambda p: natural_key(p.name),
    )
    train, test = [], []
    for i, f in enumerate(frames):
        (test if i % hold_out == 0 else train).append(str(f))
    return train, test


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--dataset_root", required=True,
                    help="Path to the TRACKS directory of M3ISR")
    ap.add_argument("--output_dir", required=True,
                    help="Directory where train.txt / test.txt will be written")
    ap.add_argument("--hold_out", type=int, default=6,
                    help="Hold-out stride; every N-th frame becomes a test frame (default: 6)")
    args = ap.parse_args()

    root = Path(args.dataset_root).resolve()
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    all_train: list[str] = []
    all_test: list[str] = []

    # Walk the directory tree and find every RGB_images/<angle>/ leaf folder.
    for rgb_root in root.rglob("RGB_images"):
        if not rgb_root.is_dir():
            continue
        for angle_dir in sorted(rgb_root.iterdir()):
            if not angle_dir.is_dir():
                continue
            tr, te = split_view(angle_dir, args.hold_out)
            all_train.extend(tr)
            all_test.extend(te)

    (out_dir / "train.txt").write_text("\n".join(all_train))
    (out_dir / "test.txt").write_text("\n".join(all_test))

    print(f"[M3ISR] Dataset root : {root}")
    print(f"[M3ISR] Hold-out     : every {args.hold_out}-th frame -> test")
    print(f"[M3ISR] Train frames : {len(all_train)}")
    print(f"[M3ISR] Test  frames : {len(all_test)}")
    print(f"[M3ISR] Saved        : {out_dir/'train.txt'}")
    print(f"[M3ISR] Saved        : {out_dir/'test.txt'}")


if __name__ == "__main__":
    main()