Debian Codegraph @

benchmark/reconstruction/evaluate.py

raw
1 # Copyright (c), ETH Zurich and UNC Chapel Hill.
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6 #
7 # * Redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer.
9 #
10 # * Redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution.
13 #
14 # * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
15 # its contributors may be used to endorse or promote products derived
16 # from this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29
30 """Run the reconstruction benchmark and report pose accuracy metrics.
31
32 A plain run evaluates one colmap binary once and writes a single report.
33 --seeds/--num_seeds instead runs it once per random seed, writing one
34 <report_name>_s<seed>.pkl report per seed, to measure run-to-run spread. The
35 scene workspaces are shared across those runs, so features and raw matches are
36 computed once and reused.
37
38 Reports are compared with compare.py.
39
40 Reproducibility caveat: RANSAC seeds per thread as random_seed +
41 omp_get_thread_num(), so only single-threaded scenes are deterministic at a
42 fixed seed. Pass --threads_per_scene 1 for reproducible runs, and use
43 --num_parallel_scenes for throughput instead -- parallelism across scenes does
44 not touch any one scene's random number stream.
45
46 Note that a seed reseeds both geometric verification and the mapper, but only
47 --overwrite_reconstruction is forced between the runs; pass
48 --overwrite_two_view_geometries as well to also redo verification.
49
50 Example:
51 # One binary across 5 seeds (run-to-run variance):
52 python evaluate.py --colmap_path /path/colmap --num_seeds 5 \\
53 --threads_per_scene 1 --overwrite_two_view_geometries \\
54 --data_path data --datasets eth3d --categories dslr --scenes meadow \\
55 --run_path runs --run_name variance-meadow
56 """
57
58 import argparse
59 import json
60 import pickle
61
62 from evaluation.blended_mvs import DatasetBlendedMVS
63 from evaluation.eth3d import DatasetETH3D
64 from evaluation.imc import DatasetIMC2023, DatasetIMC2024, DatasetIMC2025
65 from evaluation.tartanair import (
66 DatasetTartanAirPerspective,
67 DatasetTartanAirSpherical,
68 )
69 from evaluation.tartanair.tartanair_v2 import load_manifest
70 from evaluation.utils import (
71 Dataset,
72 MetricsByDatasetByCatByScene,
73 create_result_table,
74 filter_smallest_scenes_per_category,
75 parse_args,
76 process_scenes,
77 )
78
79 import pycolmap
80
81
82 def run_once(args: argparse.Namespace) -> MetricsByDatasetByCatByScene | None:
83 """Evaluates all datasets once and writes args.report_name.
84
85 Returns None if a dataset is unknown or no scenes matched.
86 """
87 datasets: dict[str, type[Dataset]] = {
88 "eth3d": DatasetETH3D,
89 "blended-mvs": DatasetBlendedMVS,
90 "imc2023": DatasetIMC2023,
91 "imc2024": DatasetIMC2024,
92 "imc2025": DatasetIMC2025,
93 "tartanair-v2-perspective": DatasetTartanAirPerspective,
94 "tartanair-v2-spherical": DatasetTartanAirSpherical,
95 }
96
97 metrics: MetricsByDatasetByCatByScene = {}
98 for dataset_name in args.datasets:
99 if dataset_name not in datasets:
100 pycolmap.logging.error(f"Unknown dataset: {dataset_name}")
101 return None
102
103 pycolmap.logging.info(f"Evaluating dataset: {dataset_name}")
104
105 dataset = datasets[dataset_name](
106 data_path=args.data_path,
107 categories=args.categories,
108 scenes=args.scenes,
109 run_path=args.run_path,
110 run_name=args.run_name,
111 )
112
113 scene_infos = dataset.list_scenes()
114
115 if args.fast:
116 scene_infos = filter_smallest_scenes_per_category(
117 scene_infos, args.fast_num_scenes
118 )
119
120 if not scene_infos:
121 pycolmap.logging.warning("No scenes found")
122 return None
123
124 metrics[dataset_name] = process_scenes(
125 args=args,
126 scene_infos=scene_infos,
127 dataset=dataset,
128 )
129
130 pycolmap.logging.info("Results:\n" + create_result_table(metrics))
131
132 report_path = args.run_path / args.run_name / (args.report_name + ".pkl")
133 pycolmap.logging.info(f"Saving report to: {report_path}")
134 with open(report_path, "wb") as report_file:
135 pickle.dump(metrics, report_file)
136
137 metadata_path = report_path.with_suffix(".json")
138 metadata = {
139 "datasets": args.datasets,
140 "pycolmap_version": pycolmap.__version__,
141 "random_seed": args.random_seed,
142 "feature": args.feature,
143 "mapper": args.mapper,
144 "use_gpu": args.use_gpu,
145 }
146 if any(name.startswith("tartanair-v2-") for name in args.datasets):
147 metadata["tartanair_manifest_version"] = load_manifest()["version"]
148 metadata_path.write_text(json.dumps(metadata, indent=2) + "\n")
149
150 return metrics
151
152
153 def run_seeds(args: argparse.Namespace) -> None:
154 """Evaluates once per seed, writing <report_name>_s<seed>.pkl each time.
155
156 A failing seed is reported and skipped, so the remaining ones still run.
157 """
158 # The seeds share one workspace per scene, so without this every run after
159 # the first would silently re-evaluate the first one's reconstruction.
160 args.overwrite_reconstruction = True
161 args.overwrite_alignment = True
162
163 report_name = args.report_name
164 pycolmap.logging.info(
165 f"{report_name}: {len(args.seeds)} seeds {args.seeds} "
166 f"-> {args.run_path / args.run_name}"
167 )
168
169 failures = []
170 for seed in args.seeds:
171 pycolmap.logging.info(f"---- seed={seed} ----")
172 args.random_seed = seed
173 args.report_name = f"{report_name}_s{seed}"
174 try:
175 reason = "" if run_once(args) is not None else ": no scenes"
176 except Exception as error:
177 reason = f": {error!r}"
178 if reason:
179 failures.append(seed)
180 pycolmap.logging.warning(
181 f"seed={seed} FAILED{reason} (its report will be missing and "
182 "a comparison skips it)"
183 )
184
185 if failures:
186 pycolmap.logging.warning(
187 f"{len(failures)} of {len(args.seeds)} run(s) failed: {failures}"
188 )
189 raise SystemExit(1)
190
191
192 def main() -> None:
193 args = parse_args(__doc__)
194 if args.seeds is not None:
195 run_seeds(args)
196 else:
197 run_once(args)
198
199
200 if __name__ == "__main__":
201 main()