Debian Codegraph @

src/pycolmap/estimators/bundle_adjustment.cc

raw
1 #include "colmap/estimators/bundle_adjustment.h"
2
3 #include "colmap/estimators/bundle_adjustment_caspar.h"
4 #include "colmap/estimators/bundle_adjustment_ceres.h"
5
6 #include "pycolmap/helpers.h"
7 #include "pycolmap/pybind11_extension.h"
8 #include "pycolmap/utils.h"
9
10 #include <pybind11/eigen.h>
11 #include <pybind11/pybind11.h>
12 #include <pybind11/stl.h>
13
14 using namespace colmap;
15 using namespace pybind11::literals;
16 namespace py = pybind11;
17
18 namespace {
19
20 class PyBundleAdjuster : public BundleAdjuster,
21 py::trampoline_self_life_support {
22 public:
23 PyBundleAdjuster(const BundleAdjustmentOptions& options,
24 const BundleAdjustmentConfig& config)
25 : BundleAdjuster(options, config) {}
26
27 std::shared_ptr<BundleAdjustmentSummary> Solve() override {
28 PYBIND11_OVERRIDE_PURE(
29 std::shared_ptr<BundleAdjustmentSummary>, BundleAdjuster, Solve);
30 }
31 };
32
33 class PyCeresBundleAdjuster : public CeresBundleAdjuster,
34 py::trampoline_self_life_support {
35 public:
36 PyCeresBundleAdjuster(const BundleAdjustmentOptions& options,
37 const BundleAdjustmentConfig& config)
38 : CeresBundleAdjuster(options, config) {}
39
40 std::shared_ptr<BundleAdjustmentSummary> Solve() override {
41 PYBIND11_OVERRIDE_PURE(
42 std::shared_ptr<BundleAdjustmentSummary>, CeresBundleAdjuster, Solve);
43 }
44
45 std::shared_ptr<ceres::Problem>& Problem() override {
46 // Cannot use PYBIND11_OVERRIDE_PURE for reference returns as it creates
47 // a temporary. Instead, manually call override and store in member.
48 py::gil_scoped_acquire gil;
49 py::function override = py::get_override(
50 static_cast<const CeresBundleAdjuster*>(this), "problem");
51 if (override) {
52 auto obj = override();
53 problem_ = obj.cast<std::shared_ptr<ceres::Problem>>();
54 }
55 return problem_;
56 }
57
58 private:
59 std::shared_ptr<ceres::Problem> problem_;
60 };
61
62 } // namespace
63
64 void BindBundleAdjuster(py::module& m) {
65 IsPyceresAvailable(); // Try to import pyceres to populate the docstrings.
66
67 auto PyBundleAdjustmentTerminationType =
68 py::enum_<BundleAdjustmentTerminationType>(
69 m, "BundleAdjustmentTerminationType")
70 .value("CONVERGENCE", BundleAdjustmentTerminationType::CONVERGENCE)
71 .value("NO_CONVERGENCE",
72 BundleAdjustmentTerminationType::NO_CONVERGENCE)
73 .value("FAILURE", BundleAdjustmentTerminationType::FAILURE)
74 .value("USER_SUCCESS", BundleAdjustmentTerminationType::USER_SUCCESS)
75 .value("USER_FAILURE", BundleAdjustmentTerminationType::USER_FAILURE);
76 AddStringToEnumConstructor(PyBundleAdjustmentTerminationType);
77
78 using BASummary = BundleAdjustmentSummary;
79 auto PyBundleAdjustmentSummary =
80 py::classh<BASummary>(m, "BundleAdjustmentSummary")
81 .def(py::init<>())
82 .def_readwrite("termination_type", &BASummary::termination_type)
83 .def_readwrite("num_residuals", &BASummary::num_residuals)
84 .def("is_solution_usable", &BASummary::IsSolutionUsable)
85 .def("brief_report", &BASummary::BriefReport);
86 MakeDataclass(PyBundleAdjustmentSummary);
87
88 using CeresBASummary = CeresBundleAdjustmentSummary;
89 auto PyCeresBundleAdjustmentSummary =
90 py::classh<CeresBASummary, BASummary>(m, "CeresBundleAdjustmentSummary")
91 .def(py::init<>())
92 .def_readwrite("ceres_summary",
93 &CeresBASummary::ceres_summary,
94 "Full Ceres solver summary.");
95 MakeDataclass(PyCeresBundleAdjustmentSummary);
96
97 #ifdef CASPAR_ENABLED
98 using CasparBASummary = CasparBundleAdjustmentSummary;
99 auto PyCasparBundleAdjustmentSummary =
100 py::classh<CasparBASummary, BASummary>(m, "CasparBundleAdjustmentSummary")
101 .def(py::init<>());
102 MakeDataclass(PyCasparBundleAdjustmentSummary);
103 #endif
104
105 auto PyBundleAdjustmentGauge =
106 py::enum_<BundleAdjustmentGauge>(m, "BundleAdjustmentGauge")
107 .value("UNSPECIFIED", BundleAdjustmentGauge::UNSPECIFIED)
108 .value("TWO_CAMS_FROM_WORLD",
109 BundleAdjustmentGauge::TWO_CAMS_FROM_WORLD)
110 .value("THREE_POINTS", BundleAdjustmentGauge::THREE_POINTS);
111 AddStringToEnumConstructor(PyBundleAdjustmentGauge);
112
113 auto PyBundleAdjustmentBackend =
114 py::enum_<BundleAdjustmentBackend>(m, "BundleAdjustmentBackend")
115 .value("CERES", BundleAdjustmentBackend::CERES)
116 .value("CASPAR", BundleAdjustmentBackend::CASPAR);
117 AddStringToEnumConstructor(PyBundleAdjustmentBackend);
118
119 using BACfg = BundleAdjustmentConfig;
120 py::classh<BACfg> PyBundleAdjustmentConfig(m, "BundleAdjustmentConfig");
121 PyBundleAdjustmentConfig.def(py::init<>())
122 .def("fix_gauge", &BACfg::FixGauge)
123 .def_property_readonly("fixed_gauge", &BACfg::FixedGauge)
124 .def("num_points", &BACfg::NumPoints)
125 .def("num_constant_cam_intrinsics", &BACfg::NumConstantCamIntrinsics)
126 .def("num_constant_sensor_from_rig_poses",
127 &BACfg::NumConstantSensorFromRigPoses)
128 .def("num_constant_rig_from_world_poses",
129 &BACfg::NumConstantRigFromWorldPoses)
130 .def("num_variable_points", &BACfg::NumVariablePoints)
131 .def("num_constant_points", &BACfg::NumConstantPoints)
132 .def("num_residuals", &BACfg::NumResiduals, "reconstruction"_a)
133 .def("add_image", &BACfg::AddImage, "image_id"_a)
134 .def("has_image", &BACfg::HasImage, "image_id"_a)
135 .def("remove_image", &BACfg::RemoveImage, "image_id"_a)
136 .def("set_constant_cam_intrinsics",
137 &BACfg::SetConstantCamIntrinsics,
138 "camera_id"_a)
139 .def("set_variable_cam_intrinsics",
140 &BACfg::SetVariableCamIntrinsics,
141 "camera_id"_a)
142 .def("has_constant_cam_intrinsics",
143 &BACfg::HasConstantCamIntrinsics,
144 "camera_id"_a)
145 .def("set_constant_sensor_from_rig_pose",
146 &BACfg::SetConstantSensorFromRigPose,
147 "sensor_id"_a)
148 .def("set_variable_sensor_from_rig_pose",
149 &BACfg::SetVariableSensorFromRigPose,
150 "sensor_id"_a)
151 .def("has_constant_sensor_from_rig_pose",
152 &BACfg::HasConstantSensorFromRigPose,
153 "sensor_id"_a)
154 .def("set_constant_rig_from_world_pose",
155 &BACfg::SetConstantRigFromWorldPose,
156 "frame_id"_a)
157 .def("set_variable_rig_from_world_pose",
158 &BACfg::SetVariableRigFromWorldPose,
159 "frame_id"_a)
160 .def("has_constant_rig_from_world_pose",
161 &BACfg::HasConstantRigFromWorldPose,
162 "frame_id"_a)
163 .def("add_variable_point", &BACfg::AddVariablePoint, "point3D_id"_a)
164 .def("add_constant_point", &BACfg::AddConstantPoint, "point3D_id"_a)
165 .def("has_point", &BACfg::HasPoint, "point3D_id"_a)
166 .def("has_variable_point", &BACfg::HasVariablePoint, "point3D_id"_a)
167 .def("has_constant_point", &BACfg::HasConstantPoint, "point3D_id"_a)
168 .def("remove_variable_point", &BACfg::RemoveVariablePoint, "point3D_id"_a)
169 .def("remove_constant_point", &BACfg::RemoveConstantPoint, "point3D_id"_a)
170 .def_property_readonly("constant_cam_intrinsics",
171 &BACfg::ConstantCamIntrinsics)
172 .def_property_readonly("images", &BACfg::Images)
173 .def_property_readonly("variable_points", &BACfg::VariablePoints)
174 .def_property_readonly("constant_points", &BACfg::ConstantPoints)
175 .def_property_readonly("constant_sensor_from_rig_poses",
176 &BACfg::ConstantSensorFromRigPoses)
177 .def_property_readonly("constant_rig_from_world_poses",
178 &BACfg::ConstantRigFromWorldPoses);
179 MakeDataclass(PyBundleAdjustmentConfig);
180
181 // Ceres-specific bundle adjustment options
182 using CeresBAOpts = CeresBundleAdjustmentOptions;
183 auto PyCeresLossFunctionType =
184 py::enum_<CeresBAOpts::LossFunctionType>(m, "LossFunctionType")
185 .value("TRIVIAL", CeresBAOpts::LossFunctionType::TRIVIAL)
186 .value("SOFT_L1", CeresBAOpts::LossFunctionType::SOFT_L1)
187 .value("CAUCHY", CeresBAOpts::LossFunctionType::CAUCHY)
188 .value("HUBER", CeresBAOpts::LossFunctionType::HUBER);
189 AddStringToEnumConstructor(PyCeresLossFunctionType);
190
191 auto PyCeresBundleAdjustmentOptions =
192 py::classh<CeresBAOpts>(m, "CeresBundleAdjustmentOptions")
193 .def(py::init<>())
194 .def("create_loss_function", &CeresBAOpts::CreateLossFunction)
195 .def("create_solver_options",
196 &CeresBAOpts::CreateSolverOptions,
197 "config"_a,
198 "problem"_a)
199 .def_readwrite("loss_function_type",
200 &CeresBAOpts::loss_function_type,
201 "Loss function types: Trivial (non-robust) and Cauchy "
202 "(robust) loss.")
203 .def_readwrite("loss_function_scale",
204 &CeresBAOpts::loss_function_scale,
205 "Scaling factor determines residual at which "
206 "robustification takes place.")
207 .def_readwrite("use_gpu",
208 &CeresBAOpts::use_gpu,
209 "Whether to use Ceres' CUDA linear algebra library, "
210 "if available.")
211 .def_readwrite("gpu_index",
212 &CeresBAOpts::gpu_index,
213 "Which GPU to use for solving the problem.")
214 .def_readwrite("solver_options",
215 &CeresBAOpts::solver_options,
216 "Options for the Ceres solver. Using this member "
217 "requires having PyCeres installed.")
218 .def_readwrite("min_num_images_gpu_solver",
219 &CeresBAOpts::min_num_images_gpu_solver,
220 "Minimum number of images to use the GPU solver.")
221 .def_readwrite(
222 "min_num_residuals_for_cpu_multi_threading",
223 &CeresBAOpts::min_num_residuals_for_cpu_multi_threading,
224 "Minimum number of residuals to enable multi-threading. Note "
225 "that single-threaded is typically better for small bundle "
226 "adjustment problems due to the overhead of threading.")
227 .def_readwrite("max_num_images_direct_dense_cpu_solver",
228 &CeresBAOpts::max_num_images_direct_dense_cpu_solver,
229 "Threshold to switch between direct, sparse, and "
230 "iterative solvers.")
231 .def_readwrite("max_num_images_direct_sparse_cpu_solver",
232 &CeresBAOpts::max_num_images_direct_sparse_cpu_solver,
233 "Threshold to switch between direct, sparse, and "
234 "iterative solvers.")
235 .def_readwrite("max_num_images_direct_dense_gpu_solver",
236 &CeresBAOpts::max_num_images_direct_dense_gpu_solver,
237 "Threshold to switch between direct, sparse, and "
238 "iterative solvers.")
239 .def_readwrite("max_num_images_direct_sparse_gpu_solver",
240 &CeresBAOpts::max_num_images_direct_sparse_gpu_solver,
241 "Threshold to switch between direct, sparse, and "
242 "iterative solvers.")
243 .def_readwrite(
244 "auto_select_solver_type",
245 &CeresBAOpts::auto_select_solver_type,
246 "Whether to automatically select solver type based on "
247 "problem size. When False, uses the linear_solver_type "
248 "and preconditioner_type from solver_options directly.")
249 .def("check", &CeresBAOpts::Check);
250 MakeDataclass(PyCeresBundleAdjustmentOptions);
251
252 // Caspar-specific bundle adjustment options
253 using CasparBAOpts = CasparBundleAdjustmentOptions;
254 auto PyCasparBundleAdjustmentOptions =
255 py::classh<CasparBAOpts>(m, "CasparBundleAdjustmentOptions")
256 .def(py::init<>())
257 .def_readwrite("solver_iter_max",
258 &CasparBAOpts::solver_iter_max,
259 "Maximum number of Caspar solver iterations.")
260 .def_readwrite("pcg_iter_max",
261 &CasparBAOpts::pcg_iter_max,
262 "Maximum number of PCG iterations per solver step.")
263 .def_readwrite("diag_init",
264 &CasparBAOpts::diag_init,
265 "Initial diagonal damping value.")
266 .def_readwrite("diag_min",
267 &CasparBAOpts::diag_min,
268 "Minimum diagonal damping value.")
269 .def_readwrite("diag_scaling_up",
270 &CasparBAOpts::diag_scaling_up,
271 "Diagonal damping increase factor.")
272 .def_readwrite("diag_scaling_down",
273 &CasparBAOpts::diag_scaling_down,
274 "Diagonal damping decrease factor.")
275 .def_readwrite("diag_exit_value",
276 &CasparBAOpts::diag_exit_value,
277 "Diagonal damping value that triggers termination.")
278 .def_readwrite("score_exit_value",
279 &CasparBAOpts::score_exit_value,
280 "Score threshold that triggers termination.")
281 .def_readwrite("pcg_rel_error_exit",
282 &CasparBAOpts::pcg_rel_error_exit,
283 "Relative PCG error threshold that triggers exit.")
284 .def_readwrite("pcg_rel_score_exit",
285 &CasparBAOpts::pcg_rel_score_exit,
286 "Relative PCG score threshold that triggers exit.")
287 .def_readwrite("pcg_rel_decrease_min",
288 &CasparBAOpts::pcg_rel_decrease_min,
289 "Minimum relative PCG decrease.")
290 .def_readwrite("solver_rel_decrease_min",
291 &CasparBAOpts::solver_rel_decrease_min,
292 "Minimum relative solver decrease.")
293 .def_readwrite("gpu_index",
294 &CasparBAOpts::gpu_index,
295 "Which GPU to use for solving the problem.");
296 MakeDataclass(PyCasparBundleAdjustmentOptions);
297
298 // Solver-agnostic bundle adjustment options
299 using BAOpts = BundleAdjustmentOptions;
300 auto PyBundleAdjustmentOptions =
301 py::classh<BAOpts>(m, "BundleAdjustmentOptions")
302 .def(py::init<>())
303 .def_readwrite("refine_focal_length",
304 &BAOpts::refine_focal_length,
305 "Whether to refine the focal length parameter group.")
306 .def_readwrite(
307 "refine_principal_point",
308 &BAOpts::refine_principal_point,
309 "Whether to refine the principal point parameter group.")
310 .def_readwrite("refine_extra_params",
311 &BAOpts::refine_extra_params,
312 "Whether to refine the extra parameter group.")
313 .def_readwrite("refine_rig_from_world",
314 &BAOpts::refine_rig_from_world,
315 "Whether to refine the frame from world extrinsic "
316 "parameter group.")
317 .def_readwrite("refine_sensor_from_rig",
318 &BAOpts::refine_sensor_from_rig,
319 "Whether to refine the sensor from rig extrinsic "
320 "parameter group.")
321 .def_readwrite("constant_rig_from_world_rotation",
322 &BAOpts::constant_rig_from_world_rotation,
323 "Whether to keep the rotation component of "
324 "rig_from_world constant. Only takes effect when "
325 "refine_rig_from_world is true.")
326 .def_readwrite("refine_points3D",
327 &BAOpts::refine_points3D,
328 "Whether to refine 3D points.")
329 .def_readwrite("min_track_length",
330 &BAOpts::min_track_length,
331 "Minimum track length for a 3D point.")
332 .def_readwrite("print_summary",
333 &BAOpts::print_summary,
334 "Whether to print a final summary.")
335 .def_readwrite("backend",
336 &BAOpts::backend,
337 "Solver backend to use for bundle adjustment.")
338 .def_readwrite("ceres",
339 &BAOpts::ceres,
340 "Ceres-specific bundle adjustment options.")
341 .def_readwrite("caspar",
342 &BAOpts::caspar,
343 "Caspar-specific bundle adjustment options.")
344 .def("check", &BAOpts::Check);
345 MakeDataclass(PyBundleAdjustmentOptions);
346
347 // Ceres-specific pose prior bundle adjustment options
348 using CeresPosePriorBAOpts = CeresPosePriorBundleAdjustmentOptions;
349 auto PyCeresPosePriorBundleAdjustmentOptions =
350 py::classh<CeresPosePriorBAOpts>(m,
351 "CeresPosePriorBundleAdjustmentOptions")
352 .def(py::init<>())
353 .def_readwrite(
354 "prior_position_loss_function_type",
355 &CeresPosePriorBAOpts::prior_position_loss_function_type,
356 "Loss function for prior position loss.")
357 .def_readwrite("prior_position_loss_scale",
358 &CeresPosePriorBAOpts::prior_position_loss_scale,
359 "Threshold on the residual for the robust loss (chi2 "
360 "for 3DOF at 95% = 7.815).")
361 .def("check", &CeresPosePriorBAOpts::Check);
362 MakeDataclass(PyCeresPosePriorBundleAdjustmentOptions);
363
364 // Solver-agnostic pose prior bundle adjustment options
365 using PosePriorBAOpts = PosePriorBundleAdjustmentOptions;
366 auto PyPosePriorBundleAdjustmentOptions =
367 py::classh<PosePriorBAOpts>(m, "PosePriorBundleAdjustmentOptions")
368 .def(py::init<>())
369 .def_readwrite(
370 "prior_position_fallback_stddev",
371 &PosePriorBAOpts::prior_position_fallback_stddev,
372 "Fallback if no prior position covariance is provided.")
373 .def_readwrite("alignment_ransac",
374 &PosePriorBAOpts::alignment_ransac_options,
375 "RANSAC options for Sim3 alignment.")
376 .def_readwrite("ceres",
377 &PosePriorBAOpts::ceres,
378 "Ceres-specific pose prior bundle adjustment options.")
379 .def("check", &PosePriorBAOpts::Check);
380 MakeDataclass(PyPosePriorBundleAdjustmentOptions);
381
382 py::classh<BundleAdjuster, PyBundleAdjuster>(m, "BundleAdjuster")
383 .def(py::init([](const BundleAdjustmentOptions& options,
384 const BundleAdjustmentConfig& config) {
385 return new PyBundleAdjuster(options, config);
386 }),
387 "options"_a,
388 "config"_a)
389 .def("solve", &BundleAdjuster::Solve)
390 .def_property_readonly("options", &BundleAdjuster::Options)
391 .def_property_readonly("config", &BundleAdjuster::Config);
392
393 py::classh<CeresBundleAdjuster, BundleAdjuster, PyCeresBundleAdjuster>(
394 m, "CeresBundleAdjuster")
395 .def(py::init([](const BundleAdjustmentOptions& options,
396 const BundleAdjustmentConfig& config) {
397 return new PyCeresBundleAdjuster(options, config);
398 }),
399 "options"_a,
400 "config"_a)
401 .def_property_readonly("problem", &CeresBundleAdjuster::Problem);
402
403 m.def("create_default_bundle_adjuster",
404 CreateDefaultBundleAdjuster,
405 "options"_a,
406 "config"_a,
407 "reconstruction"_a);
408
409 m.def("create_default_ceres_bundle_adjuster",
410 CreateDefaultCeresBundleAdjuster,
411 "options"_a,
412 "config"_a,
413 "reconstruction"_a);
414
415 m.def("create_pose_prior_bundle_adjuster",
416 CreatePosePriorBundleAdjuster,
417 "options"_a,
418 "prior_options"_a,
419 "config"_a,
420 "pose_priors"_a,
421 "reconstruction"_a);
422
423 m.def("create_pose_prior_ceres_bundle_adjuster",
424 CreatePosePriorCeresBundleAdjuster,
425 "options"_a,
426 "prior_options"_a,
427 "config"_a,
428 "pose_priors"_a,
429 "reconstruction"_a);
430 }