File size: 5,738 Bytes
4c18714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate COLMAP binary sparse models without importing COLMAP or NumPy."""

from __future__ import annotations

import argparse
import struct
from pathlib import Path


CAMERA_MODEL_PARAMETER_COUNTS = {
    0: 3,   # SIMPLE_PINHOLE
    1: 4,   # PINHOLE
    2: 4,   # SIMPLE_RADIAL
    3: 5,   # RADIAL
    4: 8,   # OPENCV
    5: 8,   # OPENCV_FISHEYE
    6: 12,  # FULL_OPENCV
    7: 5,   # FOV
    8: 4,   # SIMPLE_RADIAL_FISHEYE
    9: 5,   # RADIAL_FISHEYE
    10: 12, # THIN_PRISM_FISHEYE
}


def read_exact(handle, byte_count: int) -> bytes:
    data = handle.read(byte_count)
    if len(data) != byte_count:
        raise ValueError(
            f"Unexpected end of file at byte {handle.tell()}: "
            f"wanted {byte_count}, received {len(data)}"
        )
    return data


def unpack(handle, format_string: str):
    value_struct = struct.Struct("<" + format_string)
    return value_struct.unpack(read_exact(handle, value_struct.size))


def skip_exact(handle, byte_count: int, file_size: int) -> None:
    if byte_count < 0 or handle.tell() + byte_count > file_size:
        raise ValueError(f"Invalid block length {byte_count} at byte {handle.tell()}")
    handle.seek(byte_count, 1)


def require_eof(handle, file_size: int) -> None:
    if handle.tell() != file_size:
        raise ValueError(
            f"Parsed {handle.tell()} bytes but file contains {file_size} bytes"
        )


def validate_cameras(model_directory: Path) -> tuple[int, set[int]]:
    model_file = model_directory / "cameras.bin"
    file_size = model_file.stat().st_size
    camera_ids: set[int] = set()

    with model_file.open("rb") as handle:
        (camera_count,) = unpack(handle, "Q")
        for _ in range(camera_count):
            camera_id, model_id, width, height = unpack(handle, "iiQQ")
            if camera_id in camera_ids:
                raise ValueError(f"Duplicate camera ID {camera_id}")
            if model_id not in CAMERA_MODEL_PARAMETER_COUNTS:
                raise ValueError(f"Unsupported camera model ID {model_id}")
            if width <= 0 or height <= 0:
                raise ValueError(f"Invalid camera dimensions {width}x{height}")
            read_exact(handle, 8 * CAMERA_MODEL_PARAMETER_COUNTS[model_id])
            camera_ids.add(camera_id)
        require_eof(handle, file_size)

    return camera_count, camera_ids


def validate_images(model_directory: Path, camera_ids: set[int]) -> int:
    model_file = model_directory / "images.bin"
    file_size = model_file.stat().st_size
    image_ids: set[int] = set()

    with model_file.open("rb") as handle:
        (image_count,) = unpack(handle, "Q")
        for _ in range(image_count):
            image_data = unpack(handle, "idddddddi")
            image_id = image_data[0]
            camera_id = image_data[-1]
            if image_id in image_ids:
                raise ValueError(f"Duplicate image ID {image_id}")
            if camera_id not in camera_ids:
                raise ValueError(f"Image {image_id} references camera {camera_id}")

            name_bytes = bytearray()
            while True:
                character = read_exact(handle, 1)
                if character == b"\x00":
                    break
                name_bytes.extend(character)
            name_bytes.decode("utf-8")

            (point_count,) = unpack(handle, "Q")
            skip_exact(handle, 24 * point_count, file_size)
            image_ids.add(image_id)
        require_eof(handle, file_size)

    return image_count


def validate_points(model_directory: Path) -> int:
    model_file = model_directory / "points3D.bin"
    file_size = model_file.stat().st_size
    point_ids: set[int] = set()

    with model_file.open("rb") as handle:
        (point_count,) = unpack(handle, "Q")
        for _ in range(point_count):
            point_data = unpack(handle, "QdddBBBd")
            point_id = point_data[0]
            if point_id in point_ids:
                raise ValueError(f"Duplicate point ID {point_id}")
            (track_length,) = unpack(handle, "Q")
            skip_exact(handle, 8 * track_length, file_size)
            point_ids.add(point_id)
        require_eof(handle, file_size)

    return point_count


def discover_models(root_directory: Path) -> list[Path]:
    return sorted(
        camera_file.parent
        for camera_file in root_directory.rglob("cameras.bin")
        if (camera_file.parent / "images.bin").is_file()
        and (camera_file.parent / "points3D.bin").is_file()
    )


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "root",
        nargs="?",
        type=Path,
        default=Path(__file__).resolve().parent,
        help="Directory containing one or more COLMAP sparse models",
    )
    arguments = parser.parse_args()

    models = discover_models(arguments.root)
    if not models:
        raise SystemExit(f"No complete COLMAP models found below {arguments.root}")

    failures = 0
    for model_directory in models:
        try:
            camera_count, camera_ids = validate_cameras(model_directory)
            image_count = validate_images(model_directory, camera_ids)
            point_count = validate_points(model_directory)
            print(
                f"OK {model_directory}: "
                f"{camera_count} cameras, {image_count} images, {point_count} points"
            )
        except (OSError, UnicodeDecodeError, ValueError, struct.error) as error:
            failures += 1
            print(f"FAILED {model_directory}: {error}")

    print(f"Validated {len(models)} models; failures: {failures}")
    return 1 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main())