Debian Codegraph @

python/examples/custom_incremental_pipeline.py

raw
1 """
2 Python reimplementation of the C++ incremental mapper with equivalent logic.
3 """
4
5 import argparse
6 import time
7 from pathlib import Path
8
9 import custom_bundle_adjustment
10 import enlighten
11
12 import pycolmap
13 from pycolmap import (
14 IncrementalMapper,
15 IncrementalMapperOptions,
16 IncrementalPipeline,
17 IncrementalPipelineCallback,
18 IncrementalPipelineOptions,
19 IncrementalPipelineStatus,
20 Reconstruction,
21 ReconstructionManager,
22 logging,
23 )
24
25
26 def write_snapshot(reconstruction: Reconstruction, snapshot_path: Path) -> None:
27 logging.info("Creating snapshot")
28 timestamp = time.time() * 1000
29 path = snapshot_path / f"{timestamp:010d}"
30 path.mkdir(exist_ok=True, parents=True)
31 logging.verbose(1, f"=> Writing to {path}")
32 reconstruction.write(path)
33
34
35 def has_unknown_sensor_from_rig(
36 reconstruction: Reconstruction,
37 ) -> bool:
38 parameterized_rig_ids = set()
39 for image in reconstruction.images.values():
40 parameterized_rig_ids.add(image.frame.rig_id)
41 for rig_id in parameterized_rig_ids:
42 rig = reconstruction.rig(rig_id)
43 for sensor_id, sensor_from_rig in rig.non_ref_sensors.items():
44 if (
45 sensor_id.type == pycolmap.SensorType.CAMERA
46 and sensor_from_rig is None
47 ):
48 return True
49 return False
50
51
52 def iterative_global_refinement(
53 options: IncrementalPipelineOptions,
54 mapper_options: IncrementalMapperOptions,
55 mapper: IncrementalMapper,
56 ) -> None:
57 logging.info("Retriangulation and Global bundle adjustment")
58 # The following is equivalent to mapper.iterative_global_refinement(...)
59 custom_bundle_adjustment.iterative_global_refinement(
60 mapper,
61 options.ba_global_max_refinements,
62 options.ba_global_max_refinement_change,
63 mapper_options,
64 options.get_global_bundle_adjustment(),
65 options.get_triangulation(),
66 )
67 mapper.filter_frames(mapper_options)
68
69
70 def initialize_reconstruction(
71 controller: IncrementalPipeline,
72 mapper: IncrementalMapper,
73 mapper_options: IncrementalMapperOptions,
74 reconstruction: Reconstruction,
75 ) -> IncrementalPipelineStatus:
76 """Equivalent to IncrementalPipeline.initialize_reconstruction(...)"""
77 options = controller.options
78 init_pair = (options.init_image_id1, options.init_image_id2)
79
80 # Try to find good initial pair
81 if not options.is_initial_pair_provided():
82 logging.info("Finding good initial image pair")
83 ret = mapper.find_initial_image_pair(mapper_options, *init_pair)
84 if ret is None:
85 logging.info("No good initial image pair found.")
86 return IncrementalPipelineStatus.NO_INITIAL_PAIR
87 init_pair, init_cam2_from_cam1 = ret
88 else:
89 if not all(reconstruction.exists_image(i) for i in init_pair):
90 logging.info(f"=> Initial image pair {init_pair} does not exist.")
91 return IncrementalPipelineStatus.NO_INITIAL_PAIR
92 maybe_init_cam2_from_cam1 = mapper.estimate_initial_two_view_geometry(
93 mapper_options, *init_pair
94 )
95 if maybe_init_cam2_from_cam1 is None:
96 logging.info("Provided pair is unsuitable for initialization")
97 return IncrementalPipelineStatus.BAD_INITIAL_PAIR
98 init_cam2_from_cam1 = maybe_init_cam2_from_cam1
99 logging.info(
100 f"Registering initial image pair #{init_pair[0]} and #{init_pair[1]}"
101 )
102 mapper.register_initial_image_pair(
103 mapper_options, *init_pair, init_cam2_from_cam1
104 )
105
106 tri_options = options.get_triangulation()
107 tri_options.min_angle = mapper_options.init_min_tri_angle
108 for image_id in init_pair:
109 image = reconstruction.images[image_id]
110 assert image.frame is not None
111 for data_id in image.frame.image_ids:
112 mapper.triangulate_image(tri_options, data_id.id)
113
114 logging.info("Global bundle adjustment")
115 # The following is equivalent to: mapper.adjust_global_bundle(...)
116 custom_bundle_adjustment.adjust_global_bundle(
117 mapper, mapper_options, options.get_global_bundle_adjustment()
118 )
119 reconstruction.normalize()
120 mapper.filter_points(mapper_options)
121 mapper.filter_frames(mapper_options)
122
123 # Initial image pair failed to register
124 if (
125 reconstruction.num_reg_frames() == 0
126 or reconstruction.num_points3D() == 0
127 ):
128 return IncrementalPipelineStatus.BAD_INITIAL_PAIR
129 if options.extract_colors:
130 reconstruction.extract_colors_for_all_images(options.image_path)
131 return IncrementalPipelineStatus.SUCCESS
132
133
134 def reconstruct_sub_model(
135 controller: IncrementalPipeline,
136 mapper: IncrementalMapper,
137 mapper_options: IncrementalMapperOptions,
138 reconstruction: Reconstruction,
139 ) -> IncrementalPipelineStatus:
140 """Equivalent to IncrementalPipeline.reconstruct_sub_model(...)"""
141 mapper.begin_reconstruction(reconstruction)
142
143 if has_unknown_sensor_from_rig(reconstruction):
144 return IncrementalPipelineStatus.UNKNOWN_SENSOR_FROM_RIG
145
146 if reconstruction.num_reg_frames() == 0:
147 init_status = initialize_reconstruction(
148 controller, mapper, mapper_options, reconstruction
149 )
150 if init_status != IncrementalPipelineStatus.SUCCESS:
151 return init_status
152 controller.callback(
153 IncrementalPipelineCallback.INITIAL_IMAGE_PAIR_REG_CALLBACK
154 )
155
156 options = controller.options
157
158 structure_less_flags = []
159 if options.structure_less_registration_only:
160 structure_less_flags = [True]
161 else:
162 if options.structure_less_registration_fallback:
163 structure_less_flags = [False, True]
164 else:
165 structure_less_flags = [False]
166
167 snapshot_prev_num_reg_frames = reconstruction.num_reg_frames()
168 ba_prev_num_reg_frames = reconstruction.num_reg_frames()
169 ba_prev_num_points = reconstruction.num_points3D()
170 reg_next_success, prev_reg_next_success = True, True
171 while True:
172 if not (reg_next_success or prev_reg_next_success):
173 break
174 if controller.check_reached_max_runtime():
175 break
176 prev_reg_next_success = reg_next_success
177 reg_next_success = False
178 next_image_id = None
179 for structure_less in structure_less_flags:
180 next_images = mapper.find_next_images(
181 mapper_options, structure_less=structure_less
182 )
183 for reg_trial, next_image_id in enumerate(next_images):
184 logging.info(
185 f"Registering image #{next_image_id} "
186 f"(num_reg_frames={reconstruction.num_reg_frames()})"
187 )
188 if structure_less:
189 logging.info(
190 "Registering image with structure-less fallback"
191 )
192 num_vis = (
193 mapper.observation_manager.num_visible_correspondences(
194 next_image_id
195 )
196 )
197 num_corrs = mapper.observation_manager.num_correspondences(
198 next_image_id
199 )
200 logging.info(
201 f"=> Image sees {num_vis} / {num_corrs} correspondences"
202 )
203 reg_next_success = (
204 mapper.register_next_structure_less_image(
205 mapper_options, next_image_id
206 )
207 )
208 else:
209 num_vis = mapper.observation_manager.num_visible_points3D(
210 next_image_id
211 )
212 num_obs = mapper.observation_manager.num_observations(
213 next_image_id
214 )
215 logging.info(f"=> Image sees {num_vis} / {num_obs} points")
216 reg_next_success = mapper.register_next_image(
217 mapper_options, next_image_id
218 )
219 if reg_next_success:
220 break
221 else:
222 logging.info("=> Could not register, trying another image.")
223 # If initial pair fails to continue for some time,
224 # abort and try different initial pair.
225 kMinNumInitialRegTrials = 30
226 if (
227 reg_trial >= kMinNumInitialRegTrials
228 and reconstruction.num_reg_images() < options.min_model_size
229 ):
230 break
231 if reg_next_success:
232 break
233 if reg_next_success and next_image_id is not None:
234 image = reconstruction.images[next_image_id]
235 assert image.frame is not None
236 for data_id in image.frame.image_ids:
237 mapper.triangulate_image(
238 options.get_triangulation(), data_id.id
239 )
240 # This is equivalent to mapper.iterative_local_refinement(...)
241 custom_bundle_adjustment.iterative_local_refinement(
242 mapper,
243 options.ba_local_max_refinements,
244 options.ba_local_max_refinement_change,
245 mapper_options,
246 options.get_local_bundle_adjustment(),
247 options.get_triangulation(),
248 next_image_id,
249 )
250 if controller.check_run_global_refinement(
251 reconstruction, ba_prev_num_reg_frames, ba_prev_num_points
252 ):
253 iterative_global_refinement(options, mapper_options, mapper)
254 ba_prev_num_points = reconstruction.num_points3D()
255 ba_prev_num_reg_frames = reconstruction.num_reg_frames()
256 if options.extract_colors:
257 for data_id in image.frame.image_ids:
258 if not reconstruction.extract_colors_for_image(
259 data_id.id, options.image_path
260 ):
261 logging.warning(
262 f"Could not read image "
263 f"{reconstruction.images[data_id.id].name} "
264 f"at path {options.image_path}"
265 )
266 if (
267 options.snapshot_frames_freq > 0
268 and reconstruction.num_reg_frames()
269 >= options.snapshot_frames_freq + snapshot_prev_num_reg_frames
270 ):
271 snapshot_prev_num_reg_frames = reconstruction.num_reg_frames()
272 write_snapshot(reconstruction, Path(options.snapshot_path))
273 controller.callback(
274 IncrementalPipelineCallback.NEXT_IMAGE_REG_CALLBACK
275 )
276 if mapper.num_shared_reg_images() >= int(options.max_model_overlap):
277 break
278 if (not reg_next_success) and prev_reg_next_success:
279 iterative_global_refinement(options, mapper_options, mapper)
280
281 if controller.check_reached_max_runtime():
282 return pycolmap.IncrementalPipelineStatus.INTERRUPTED
283
284 # Only run final global BA, if last incremental BA was not global
285 if (
286 reconstruction.num_reg_frames() > 0
287 and reconstruction.num_reg_frames() != ba_prev_num_reg_frames
288 and reconstruction.num_points3D() != ba_prev_num_points
289 ):
290 iterative_global_refinement(options, mapper_options, mapper)
291 return IncrementalPipelineStatus.SUCCESS
292
293
294 def reconstruct(
295 controller: IncrementalPipeline,
296 mapper: IncrementalMapper,
297 mapper_options: IncrementalMapperOptions,
298 continue_reconstruction: bool,
299 ) -> IncrementalPipelineStatus:
300 """Equivalent to IncrementalPipeline.reconstruct(...)"""
301 options = controller.options
302
303 database_cache = controller.database_cache
304 reconstruction_manager = controller.reconstruction_manager
305
306 for num_trials in range(options.init_num_trials):
307 if controller.check_reached_max_runtime():
308 break
309 if not continue_reconstruction or num_trials > 0:
310 reconstruction_idx = reconstruction_manager.add()
311 else:
312 reconstruction_idx = 0
313
314 reconstruction = reconstruction_manager.get(reconstruction_idx)
315 status = reconstruct_sub_model(
316 controller, mapper, mapper_options, reconstruction
317 )
318 if status == IncrementalPipelineStatus.INTERRUPTED:
319 reconstruction.update_point_3d_errors()
320 logging.info("Keeping reconstruction due to interrupt")
321 mapper.end_reconstruction(False)
322 pycolmap.align_reconstruction_to_orig_rig_scales(
323 database_cache.rigs, reconstruction
324 )
325 elif status == IncrementalPipelineStatus.UNKNOWN_SENSOR_FROM_RIG:
326 logging.error(
327 "Discarding reconstruction due to unknown sensor_from_rig "
328 "poses. Either explicitly define the poses by configuring the "
329 "rigs or first run reconstruction without configured rigs and "
330 "then derive the poses from the initial reconstruction for a "
331 "subsequent reconstruction with rig constraints. See "
332 "documentation for detailed instructions."
333 )
334 mapper.end_reconstruction(True)
335 reconstruction_manager.delete(reconstruction_idx)
336 return IncrementalPipelineStatus.STOP
337 elif status == IncrementalPipelineStatus.BAD_INITIAL_PAIR:
338 logging.info("Disacarding reconstruction due to bad initial pair")
339 mapper.end_reconstruction(True)
340 reconstruction_manager.delete(reconstruction_idx)
341 elif status == IncrementalPipelineStatus.NO_INITIAL_PAIR:
342 logging.info("Disacarding reconstruction due to no initial pair")
343 mapper.end_reconstruction(True)
344 reconstruction_manager.delete(reconstruction_idx)
345 return IncrementalPipelineStatus.CONTINUE
346 elif status == IncrementalPipelineStatus.SUCCESS:
347 num_reg_images = reconstruction.num_reg_images()
348 total_num_reg_images = mapper.num_total_reg_images()
349 if (
350 options.multiple_models
351 and reconstruction_manager.size() > 1
352 and num_reg_images < options.min_model_size
353 ) or num_reg_images == 0:
354 logging.info(
355 "Discarding reconstruction due to insufficient size"
356 )
357 mapper.end_reconstruction(True)
358 reconstruction_manager.delete(reconstruction_idx)
359 else:
360 reconstruction.update_point_3d_errors()
361 logging.info("Keeping successful reconstruction")
362 mapper.end_reconstruction(False)
363 pycolmap.align_reconstruction_to_orig_rig_scales(
364 database_cache.rigs, reconstruction
365 )
366 controller.callback(
367 IncrementalPipelineCallback.LAST_IMAGE_REG_CALLBACK
368 )
369 if (
370 not options.multiple_models
371 or reconstruction_manager.size() >= options.max_num_models
372 or total_num_reg_images >= database_cache.num_images() - 1
373 ):
374 return IncrementalPipelineStatus.STOP
375 else:
376 logging.fatal(f"Unknown reconstruction status: {status}")
377
378 return IncrementalPipelineStatus.CONTINUE
379
380
381 def main_incremental_mapper(controller: IncrementalPipeline) -> None:
382 """Equivalent to IncrementalPipeline.run()"""
383 timer = pycolmap.Timer()
384 timer.start()
385
386 database_cache = controller.database_cache
387
388 if database_cache.num_images() == 0:
389 logging.warning("No images with matches found in the database")
390 return
391
392 if (
393 controller.options.use_prior_position
394 and database_cache.num_pose_priors() == 0
395 ):
396 logging.warning("No pose priors")
397 return
398
399 reconstruction_manager = controller.reconstruction_manager
400
401 continue_reconstruction = reconstruction_manager.size() > 0
402 if reconstruction_manager.size() > 1:
403 logging.fatal(
404 "Can only resume from a single reconstruction, "
405 "but multiple are given"
406 )
407
408 num_images = database_cache.num_images()
409 mapper = IncrementalMapper(database_cache)
410 mapper_options = controller.options.get_mapper()
411 if (
412 reconstruct(controller, mapper, mapper_options, continue_reconstruction)
413 == IncrementalPipelineStatus.STOP
414 ):
415 return
416
417 def should_stop():
418 return (
419 mapper.num_total_reg_images() == num_images
420 or controller.check_reached_max_runtime()
421 )
422
423 for _ in range(2): # number of relaxations
424 if should_stop():
425 break
426
427 logging.info("=> Relaxing the initialization constraints")
428 mapper_options.init_min_num_inliers = int(
429 mapper_options.init_min_num_inliers / 2
430 )
431 mapper.reset_initialization_stats()
432 if (
433 reconstruct(
434 controller,
435 mapper,
436 mapper_options,
437 continue_reconstruction=False,
438 )
439 == IncrementalPipelineStatus.STOP
440 ):
441 return
442
443 if should_stop():
444 break
445
446 logging.info("=> Relaxing the initialization constraints")
447 mapper_options.init_min_tri_angle /= 2
448 mapper.reset_initialization_stats()
449 if (
450 reconstruct(
451 controller,
452 mapper,
453 mapper_options,
454 continue_reconstruction=False,
455 )
456 == IncrementalPipelineStatus.STOP
457 ):
458 return
459 timer.print_minutes()
460
461
462 def main(
463 database_path: Path,
464 image_path: Path,
465 output_path: Path,
466 options: IncrementalPipelineOptions | None = None,
467 input_path: Path | None = None,
468 ) -> dict[int, Reconstruction]:
469 if options is None:
470 options = IncrementalPipelineOptions()
471 options.image_path = image_path
472 if not database_path.exists():
473 logging.fatal(f"Database path does not exist: {database_path}")
474 if not image_path.exists():
475 logging.fatal(f"Image path does not exist: {image_path}")
476 output_path.mkdir(exist_ok=True, parents=True)
477 reconstruction_manager = ReconstructionManager()
478 if input_path:
479 reconstruction_manager.read(input_path)
480
481 with pycolmap.Database.open(database_path) as database:
482 mapper = IncrementalPipeline(options, database, reconstruction_manager)
483 num_images = database.num_images()
484 with enlighten.Manager() as manager:
485 with manager.counter(
486 total=num_images, desc="Images registered:"
487 ) as pbar:
488 pbar.update(0, force=True)
489 mapper.add_callback(
490 IncrementalPipelineCallback.INITIAL_IMAGE_PAIR_REG_CALLBACK,
491 lambda: pbar.update(2),
492 )
493 mapper.add_callback(
494 IncrementalPipelineCallback.NEXT_IMAGE_REG_CALLBACK,
495 lambda: pbar.update(1),
496 )
497 main_incremental_mapper(mapper)
498
499 # write and output
500 reconstruction_manager.write(output_path)
501 reconstructions = {}
502 for i in range(reconstruction_manager.size()):
503 reconstructions[i] = reconstruction_manager.get(i)
504 return reconstructions
505
506
507 def parse_args() -> argparse.Namespace:
508 parser = argparse.ArgumentParser()
509 parser.add_argument("--database_path", required=True)
510 parser.add_argument("--image_path", required=True)
511 parser.add_argument("--input_path", default=None)
512 parser.add_argument("--output_path", required=True)
513 return parser.parse_args()
514
515
516 if __name__ == "__main__":
517 args = parse_args()
518 main(
519 database_path=Path(args.database_path),
520 image_path=Path(args.image_path),
521 input_path=Path(args.input_path) if args.input_path else None,
522 output_path=Path(args.output_path),
523 )