| 1 |
""" |
| 2 |
Python reimplementation of the bundle adjustment for the incremental mapper of |
| 3 |
C++ with equivalent logic. As a result, one can add customized residuals on top |
| 4 |
of the exposed ceres problem from conventional bundle adjustment. |
| 5 |
""" |
| 6 |
|
| 7 |
import collections |
| 8 |
import copy |
| 9 |
|
| 10 |
import pycolmap |
| 11 |
from pycolmap import logging |
| 12 |
|
| 13 |
|
| 14 |
def solve_bundle_adjustment( |
| 15 |
reconstruction: pycolmap.Reconstruction, |
| 16 |
ba_options: pycolmap.BundleAdjustmentOptions, |
| 17 |
ba_config: pycolmap.BundleAdjustmentConfig, |
| 18 |
) -> pycolmap.BundleAdjustmentSummary: |
| 19 |
bundle_adjuster = pycolmap.create_default_bundle_adjuster( |
| 20 |
ba_options, ba_config, reconstruction |
| 21 |
) |
| 22 |
summary = bundle_adjuster.solve() |
| 23 |
# Alternatively, you can customize the existing Ceres problem or options as: |
| 24 |
# import pyceres # The minimal bindings in pycolmap aren't sufficient. |
| 25 |
# bundle_adjuster = pycolmap.create_default_ceres_bundle_adjuster( |
| 26 |
# ba_options, ba_config, reconstruction |
| 27 |
# ) |
| 28 |
# solver_options = ba_options.ceres.create_solver_options( |
| 29 |
# ba_config, bundle_adjuster.problem |
| 30 |
# ) |
| 31 |
# summary = pyceres.SolverSummary() |
| 32 |
# pyceres.solve(solver_options, bundle_adjuster.problem, summary) |
| 33 |
return summary |
| 34 |
|
| 35 |
|
| 36 |
def adjust_global_bundle( |
| 37 |
mapper: pycolmap.IncrementalMapper, |
| 38 |
mapper_options: pycolmap.IncrementalMapperOptions, |
| 39 |
ba_options: pycolmap.BundleAdjustmentOptions, |
| 40 |
) -> bool: |
| 41 |
"""Equivalent to mapper.adjust_global_bundle(...)""" |
| 42 |
reconstruction = mapper.reconstruction |
| 43 |
assert reconstruction is not None |
| 44 |
reg_frame_ids = reconstruction.reg_frame_ids() |
| 45 |
if len(reg_frame_ids) < 2: |
| 46 |
logging.fatal("At least two images must be registered for global BA") |
| 47 |
custom_ba_options = copy.deepcopy(ba_options) |
| 48 |
|
| 49 |
# Use stricter convergence criteria for first registered images |
| 50 |
if len(reg_frame_ids) < 10: # kMinNumRegImagesForFastBA = 10 |
| 51 |
custom_ba_options.ceres.solver_options.function_tolerance /= 10 |
| 52 |
custom_ba_options.ceres.solver_options.gradient_tolerance /= 10 |
| 53 |
custom_ba_options.ceres.solver_options.parameter_tolerance /= 10 |
| 54 |
custom_ba_options.ceres.solver_options.max_num_iterations *= 2 |
| 55 |
custom_ba_options.ceres.solver_options.max_linear_solver_iterations = ( |
| 56 |
200 |
| 57 |
) |
| 58 |
|
| 59 |
# Avoid degeneracies in bundle adjustment |
| 60 |
mapper.observation_manager.filter_observations_with_negative_depth() |
| 61 |
|
| 62 |
# Configure bundle adjustment |
| 63 |
ba_config = pycolmap.BundleAdjustmentConfig() |
| 64 |
for frame_id in reg_frame_ids: |
| 65 |
frame = reconstruction.frame(frame_id) |
| 66 |
for data_id in frame.data_ids: |
| 67 |
if data_id.sensor_id.type != pycolmap.SensorType.CAMERA: |
| 68 |
continue |
| 69 |
ba_config.add_image(data_id.id) |
| 70 |
|
| 71 |
# Fix the existing images, if option specified |
| 72 |
if mapper_options.fix_existing_frames: |
| 73 |
for frame_id in reg_frame_ids: |
| 74 |
if frame_id in mapper.existing_frame_ids: |
| 75 |
ba_config.set_constant_rig_from_world_pose(frame_id) |
| 76 |
|
| 77 |
for rig_id in mapper_options.constant_rigs: |
| 78 |
for sensor_id in reconstruction.rig(rig_id).non_ref_sensors: |
| 79 |
ba_config.set_constant_sensor_from_rig_pose(sensor_id) |
| 80 |
|
| 81 |
for camera_id in mapper_options.constant_cameras: |
| 82 |
ba_config.set_constant_cam_intrinsics(camera_id) |
| 83 |
|
| 84 |
# TODO: Add python support for prior positions |
| 85 |
# Fixing the gauge with two cameras leads to a more stable optimization |
| 86 |
# with fewer steps as compared to fixing three points. |
| 87 |
ba_config.fix_gauge(pycolmap.BundleAdjustmentGauge.TWO_CAMS_FROM_WORLD) |
| 88 |
|
| 89 |
# Run bundle adjustment |
| 90 |
summary = solve_bundle_adjustment( |
| 91 |
reconstruction, custom_ba_options, ba_config |
| 92 |
) |
| 93 |
logging.info("Global Bundle Adjustment") |
| 94 |
logging.info(summary.brief_report()) |
| 95 |
return summary.is_solution_usable() |
| 96 |
|
| 97 |
|
| 98 |
def iterative_global_refinement( |
| 99 |
mapper: pycolmap.IncrementalMapper, |
| 100 |
max_num_refinements: int, |
| 101 |
max_refinement_change: float, |
| 102 |
mapper_options: pycolmap.IncrementalMapperOptions, |
| 103 |
ba_options: pycolmap.BundleAdjustmentOptions, |
| 104 |
tri_options: pycolmap.IncrementalTriangulatorOptions, |
| 105 |
normalize_reconstruction: bool = True, |
| 106 |
) -> bool: |
| 107 |
"""Equivalent to mapper.iterative_global_refinement(...)""" |
| 108 |
reconstruction = mapper.reconstruction |
| 109 |
mapper.complete_and_merge_tracks(tri_options) |
| 110 |
num_retriangulated_observations = mapper.retriangulate(tri_options) |
| 111 |
logging.verbose( |
| 112 |
1, f"=> Retriangulated observations: {num_retriangulated_observations}" |
| 113 |
) |
| 114 |
for _ in range(max_num_refinements): |
| 115 |
num_observations = reconstruction.compute_num_observations() |
| 116 |
# mapper.adjust_global_bundle(mapper_options, ba_options) |
| 117 |
if not adjust_global_bundle(mapper, mapper_options, ba_options): |
| 118 |
return False |
| 119 |
if normalize_reconstruction: |
| 120 |
reconstruction.normalize() |
| 121 |
num_changed_observations = mapper.complete_and_merge_tracks(tri_options) |
| 122 |
num_changed_observations += mapper.filter_points(mapper_options) |
| 123 |
changed = ( |
| 124 |
num_changed_observations / num_observations |
| 125 |
if num_observations > 0 |
| 126 |
else 0 |
| 127 |
) |
| 128 |
logging.verbose(1, f"=> Changed observations: {changed:.6f}") |
| 129 |
if changed < max_refinement_change: |
| 130 |
break |
| 131 |
return True |
| 132 |
|
| 133 |
|
| 134 |
def adjust_local_bundle( |
| 135 |
mapper: pycolmap.IncrementalMapper, |
| 136 |
mapper_options: pycolmap.IncrementalMapperOptions, |
| 137 |
ba_options: pycolmap.BundleAdjustmentOptions, |
| 138 |
tri_options: pycolmap.IncrementalTriangulatorOptions, |
| 139 |
image_id: int, |
| 140 |
point3D_ids: set[int], |
| 141 |
) -> pycolmap.LocalBundleAdjustmentReport: |
| 142 |
"""Equivalent to mapper.adjust_local_bundle(...)""" |
| 143 |
reconstruction = mapper.reconstruction |
| 144 |
assert reconstruction is not None |
| 145 |
report = pycolmap.LocalBundleAdjustmentReport() |
| 146 |
|
| 147 |
# Find images that have most 3D points with given image in common |
| 148 |
local_bundle = mapper.find_local_bundle(mapper_options, image_id) |
| 149 |
image_ids = set() |
| 150 |
|
| 151 |
# Do the bundle adjustment only if there is any connected images |
| 152 |
if local_bundle: |
| 153 |
ba_config = pycolmap.BundleAdjustmentConfig() |
| 154 |
ba_config.fix_gauge(pycolmap.BundleAdjustmentGauge.THREE_POINTS) |
| 155 |
|
| 156 |
# Insert the images of all local frames. |
| 157 |
image = reconstruction.image(image_id) |
| 158 |
frame_ids = {image.frame_id} |
| 159 |
assert image.frame is not None |
| 160 |
for data_id in image.frame.image_ids: |
| 161 |
ba_config.add_image(data_id.id) |
| 162 |
for local_image_id in local_bundle: |
| 163 |
local_image = reconstruction.image(local_image_id) |
| 164 |
frame_ids.add(local_image.frame_id) |
| 165 |
assert local_image.frame is not None |
| 166 |
for data_id in local_image.frame.image_ids: |
| 167 |
ba_config.add_image(data_id.id) |
| 168 |
|
| 169 |
# Fix the existing images, if options specified |
| 170 |
if mapper_options.fix_existing_frames: |
| 171 |
for frame_id in frame_ids: |
| 172 |
if frame_id in mapper.existing_frame_ids: |
| 173 |
ba_config.set_constant_rig_from_world_pose(frame_id) |
| 174 |
|
| 175 |
# Fix rig poses, if not all frames within the local bundle. |
| 176 |
num_frames_per_rig: dict[int, int] = collections.defaultdict(int) |
| 177 |
for frame_id in frame_ids: |
| 178 |
frame = reconstruction.frame(frame_id) |
| 179 |
num_frames_per_rig[frame.rig_id] += 1 |
| 180 |
for rig_id, num_frames_local in num_frames_per_rig.items(): |
| 181 |
if ( |
| 182 |
rig_id in mapper_options.constant_rigs |
| 183 |
or num_frames_local < mapper.num_reg_frames_per_rig[rig_id] |
| 184 |
): |
| 185 |
for sensor_id in reconstruction.rig(rig_id).non_ref_sensors: |
| 186 |
ba_config.set_constant_sensor_from_rig_pose(sensor_id) |
| 187 |
|
| 188 |
# Fix camera intrinsics, if not all images within local bundle. |
| 189 |
num_images_per_camera: dict[int, int] = collections.defaultdict(int) |
| 190 |
for image_id in ba_config.images: |
| 191 |
image = reconstruction.images[image_id] |
| 192 |
num_images_per_camera[image.camera_id] += 1 |
| 193 |
for camera_id, num_images_local in num_images_per_camera.items(): |
| 194 |
if ( |
| 195 |
camera_id in mapper_options.constant_cameras |
| 196 |
or num_images_local |
| 197 |
< mapper.num_reg_images_per_camera[camera_id] |
| 198 |
): |
| 199 |
ba_config.set_constant_cam_intrinsics(camera_id) |
| 200 |
|
| 201 |
# Make sure, we refine all new and short-track 3D points, no matter if |
| 202 |
# they are fully contained in the local image set or not. Do not include |
| 203 |
# long track 3D points as they are usually already very stable and |
| 204 |
# adding to them to bundle adjustment and track merging/completion would |
| 205 |
# slow down the local bundle adjustment significantly. |
| 206 |
variable_point3D_ids = set() |
| 207 |
for point3D_id in list(point3D_ids): |
| 208 |
point3D = reconstruction.point3D(point3D_id) |
| 209 |
kMaxTrackLength = 15 |
| 210 |
if ( |
| 211 |
point3D.error == -1.0 |
| 212 |
) or point3D.track.length() <= kMaxTrackLength: |
| 213 |
ba_config.add_variable_point(point3D_id) |
| 214 |
variable_point3D_ids.add(point3D_id) |
| 215 |
|
| 216 |
# Adjust the local bundle |
| 217 |
summary = solve_bundle_adjustment( |
| 218 |
mapper.reconstruction, ba_options, ba_config |
| 219 |
) |
| 220 |
logging.info("Local Bundle Adjustment") |
| 221 |
logging.info(summary.brief_report()) |
| 222 |
|
| 223 |
image_ids = ba_config.images |
| 224 |
report.num_adjusted_observations = int(summary.num_residuals / 2) |
| 225 |
# Merge refined tracks with other existing points |
| 226 |
report.num_merged_observations = mapper.triangulator.merge_tracks( |
| 227 |
tri_options, variable_point3D_ids |
| 228 |
) |
| 229 |
# Complete tracks that may have failed to triangulate before refinement |
| 230 |
# of camera pose and calibration in bundle adjustment. This may avoid |
| 231 |
# that some points are filtered and helps for subsequent image |
| 232 |
# registrations. |
| 233 |
report.num_completed_observations = mapper.triangulator.complete_tracks( |
| 234 |
tri_options, variable_point3D_ids |
| 235 |
) |
| 236 |
report.num_completed_observations += mapper.triangulator.complete_image( |
| 237 |
tri_options, image_id |
| 238 |
) |
| 239 |
|
| 240 |
report.num_filtered_observations = ( |
| 241 |
mapper.observation_manager.filter_points3D_in_images( |
| 242 |
mapper_options.filter_max_reproj_error, |
| 243 |
mapper_options.filter_min_tri_angle, |
| 244 |
image_ids, |
| 245 |
) |
| 246 |
) |
| 247 |
report.num_filtered_observations += ( |
| 248 |
mapper.observation_manager.filter_points3D( |
| 249 |
mapper_options.filter_max_reproj_error, |
| 250 |
mapper_options.filter_min_tri_angle, |
| 251 |
point3D_ids, |
| 252 |
) |
| 253 |
) |
| 254 |
return report |
| 255 |
|
| 256 |
|
| 257 |
def iterative_local_refinement( |
| 258 |
mapper: pycolmap.IncrementalMapper, |
| 259 |
max_num_refinements: int, |
| 260 |
max_refinement_change: float, |
| 261 |
mapper_options: pycolmap.IncrementalMapperOptions, |
| 262 |
ba_options: pycolmap.BundleAdjustmentOptions, |
| 263 |
tri_options: pycolmap.IncrementalTriangulatorOptions, |
| 264 |
image_id: int, |
| 265 |
) -> None: |
| 266 |
"""Equivalent to mapper.iterative_local_refinement(...)""" |
| 267 |
custom_ba_options = copy.deepcopy(ba_options) |
| 268 |
for _ in range(max_num_refinements): |
| 269 |
# report = mapper.adjust_local_bundle( |
| 270 |
# mapper_options, |
| 271 |
# custom_ba_options, |
| 272 |
# tri_options, |
| 273 |
# image_id, |
| 274 |
# mapper.get_modified_points3D(), |
| 275 |
# ) |
| 276 |
report = adjust_local_bundle( |
| 277 |
mapper, |
| 278 |
mapper_options, |
| 279 |
custom_ba_options, |
| 280 |
tri_options, |
| 281 |
image_id, |
| 282 |
mapper.get_modified_points3D(), |
| 283 |
) |
| 284 |
logging.verbose( |
| 285 |
1, f"=> Merged observations: {report.num_merged_observations}" |
| 286 |
) |
| 287 |
logging.verbose( |
| 288 |
1, f"=> Completed observations: {report.num_completed_observations}" |
| 289 |
) |
| 290 |
logging.verbose( |
| 291 |
1, f"=> Filtered observations: {report.num_filtered_observations}" |
| 292 |
) |
| 293 |
changed = 0.0 |
| 294 |
if report.num_adjusted_observations > 0: |
| 295 |
changed = ( |
| 296 |
report.num_merged_observations |
| 297 |
+ report.num_completed_observations |
| 298 |
+ report.num_filtered_observations |
| 299 |
) / report.num_adjusted_observations |
| 300 |
logging.verbose(1, f"=> Changed observations: {changed:.6f}") |
| 301 |
if changed < max_refinement_change: |
| 302 |
break |
| 303 |
|
| 304 |
# Only use robust cost function for first iteration |
| 305 |
custom_ba_options.ceres.loss_function_type = ( |
| 306 |
pycolmap.LossFunctionType.TRIVIAL |
| 307 |
) |
| 308 |
mapper.clear_modified_points3D() |