File size: 4,663 Bytes
8d5dfff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Creates a submission.zip with valid, correctly-sized and correctly-formatted
but randomly-generated content, so you can test your submission pipeline
(zip layout, image sizes, point cloud properties) before you have a trained
model. See this folder's README.md for the submission format this mirrors.

Only reads test/sparse/0/cameras.txt and images.txt from the dataset, so it
works for every scene, including final-testing scenes where the reference
photos and 3D ground truth are withheld.

Usage:
    python make_dummy_submission.py --output submission.zip
"""

import argparse
import io
import zipfile
from pathlib import Path

import numpy as np
from PIL import Image
from plyfile import PlyData, PlyElement

DATASET_ROOT = Path(__file__).resolve().parent.parent  # Twinworld_Datasets/
DATASETS = {
    "tum": "Data_TUM",
    "gold_coast": "Data_Goldcoast",
}
NUM_POINTS = 2000
SEED = 0


def read_cameras_txt(path):
    """Return {camera_id: (width, height)}."""
    cameras = {}
    with open(path) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            parts = line.split()
            camera_id = int(parts[0])
            cameras[camera_id] = (int(parts[2]), int(parts[3]))
    return cameras


def read_images_txt(path):
    """Return [(name, camera_id), ...]. Each image occupies two lines; the
    second (POINTS2D) line is not needed here and is skipped."""
    with open(path) as f:
        lines = [line for line in f if not line.startswith('#')]
    entries = []
    for i in range(0, len(lines), 2):
        parts = lines[i].split()
        if not parts:
            continue
        entries.append((parts[9], int(parts[8])))
    return entries


def scene_frames(scene_dir):
    """Return [(frame_stem, width, height), ...] for a scene's test poses."""
    sparse_dir = scene_dir / "test" / "sparse" / "0"
    cameras = read_cameras_txt(sparse_dir / "cameras.txt")
    images = read_images_txt(sparse_dir / "images.txt")
    return [(Path(name).stem, *cameras[camera_id]) for name, camera_id in images]


def random_png_bytes(width, height, rng):
    pixels = rng.integers(0, 256, size=(height, width, 3), dtype=np.uint8)
    buf = io.BytesIO()
    Image.fromarray(pixels, mode="RGB").save(buf, format="PNG")
    return buf.getvalue()


def random_point_cloud_bytes(num_points, rng, with_classification):
    fields = [("x", "f4"), ("y", "f4"), ("z", "f4")]
    if with_classification:
        fields.append(("classification", "u1"))

    vertex = np.empty(num_points, dtype=fields)
    xyz = rng.uniform(-50.0, 50.0, size=(num_points, 3)).astype(np.float32)
    vertex["x"], vertex["y"], vertex["z"] = xyz[:, 0], xyz[:, 1], xyz[:, 2]
    if with_classification:
        vertex["classification"] = rng.choice(
            [0, 1, 2, 3, 4, 255], size=num_points).astype(np.uint8)

    buf = io.BytesIO()
    PlyData([PlyElement.describe(vertex, "vertex")], text=False, byte_order="<").write(buf)
    return buf.getvalue()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path("submission.zip"),
                         help="output zip path")
    parser.add_argument("--dataset_root", type=Path, default=DATASET_ROOT,
                         help="path to Twinworld_Datasets (containing Data_TUM/Data_Goldcoast)")
    parser.add_argument("--num_points", type=int, default=NUM_POINTS,
                         help="random points per scene's point cloud")
    parser.add_argument("--seed", type=int, default=SEED)
    args = parser.parse_args()
    rng = np.random.default_rng(args.seed)

    n_scenes, n_frames = 0, 0
    with zipfile.ZipFile(args.output, "w", zipfile.ZIP_DEFLATED) as zf:
        for dataset_name, dir_name in DATASETS.items():
            dataset_dir = args.dataset_root / dir_name
            for scene_dir in sorted(dataset_dir.glob("scene_*")):
                with_classification = dataset_name == "gold_coast"

                for stem, width, height in scene_frames(scene_dir):
                    zf.writestr(f"{dataset_name}/{scene_dir.name}/rgb/{stem}.png",
                                random_png_bytes(width, height, rng))
                    n_frames += 1

                ply_bytes = random_point_cloud_bytes(args.num_points, rng, with_classification)
                zf.writestr(f"{dataset_name}/{scene_dir.name}/3D_point_cloud/point_cloud.ply",
                            ply_bytes)
                n_scenes += 1

    print(f"Wrote {args.output} ({n_scenes} scenes, {n_frames} rgb frames)")


if __name__ == "__main__":
    main()