Bundle adjustment¶
Bundle adjustment (BA) jointly refines camera poses (and optionally intrinsics) and 3D points by minimizing reprojection error (and optional priors), usually with Ceres Solver. In Theia this is centered on BundleAdjustmentOptions, BundleAdjustmentSummary, and high-level functions that take a Reconstruction.
C++: src/theia/sfm/bundle_adjustment/bundle_adjustment.h, incremental builder bundle_adjuster.h.
Python: pytheia.sfm — options, summaries, Ceres enums, and BundleAdjust* wrappers; see Python API overview.
What is optimized¶
- Extrinsics: camera orientation and position (per
View) unless marked constant in options. - Structure:
Track3D positions (homogeneous or inverse-depth depending on options). - Intrinsics: only parameters selected by
OptimizeIntrinsicsTypebitmask (FOCAL_LENGTH,PRINCIPAL_POINTS, distortion flags,NONE,ALL, etc.). Defaults are conservative (often no intrinsics optimization).
Optional priors in BundleAdjustmentOptions: position, orientation, gravity, depth—enable only when you have reliable metadata.
High-level entry points¶
Python (pt.sfm) |
Effect |
|---|---|
BundleAdjustReconstruction |
Full BA: all estimated views and tracks in the reconstruction. |
BundleAdjustPartialReconstruction |
Only the given view and track ID sets (plus their incident residuals). |
BundleAdjustPartialViewsConstant |
Some views variable, others held fixed (see C++ signature). |
BundleAdjustReconstructionWithConstantTracks |
Full BA on all estimated views and tracks, but holds the given track IDs fixed (control points). Useful when importing 3D points from another reconstruction to pin cameras into that frame through reprojection while the points themselves do not move. |
BundleAdjustReconstructionWithRelativePoseEdges |
Full BA (cameras + points + reprojection + view priors) plus optional SE3 relative pose-to-pose edges between view pairs. See Relative pose edges. |
BundleAdjustView / BundleAdjustViews |
Local BA around one or more views. |
BundleAdjustTrack / BundleAdjustTracks |
Refine selected tracks (and connected cameras). |
BundleAdjustTwoViewsAngular |
Specialized two-view angular / relative adjustment. |
Variants suffixed with WithCov return empirical covariance blocks for tracks or views (C++ overloads wrapped in Python).
BundleAdjustmentOptions¶
Defaults below are from bundle_adjustment.h (C++). In pyTheia, all listed fields are exposed on pt.sfm.BundleAdjustmentOptions except where noted. Ceres enumerators are re-exported under pt.sfm (e.g. pt.sfm.LinearSolverType.SPARSE_SCHUR).
Ceres linear solver (linear_solver_type)¶
Maps to ceres::SolverOptions::linear_solver_type. Exposed as LinearSolverType in Python.
| Value | Role (short) |
|---|---|
DENSE_QR |
Dense normal equations via QR. Small problems only. |
DENSE_NORMAL_CHOLESKY |
Dense normal equations + Cholesky. Small / dense structure. |
DENSE_SCHUR |
Dense Schur complement elimination. Medium problems; uses dense linear algebra backend. |
SPARSE_NORMAL_CHOLESKY |
Sparse Cholesky on the normal equations. |
SPARSE_SCHUR |
Sparse Schur complement (default in BundleAdjustmentOptions). Good default for many SfM-sized problems. |
ITERATIVE_SCHUR |
Iterative Schur + preconditioner; preferred for very large camera counts when memory or factorization cost bites. |
CGNR |
CGNR on the reduced camera system. |
Practical note: Header comments suggest considering ITERATIVE_SCHUR when you have on the order of \(> 1000\) cameras. Pair it with a Schur-appropriate preconditioner_type (often SCHUR_JACOBI or a cluster preconditioner for iterative Schur). See also the Ceres documentation on solvers.
Preconditioner (preconditioner_type)¶
Exposed as PreconditionerType.
| Value | Typical use |
|---|---|
IDENTITY |
No preconditioning (rarely best for large BA). |
JACOBI |
Jacobi preconditioner. |
SCHUR_JACOBI |
Default. Schur–Jacobi; works well with Schur-based solvers. |
CLUSTER_JACOBI |
Clustering-based Jacobi; used with ITERATIVE_SCHUR and visibility clustering. |
CLUSTER_TRIDIAGONAL |
Cluster tridiagonal preconditioner; likewise for iterative Schur + clusters. |
Visibility clustering (visibility_clustering_type)¶
Used when the preconditioner uses clusters (CLUSTER_*). Exposed as VisibilityClusteringType.
| Value | Meaning |
|---|---|
CANONICAL_VIEWS |
Default. Ceres “canonical views” clustering. |
SINGLE_LINKAGE |
Single-linkage style clustering. |
Dense and sparse linear algebra libraries¶
These select which library implements dense/sparse factorization and mat-vec work inside Ceres. Exposed as DenseLinearAlgebraLibraryType and SparseLinearAlgebraLibraryType.
Dense (dense_linear_algebra_library_type) — default EIGEN
| Value | Notes |
|---|---|
EIGEN |
Eigen dense linear algebra (default). |
LAPACK |
LAPACK-backed dense solves (if Ceres built with it). |
CUDA |
GPU dense linear algebra — only if Ceres was compiled with CUDA and pyTheia was built with THEIA_CERES_HAS_CUDA_DENSE. Otherwise unavailable in Python. |
Sparse (sparse_linear_algebra_library_type) — default EIGEN_SPARSE
| Value | Notes |
|---|---|
SUITE_SPARSE |
SuiteSparse (CHOLMOD etc.) when Ceres links it. |
EIGEN_SPARSE |
Eigen sparse (default). |
ACCELERATE_SPARSE |
Apple Accelerate sparse (platform-specific). |
CUDA_SPARSE |
GPU sparse — only if Ceres has CUDA sparse and pyTheia defines THEIA_CERES_HAS_CUDA_SPARSE. |
CUDA / GPU usage¶
GPU backends are optional and depend entirely on your Ceres build and Theia’s CMake detecting CUDA support:
- For dense Schur-style solvers (e.g.
DENSE_SCHUR), setdense_linear_algebra_library_type = CUDAwhen available. - For sparse solvers (e.g.
SPARSE_SCHUR,ITERATIVE_SCHUR), setsparse_linear_algebra_library_type = CUDA_SPARSEwhen available.
If CUDA was not enabled in Ceres, these settings either do not exist in the Python module or will not accelerate solves. num_threads still controls Ceres’ CPU parallelism.
Robust loss (loss_function_type, widths)¶
loss_function_type — exposed as LossFunctionType (TRIVIAL, HUBER, SOFTLONE, CAUCHY, ARCTAN, TUKEY). Implemented in create_loss_function.cc.
| Value | Effect |
|---|---|
TRIVIAL |
Pure \(L_2\) on reprojection residuals (sensitive to outlier observations; was the default before 1.3.2). |
HUBER |
Huber; transitions at robust_loss_width (default since 1.3.2, width 1.0 px). |
SOFTLONE |
SoftLOneLoss with scale robust_loss_width. |
CAUCHY |
Cauchy robust loss. |
ARCTAN |
Arctan robust loss. |
TUKEY |
Tukey; errors beyond the width are effectively capped. |
Widths
robust_loss_width— default2.0inBundleAdjustmentOptions; pipeline defaults fromReconstructionEstimatorOptionsoften use10.0forbundle_adjustment_robust_loss_width(see below).robust_loss_width_depth_prior— default0.01; scale for robust treatment of depth priors when enabled.
C++ also defines LossFunctionType::TRUNCATED (TruncatedLoss); it is not currently exposed in pybind.
Intrinsics bitmask (intrinsics_to_optimize)¶
OptimizeIntrinsicsType is a bitmask (combine with | in C++; in Python use | on enum values).
| Flag | Bit |
|---|---|
NONE |
Optimize no intrinsics (default on raw BundleAdjustmentOptions). |
FOCAL_LENGTH |
|
ASPECT_RATIO |
|
SKEW |
|
PRINCIPAL_POINTS |
|
RADIAL_DISTORTION |
|
TANGENTIAL_DISTORTION |
|
DISTORTION |
Alias: radial | tangential. |
FOCAL_LENGTH_DISTORTION |
Focal + both distortions. |
FOCAL_LENGTH_RADIAL_DISTORTION |
Focal + radial. |
ALL |
All of the above. |
Pipeline default (ReconstructionEstimatorOptions): FOCAL_LENGTH | RADIAL_DISTORTION — stricter than the bare BundleAdjustmentOptions default.
3D point parametrization¶
| Field | Default | Meaning |
|---|---|---|
use_homogeneous_point_parametrization |
true |
Homogeneous point with local tangent (manifold) updates; 4D state with 3 DOF increments. |
use_inverse_depth_parametrization |
false |
If true, inverse-depth parametrization is used and use_homogeneous_point_parametrization is ignored (per header). |
Inverse-depth parametrization¶
With use_inverse_depth_parametrization = True every track is anchored in a reference view (Track.ReferenceViewId(), by default the first view that observed it). The point is stored as a unit reference bearing vector (Track.ReferenceBearingVector(), the viewing ray of the reference observation) and one scalar inverse depth \(\rho = 1 / \lVert R_{ref}(X - c_{ref}) \rVert\), the inverse distance between the reference camera center and the point (Track.InverseDepth(); 0 is a point at infinity). The residual of another view is the usual reprojection error of \(X = c_{ref} + R_{ref}^T\, b / \rho\); it is evaluated without any division as the projection of \(R_{o} R_{ref}^T\, b + \rho\, R_{o}(c_{ref} - c_{o})\), so it matches the XYZ residual at the same point for every central camera model. \(\rho\) has a lower bound of 0.
- Initialization is automatic. Before a track is added to the problem the reference view, the bearing and \(\rho\) are re-derived from the current 3D point (
Reconstruction.InitializeTrackInverseDepth(track_id)), so you no longer have to callReconstruction.InitializeInverseDepth()first and poses that changed since then cannot leave stale anchors. A track that cannot be represented (no estimated reference view, point behind the reference ray, orthographic camera, no observation besides the reference view) is skipped and its 3D point is left untouched. - After the solve the 3D point of every optimized track is rewritten from \(\rho\). When you optimize with the XYZ parametrization, the bearing and \(\rho\) are refreshed from the points, so both representations stay in sync.
- Partial entry points.
BundleAdjustPartialReconstructionandBundleAdjustPartialViewsConstantkeep all views that are not listed constant, as with XYZ points.BundleAdjustReconstructionWithConstantTracksalways uses XYZ points (a point anchored to a moving reference camera cannot act as a fixed control point). - Limitations. The ray through the reference observation is computed once with the current intrinsics. If you optimize intrinsics together with inverse depths, the bearing vectors do not follow the intrinsics during that solve; use
intrinsics_to_optimize = NONEor an XYZ solve for intrinsics. The reference observation itself has no information on the inverse depth, and the point is forced onto the reference ray, so with noisy observations the cost is higher than with XYZ points (3 degrees of freedom per point). Orthographic cameras and depth priors are not supported; covariance queries always use XYZ points.
When you run incremental / global reconstruction, the pipeline sets these from TrackParametrizationType (XYZW, XYZW_MANIFOLD, INVERSE_DEPTH) via SetBundleAdjustmentOptions — see SfM.
Analytic Jacobians (analytic_jacobians)¶
| Field | Default | Meaning |
|---|---|---|
analytic_jacobians |
true |
Use hand-derived Jacobians for the reprojection residuals instead of Ceres automatic differentiation. |
Covered camera models: PINHOLE, PINHOLE_RADIAL_TANGENTIAL, FISHEYE, DOUBLE_SPHERE, EXTENDED_UNIFIED, FOV, DIVISION_UNDISTORTION, FULL_OPENCV, RADIAL_FISHEYE, THIN_PRISM_FISHEYE and RAD_TAN_THIN_PRISM_FISHEYE. This applies to the homogeneous XYZ residual (extrinsics, intrinsics and the 4-vector point; Ceres applies the SphereManifold) and to the inverse-depth residuals (reference-view and other-view residual, including the pose-only variant), and to the reprojection residuals of BundleAdjustTwoViews. The residuals, the whitening by the feature covariance and the handling of invalid points (point at the camera center, behind a double-sphere / unified camera, FOV / fisheye branches) are the same as in the autodiff versions; Jacobians agree with autodiff to about 1e-8 relative (checked over many random evaluations for every model). ORTHOGRAPHIC cameras, Sim3 residuals and all prior / relative-pose / depth-prior residuals still use autodiff.
The Jacobian and residual phase of a Ceres iteration is about 3x faster single-threaded (about 2x with 8 threads). Measured Ceres solve time (median over the models, 1 thread): about 4x for pose refinement with constant points, 2.3-2.9x for 3 to 10 views, 1.7x for 40 views / 5000 tracks with the XYZ parametrization (3-5x with inverse depth); with 8 threads about 1.2-2.3x. On large problems the sparse linear solve dominates and the gain tends to 1.1x. Set analytic_jacobians = False to fall back to autodiff everywhere, e.g. to compare results or when you add a camera model without an analytic implementation (models without one use autodiff automatically).
!!! note "SuiteSparse is intentionally not used"
pyTheia does not use SuiteSparse / CHOLMOD (GPL) anywhere in its own code, and the wheels do not link it. The sparse linear solves use Eigen (EIGEN_SPARSE) or, in a local build, CUDA backends. The analytic Jacobians are one of the measures that make the BA cheaper without a GPL dependency. SUITE_SPARSE in sparse_linear_algebra_library_type is only available if you build against a Ceres that was compiled with SuiteSparse yourself.
Camera constants, trajectory mode, orthographic¶
| Field | Default | Meaning |
|---|---|---|
constant_camera_orientation |
false |
Fix all camera rotations. |
constant_camera_position |
false |
Fix all camera positions. |
optimize_for_forward_facing_trajectory |
false |
Merge intrinsics + extrinsics into one parameter block for forward-facing trajectories. |
orthographic_camera |
false |
Use orthographic camera residuals where applicable. |
Priors¶
| Field | Default | Meaning |
|---|---|---|
use_position_priors |
false |
Add position prior residuals (metadata must be present on views). |
use_orientation_priors |
false |
Orientation priors. |
use_depth_priors |
false |
Depth priors (uses robust_loss_width_depth_prior when robust). |
use_gravity_priors |
false |
Gravity-aligned orientation priors. |
gravity_prior_error_type |
DIRECTION_CROSS |
VECTOR_DIFF (legacy 3-vector) or DIRECTION_CROSS (cross product, 2-DOF). |
use_point_priors |
false |
Add 3D point (track position) prior residuals. See 3D point priors. |
robust_loss_width_point_prior |
0.0 |
Width of the robust loss on point prior residuals; 0 means no robust loss. |
Feature uncertainty (covariance and accuracy)¶
Every Feature carries a 2x2 covariance in px^2. The reprojection residual is whitened with it, so the optimizer minimizes the Mahalanobis distance of the observation (correlated noise is handled by the off-diagonal term). The default is the identity, which gives plain pixel residuals. A feature that is located less accurately gets a larger covariance and pulls less on the solution.
import numpy as np
import pytheia as pt
# keyword arguments work on all constructors and methods
f = pt.sfm.Feature(point=np.array([410.5, 233.2]), covariance=np.diag([1.0, 4.0]))
g = pt.sfm.Feature(np.array([100.0, 50.0]))
g.set_isotropic_sigma(2.5) # covariance = 2.5^2 * I (sigma in px)
W = g.sqrt_information() # W^T W = covariance^-1
A natural choice for SIFT is a sigma proportional to the keypoint scale. The covariance is used in the bundle adjustment residuals only; two-view RANSAC, triangulation and PnP ignore it.
Setting priors on View (Python)¶
Priors are stored per view and only take effect when the matching use_*_priors flag is enabled on BundleAdjustmentOptions:
import numpy as np
import pytheia as pt
view = reconstruction.View(view_id)
# sqrt-information matrices (not covariance): larger diagonal = stronger pull.
info_pos = np.eye(3) * 60.0 # units 1/m
info_rot = np.eye(3) * 40.0 # units 1/rad
view.SetPositionPrior(target_camera_center, info_pos)
view.SetOrientationPrior(target_world_to_cam_angle_axis, info_rot)
opts = pt.sfm.BundleAdjustmentOptions()
opts.use_position_priors = True
opts.use_orientation_priors = True
summary = pt.sfm.BundleAdjustReconstruction(opts, reconstruction)
GetPositionPrior, GetPositionPriorSqrtInformation, GetOrientationPrior, GetOrientationPriorSqrtInformation, and HasPositionPrior / HasOrientationPrior are also exposed. Position priors compare against Camera::GetPosition(); orientation priors compare against the world→camera angle-axis in Camera::GetOrientation().
3D point priors (ground control points, known points)¶
A Track can carry a prior on its 3D position, for example a surveyed ground control point or a LiDAR point. With use_point_priors = True, every optimized track that has a prior adds the residual S (X - prior), where X is the Euclidean point (xyz / w of the homogeneous parameter) and S is the sqrt information. Tracks held constant (for example in BundleAdjustReconstructionWithConstantTracks) get no prior residual.
import numpy as np
import pytheia as pt
track = reconstruction.MutableTrack(track_id)
# Units: the prior position is in the reconstruction's units (usually meters).
# Covariance in m^2; the sqrt information is computed as S with S^T S = Sigma^-1.
ok = track.SetPositionPriorCovariance(
np.array([12.40, -3.10, 55.02]), # prior position X_gcp
np.diag([0.01**2, 0.01**2, 0.03**2]), # 1 cm in x/y, 3 cm in z (1-sigma)
)
assert ok # False if the covariance is not symmetric positive definite
# Or set the sqrt information directly (larger = stronger pull, units 1/m):
# track.SetPositionPrior(X_gcp, np.diag([100.0, 100.0, 33.3]))
print(track.HasPositionPrior(), track.PositionPrior(), track.PositionPriorSqrtInformation())
opts = pt.sfm.BundleAdjustmentOptions()
opts.use_point_priors = True
opts.robust_loss_width_point_prior = 0.0 # 0 (default): plain quadratic residual
summary = pt.sfm.BundleAdjustReconstruction(opts, reconstruction)
track.RemovePositionPrior() # back to no prior
Notes:
- The residual is whitened by the sqrt information
S(a 3x3 upper-triangular factor from the Cholesky decomposition of the information matrix when built from a covariance). UseSetPositionPriorCovarianceif you have covariances;SetPositionPriortakes the sqrt information directly, like the view priors do. - Tracks with a prior are only constrained when they are optimized (
BundleAdjustReconstruction,BundleAdjustTracks, and the other entry points that add the track). A track that is held constant gets no prior residual. - Point priors are only supported with the homogeneous point parametrization (
use_homogeneous_point_parametrization = True, the default). Withuse_inverse_depth_parametrization = Truethey are not supported: the priors are ignored and a warning is logged once. - The point prior is part of the Ceres problem, so the covariance returned by
GetCovarianceForTrack/GetCovarianceForTracksincludes it. - The priors are stored in the track and written with
WriteReconstruction(archive version 2); reconstructions written by older versions load without priors.
Iterations, stopping, trust region, refinement¶
| Field | Default | Meaning |
|---|---|---|
verbose |
false |
Ceres logging (PER_MINIMIZER_ITERATION vs silent). |
num_threads |
hardware_concurrency() |
Ceres thread count (overridden when BA is invoked from ReconstructionEstimatorOptions.num_threads). |
max_num_iterations |
100 |
Max optimizer iterations (pipeline default is often 50 via reconstruction options). |
max_solver_time_in_seconds |
3600 |
Wall-clock cap for the solver. |
use_inner_iterations |
true |
Ceres inner iterations (can improve convergence). |
function_tolerance |
1e-6 |
Stop when relative cost change is small. |
gradient_tolerance |
1e-10 |
Gradient norm tolerance. |
parameter_tolerance |
1e-8 |
Step tolerance. |
max_trust_region_radius |
1e12 |
Trust-region radius cap. |
use_mixed_precision_solves |
false |
Ceres mixed-precision iterative refinement. |
max_num_refinement_iterations |
2 |
Refinement iterations when mixed precision is on. |
Full field list (quick reference)¶
| Field | Default (C++ BundleAdjustmentOptions) |
|---|---|
loss_function_type |
HUBER |
robust_loss_width |
1.0 |
robust_loss_width_depth_prior |
0.01 |
linear_solver_type |
SPARSE_SCHUR |
preconditioner_type |
SCHUR_JACOBI |
visibility_clustering_type |
CANONICAL_VIEWS |
dense_linear_algebra_library_type |
EIGEN |
sparse_linear_algebra_library_type |
EIGEN_SPARSE |
optimize_for_forward_facing_trajectory |
false |
use_mixed_precision_solves |
false |
max_num_refinement_iterations |
2 |
verbose |
false |
constant_camera_orientation |
false |
constant_camera_position |
false |
use_homogeneous_point_parametrization |
true |
use_inverse_depth_parametrization |
false |
analytic_jacobians |
true |
intrinsics_to_optimize |
NONE |
num_threads |
hardware concurrency |
max_num_iterations |
100 |
max_solver_time_in_seconds |
3600 |
use_inner_iterations |
true |
function_tolerance |
1e-6 |
gradient_tolerance |
1e-10 |
parameter_tolerance |
1e-8 |
max_trust_region_radius |
1e12 |
use_position_priors |
false |
use_orientation_priors |
false |
use_depth_priors |
false |
orthographic_camera |
false |
use_gravity_priors |
false |
TwoViewBundleAdjustmentOptions¶
Used by BundleAdjustTwoViews (C++); Python exposes pt.sfm.TwoViewBundleAdjustmentOptions with:
ba_options— a nestedBundleAdjustmentOptions.constant_camera1_intrinsics/constant_camera2_intrinsics— defaulttrue(hold intrinsics fixed per camera).
BundleAdjustTwoViewsAngular takes a plain BundleAdjustmentOptions (angular / epipolar formulation; see C++ header). RANSAC local optimization for calibrated / monodepth relative pose no longer calls this path; it uses dense LM instead (RANSAC — local optimization).
Pipeline-level BA settings (ReconstructionEstimatorOptions)¶
When you use incremental / global / hybrid reconstruction, bundle adjustment is configured from ReconstructionEstimatorOptions. These fields are copied into BundleAdjustmentOptions by SetBundleAdjustmentOptions (see reconstruction_estimator_utils.cc):
| Field | Role |
|---|---|
bundle_adjustment_loss_function_type |
Maps to loss_function_type. |
bundle_adjustment_robust_loss_width |
Maps to robust_loss_width (default 10.0 here vs 2.0 on raw BA options). |
intrinsics_to_optimize |
Same bitmask as BA. |
track_parametrization_type |
Sets use_homogeneous_point_parametrization / use_inverse_depth_parametrization. |
dense_linear_algebra_library_type |
Same as BA. |
sparse_linear_algebra_library_type |
Same as BA. |
linear_solver_type |
Same as BA. |
preconditioner_type |
Same as BA. |
visibility_clustering_type |
Same as BA. |
max_num_iterations |
BA iteration cap (default 50 in reconstruction options). |
use_inner_iterations |
Passed through (stored as int in the struct). |
optimize_for_forward_facing_trajectory |
Passed through. |
num_threads |
Sets BA num_threads. |
Scheduling / quality trade-offs (do not map 1:1 to a single BundleAdjustmentOptions field):
full_bundle_adjustment_growth_percent— how much the model grows before a full BA (incremental/hybrid).partial_bundle_adjustment_num_views— window size for partial BA.subsample_tracks_for_bundle_adjustmentand related track selection thresholds — reduce the number of 3D points in BA.bundle_adjust_tracks— BA immediately after triangulating a track (triangulation path).num_retriangulation_iterations— global pipeline: retriangulation + full BA rounds.
min_cameras_for_iterative_solver is documented on ReconstructionEstimatorOptions (default 1000) as a threshold for switching to iterative Schur, but SetBundleAdjustmentOptions does not apply it automatically — you still choose linear_solver_type explicitly if you want ITERATIVE_SCHUR.
BundleAdjuster (incremental / custom subsets)¶
BundleAdjuster(options, reconstruction) builds a Ceres problem explicitly:
AddView(view_id)— include this view’s parameters and reprojection residuals for observed tracks.AddTrack(track_id)— include this point (must be consistent with added views).Optimize()— run the solver.
Use this when the convenience BundleAdjust* functions do not match your scheduling (e.g. sliding-window BA).
AddRelativePoseConstraint(view_id_i, view_id_j, sqrt_information)— add an SE3 relative pose edge between two views that were already added viaAddView(). The measured relative pose (camera i → camera j) is snapshotted from the current extrinsics at setup time, so the edge preserves the present local odometry while absolute priors or reprojection terms move the trajectory. The 6×6sqrt_informationuses Sophus tangent order [translation(3), rotation(3)].
Relative pose edges¶
BundleAdjustReconstructionWithRelativePoseEdges runs the same full reconstruction BA as BundleAdjustReconstruction (all estimated views and tracks, plus any view position/orientation priors), and additionally adds SE3 pose-to-pose constraints between specified view pairs.
RelativePoseConstraint (Python: pt.sfm.RelativePoseConstraint)¶
| Field | Meaning |
|---|---|
view_id_i |
First view in the edge (camera i). |
view_id_j |
Second view (camera j). |
translation_sqrt_weight |
Diagonal sqrt-information for the translation part of the SE3 log residual (1/m). Used when scale_invariant_translation is False. |
rotation_sqrt_weight |
Diagonal sqrt-information for the rotation part (1/rad). |
scale_invariant_translation |
If True, use ScaledRelativePoseError instead of the full SE3 translation log. |
translation_direction_sqrt_weight |
Weight on \(\mathbf{t}_{\mathrm{pred}} \times \mathbf{t}_{\mathrm{meas}}\) (unit translation vectors). |
translation_magnitude_sqrt_weight |
Weight on \(\log(\|\mathbf{t}_{\mathrm{pred}}\|/\|\mathbf{t}_{\mathrm{meas}}\|)\); set to 0 for scale-free odometry along the chain. |
At solve time the implementation builds world→camera poses from each view’s extrinsics ([position(3), orientation angle-axis(3)]), forms the predicted relative pose \(\mathbf{g}_{j\leftarrow i} = \mathbf{g}_j\,\mathbf{g}_i^{-1}\), and compares it to the fixed measurement \(\hat{\mathbf{g}}_{j\leftarrow i}\) snapshotted at edge creation.
Full motivation and math: Cross-run alignment.
Example: stiffen a trajectory during prior-BA¶
import pytheia as pt
# ... set position/orientation priors on anchor views, enable use_position_priors /
# use_orientation_priors on opts as above ...
edges = []
for vid_i, vid_j in consecutive_frame_pairs: # your ordering
e = pt.sfm.RelativePoseConstraint()
e.view_id_i = vid_i
e.view_id_j = vid_j
e.translation_sqrt_weight = 30.0
e.rotation_sqrt_weight = 100.0
edges.append(e)
opts = pt.sfm.BundleAdjustmentOptions()
opts.use_position_priors = True
opts.use_orientation_priors = True
opts.use_homogeneous_point_parametrization = True
opts.loss_function_type = pt.sfm.LossFunctionType.HUBER
# Relative edges couple two camera blocks; prefer SPARSE_SCHUR + EIGEN_SPARSE
# for large problems (inner iterations are disabled automatically when edges are present).
opts.linear_solver_type = pt.sfm.LinearSolverType.SPARSE_SCHUR
opts.sparse_linear_algebra_library_type = pt.sfm.SparseLinearAlgebraLibraryType.EIGEN_SPARSE
summary = pt.sfm.BundleAdjustReconstructionWithRelativePoseEdges(opts, edges, reconstruction)
When to use: absolute anchor priors alone only pull the anchor frames; relative edges keep the local shape of the run (its own odometry) so corrections propagate along the chain instead of being absorbed by shared 3D points. Typical pairing: strong priors on anchor views + soft or no dense interpolated priors + relative edges between consecutive frames.
Scale-invariant odometry (run-to-segment alignment)¶
When the run reconstruction may still have wrong metric scale after a coarse warp into the segment frame, set scale_invariant_translation = True and use direction weights only (translation_magnitude_sqrt_weight = 0). Rotation is still penalized via the SE3 log rotation part; translation is matched by direction (cross product of unit vectors), not by full \(\mathfrak{se}(3)\) translation components.
edge = pt.sfm.RelativePoseConstraint()
edge.view_id_i = vid_i
edge.view_id_j = vid_j
edge.rotation_sqrt_weight = 100.0
edge.scale_invariant_translation = True
edge.translation_direction_sqrt_weight = 30.0
edge.translation_magnitude_sqrt_weight = 0.0
See Cross-run alignment → scale-invariant edges and pytests/sfm/relative_pose_constraint_test.py.
C++: relative_pose_error.h, scaled_relative_pose_error.h, BundleAdjustReconstructionWithRelativePoseEdges in bundle_adjustment.h.
Control-point BA¶
BundleAdjustReconstructionWithConstantTracks optimizes all estimated cameras and variable tracks, but skips AddTrack() for the given track IDs so those 3D points stay fixed. Reprojection residuals for observations of constant tracks still pin the cameras. This is the usual pattern for aligning one reconstruction to another’s map without moving the reference points.
constant_track_ids = [seg_track_id, ...] # segment / map points
summary = pt.sfm.BundleAdjustReconstructionWithConstantTracks(
opts, constant_track_ids, run_reconstruction
)
Only estimated views and tracks are added; unestimated tracks (e.g. after a failed retriangulation) are skipped automatically.
BundleAdjustmentSummary¶
success— optimization ran without Ceres failure (does not guarantee geometric quality).initial_cost/final_costsetup_time_in_seconds/solve_time_in_seconds
Always inspect reprojection errors and inlier counts in the reconstruction after BA.
Related helpers¶
SelectGoodTracksForBundleAdjustment— subsample long tracks / balance coverage before a large BA.SetOutlierTracksToUnestimated— drop poorly supported points after BA or filtering.
See also¶
- SfM —
Reconstruction,View,Track, pipelines - Triangulation — initial structure before refinement
- Transformations — align or apply a global Sim3 before/after BA
- Cameras — intrinsics models and projection