File size: 6,295 Bytes
4e6a175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python3
"""Downsample a dataset by 2 while preserving its directory structure."""

import argparse
import json
import os
import shutil
import tempfile
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

from PIL import Image


FACTOR = 2
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png"}
DEFAULT_WORKERS = min(8, os.cpu_count() or 1)


def half_size(size):
    width, height = size
    return max(1, width // FACTOR), max(1, height // FACTOR)


def resize_image(source, destination):
    with Image.open(source) as image:
        resized = image.resize(half_size(image.size), Image.Resampling.LANCZOS)
        save_options = (
            {"quality": 90}
            if source.suffix.lower() in {".jpg", ".jpeg"}
            else {}
        )
        resized.save(destination, **save_options)


def resize_mask(source, destination):
    rgb_path = source.parent.parent / "rgb" / f"{source.stem}.png"
    if not rgb_path.is_file():
        raise RuntimeError(f"cannot determine dimensions for mask without {rgb_path}")

    with Image.open(rgb_path) as rgb:
        size = rgb.size

    values = source.read_bytes()
    expected = size[0] * size[1]
    if len(values) != expected:
        raise RuntimeError(
            f"{source} contains {len(values)} values; expected {expected} "
            f"for {size[0]}x{size[1]}"
        )

    mask = Image.frombytes("L", size, values)
    resized = mask.resize(half_size(size), Image.Resampling.NEAREST)
    destination.write_bytes(resized.tobytes())


def scale_homography_metadata(source, destination):
    data = json.loads(source.read_text())

    for key in ("ir_size", "rgb_size"):
        if key in data:
            data[key] = list(half_size(data[key]))

    for subset in data.get("subsets", []):
        for correspondence in subset.get("correspondences", []):
            for key in ("ir", "rgb"):
                if key in correspondence:
                    correspondence[key] = [
                        value / FACTOR for value in correspondence[key]
                    ]

        for key in ("ransac_threshold_px", "rmse_px"):
            if key in subset:
                subset[key] /= FACTOR

        if "translation_px" in subset:
            subset["translation_px"] = [
                value / FACTOR for value in subset["translation_px"]
            ]

        if "matrix" in subset:
            matrix = subset["matrix"]
            if len(matrix) != 3 or any(len(row) != 3 for row in matrix):
                raise RuntimeError(f"invalid homography matrix in {source}")
            # Both coordinate systems are scaled equally: H' = S H S^-1.
            matrix[0][2] /= FACTOR
            matrix[1][2] /= FACTOR
            matrix[2][0] *= FACTOR
            matrix[2][1] *= FACTOR

    destination.write_text(json.dumps(data, indent=2) + "\n")


def copy_entry(source, destination):
    suffix = source.suffix.lower()
    if suffix in IMAGE_SUFFIXES:
        resize_image(source, destination)
    elif suffix == ".txt" and source.parent.name == "mask":
        resize_mask(source, destination)
    elif suffix == ".json" and source.parent.name == "homography":
        scale_homography_metadata(source, destination)
    else:
        shutil.copy2(source, destination)


def resize_dataset(source_root, output_root, workers=DEFAULT_WORKERS):
    source_root = source_root.resolve()
    output_root = output_root.resolve()

    if workers < 1:
        raise RuntimeError("workers must be at least 1")
    if not source_root.is_dir():
        raise RuntimeError(f"dataset directory does not exist: {source_root}")
    if source_root == output_root or source_root in output_root.parents:
        raise RuntimeError("output directory must not be inside the source dataset")
    if output_root.exists() and (
        not output_root.is_dir() or any(output_root.iterdir())
    ):
        raise RuntimeError(f"output directory is not empty: {output_root}")

    output_root.parent.mkdir(parents=True, exist_ok=True)
    count = 0
    with tempfile.TemporaryDirectory(
        prefix=f".{output_root.name}.", dir=output_root.parent
    ) as temp:
        staged_root = Path(temp) / output_root.name
        staged_root.mkdir()

        files = []
        for source in sorted(source_root.rglob("*")):
            if source.is_symlink():
                raise RuntimeError(f"symbolic links are not supported: {source}")

            destination = staged_root / source.relative_to(source_root)
            if source.is_dir():
                destination.mkdir(exist_ok=True)
            elif source.is_file():
                destination.parent.mkdir(parents=True, exist_ok=True)
                files.append((source, destination))

        if workers == 1:
            for source, destination in files:
                copy_entry(source, destination)
        elif files:
            with ProcessPoolExecutor(max_workers=workers) as executor:
                sources = (source for source, _ in files)
                destinations = (destination for _, destination in files)
                for _ in executor.map(copy_entry, sources, destinations):
                    pass
        count = len(files)

        if output_root.exists():
            output_root.rmdir()
        staged_root.replace(output_root)

    return count


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "source",
        nargs="?",
        type=Path,
        default=Path("Data"),
        help="source dataset (default: Data/)",
    )
    parser.add_argument(
        "output",
        nargs="?",
        type=Path,
        default=Path("ResizedData"),
        help="output dataset (default: ResizedData/)",
    )
    parser.add_argument(
        "-j",
        "--workers",
        type=int,
        default=DEFAULT_WORKERS,
        help=f"parallel worker processes (default: {DEFAULT_WORKERS})",
    )
    return parser.parse_args()


def main():
    args = parse_args()
    try:
        count = resize_dataset(args.source, args.output, args.workers)
    except (OSError, RuntimeError, json.JSONDecodeError) as error:
        raise SystemExit(f"error: {error}") from error
    print(f"wrote {count} files to {args.output}")


if __name__ == "__main__":
    main()