blob: 70a96409e4afe92b32dbe6f402dc74e12504c0ad [file] [log] [blame]
Keir Mierle8ebb0732012-04-30 23:09:08 -07001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
3// http://code.google.com/p/ceres-solver/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of Google Inc. nor the names of its contributors may be
14// used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: sameeragarwal@google.com (Sameer Agarwal)
30//
31// An example of solving a dynamically sized problem with various
32// solvers and loss functions.
33//
34// For a simpler bare bones example of doing bundle adjustment with
35// Ceres, please see simple_bundle_adjuster.cc.
36//
37// NOTE: This example will not compile without gflags and SuiteSparse.
38//
39// The problem being solved here is known as a Bundle Adjustment
40// problem in computer vision. Given a set of 3d points X_1, ..., X_n,
41// a set of cameras P_1, ..., P_m. If the point X_i is visible in
42// image j, then there is a 2D observation u_ij that is the expected
43// projection of X_i using P_j. The aim of this optimization is to
44// find values of X_i and P_j such that the reprojection error
45//
46// E(X,P) = sum_ij |u_ij - P_j X_i|^2
47//
48// is minimized.
49//
50// The problem used here comes from a collection of bundle adjustment
51// problems published at University of Washington.
52// http://grail.cs.washington.edu/projects/bal
53
54#include <algorithm>
55#include <cmath>
56#include <cstdio>
Sameer Agarwal1b7f3b52012-08-09 21:46:19 -070057#include <cstdlib>
Keir Mierle8ebb0732012-04-30 23:09:08 -070058#include <string>
59#include <vector>
60
Keir Mierle8ebb0732012-04-30 23:09:08 -070061#include "bal_problem.h"
Keir Mierle8ebb0732012-04-30 23:09:08 -070062#include "ceres/ceres.h"
Sameer Agarwal4b040432012-08-13 14:38:41 -070063#include "gflags/gflags.h"
64#include "glog/logging.h"
65#include "snavely_reprojection_error.h"
Keir Mierle8ebb0732012-04-30 23:09:08 -070066
67DEFINE_string(input, "", "Input File name");
Sameer Agarwalcbae8562012-09-02 13:50:43 -070068DEFINE_string(trust_region_strategy, "levenberg_marquardt",
Sameer Agarwal65625f72012-09-17 12:06:57 -070069 "Options are: levenberg_marquardt, dogleg.");
Sameer Agarwal9123e2f2012-09-18 21:49:06 -070070DEFINE_string(dogleg, "traditional_dogleg", "Options are: traditional_dogleg,"
71 "subspace_dogleg.");
72
73DEFINE_bool(inner_iterations, false, "Use inner iterations to non-linearly "
74 "refine each successful trust region step.");
75
Sameer Agarwalba8d9672012-10-02 00:48:57 -070076DEFINE_string(blocks_for_inner_iterations, "automatic", "Options are: "
77 "automatic, cameras, points, cameras,points, points,cameras");
Sameer Agarwal9123e2f2012-09-18 21:49:06 -070078
Sameer Agarwalcbae8562012-09-02 13:50:43 -070079DEFINE_string(linear_solver, "sparse_schur", "Options are: "
80 "sparse_schur, dense_schur, iterative_schur, sparse_normal_cholesky, "
Sameer Agarwal65625f72012-09-17 12:06:57 -070081 "dense_qr, dense_normal_cholesky and cgnr.");
Sameer Agarwalcbae8562012-09-02 13:50:43 -070082DEFINE_string(preconditioner, "jacobi", "Options are: "
83 "identity, jacobi, schur_jacobi, cluster_jacobi, "
Sameer Agarwal65625f72012-09-17 12:06:57 -070084 "cluster_tridiagonal.");
Sameer Agarwalf06b9fa2013-10-27 21:38:13 -070085DEFINE_string(visibility_clustering, "canonical_views",
86 "single_linkage, canonical_views");
87
Sameer Agarwalcbae8562012-09-02 13:50:43 -070088DEFINE_string(sparse_linear_algebra_library, "suite_sparse",
Sameer Agarwal65625f72012-09-17 12:06:57 -070089 "Options are: suite_sparse and cx_sparse.");
Sameer Agarwal367b65e2013-08-09 10:35:37 -070090DEFINE_string(dense_linear_algebra_library, "eigen",
91 "Options are: eigen and lapack.");
Sameer Agarwal65625f72012-09-17 12:06:57 -070092DEFINE_string(ordering, "automatic", "Options are: automatic, user.");
Sameer Agarwalcbae8562012-09-02 13:50:43 -070093
Sameer Agarwal5476df52012-08-09 21:46:19 -070094DEFINE_bool(use_quaternions, false, "If true, uses quaternions to represent "
Sameer Agarwal65625f72012-09-17 12:06:57 -070095 "rotations. If false, angle axis is used.");
Sameer Agarwal5476df52012-08-09 21:46:19 -070096DEFINE_bool(use_local_parameterization, false, "For quaternions, use a local "
97 "parameterization.");
Sameer Agarwal65625f72012-09-17 12:06:57 -070098DEFINE_bool(robustify, false, "Use a robust loss function.");
Sameer Agarwal5476df52012-08-09 21:46:19 -070099
Sameer Agarwal5476df52012-08-09 21:46:19 -0700100DEFINE_double(eta, 1e-2, "Default value for eta. Eta determines the "
101 "accuracy of each linear solve of the truncated newton step. "
Sameer Agarwal65625f72012-09-17 12:06:57 -0700102 "Changing this parameter can affect solve performance.");
Sameer Agarwal5476df52012-08-09 21:46:19 -0700103
Sameer Agarwal65625f72012-09-17 12:06:57 -0700104DEFINE_int32(num_threads, 1, "Number of threads.");
105DEFINE_int32(num_iterations, 5, "Number of iterations.");
Sameer Agarwalfa015192012-06-11 14:21:42 -0700106DEFINE_double(max_solver_time, 1e32, "Maximum solve time in seconds.");
Sameer Agarwala8f87d72012-08-08 10:38:31 -0700107DEFINE_bool(nonmonotonic_steps, false, "Trust region algorithm can use"
Sameer Agarwal65625f72012-09-17 12:06:57 -0700108 " nonmonotic steps.");
Keir Mierle8ebb0732012-04-30 23:09:08 -0700109
Sameer Agarwal5476df52012-08-09 21:46:19 -0700110DEFINE_double(rotation_sigma, 0.0, "Standard deviation of camera rotation "
111 "perturbation.");
112DEFINE_double(translation_sigma, 0.0, "Standard deviation of the camera "
113 "translation perturbation.");
114DEFINE_double(point_sigma, 0.0, "Standard deviation of the point "
Sameer Agarwal65625f72012-09-17 12:06:57 -0700115 "perturbation.");
Sameer Agarwal5476df52012-08-09 21:46:19 -0700116DEFINE_int32(random_seed, 38401, "Random seed used to set the state "
117 "of the pseudo random number generator used to generate "
118 "the pertubations.");
Sameer Agarwal1b7f3b52012-08-09 21:46:19 -0700119DEFINE_string(solver_log, "", "File to record the solver execution to.");
Sameer Agarwal1c70ae92013-06-30 12:50:43 -0700120DEFINE_bool(line_search, false, "Use a line search instead of trust region "
121 "algorithm.");
Sameer Agarwal5476df52012-08-09 21:46:19 -0700122
Keir Mierle8ebb0732012-04-30 23:09:08 -0700123namespace ceres {
124namespace examples {
125
126void SetLinearSolver(Solver::Options* options) {
Sameer Agarwalcbae8562012-09-02 13:50:43 -0700127 CHECK(StringToLinearSolverType(FLAGS_linear_solver,
128 &options->linear_solver_type));
129 CHECK(StringToPreconditionerType(FLAGS_preconditioner,
130 &options->preconditioner_type));
Sameer Agarwalf06b9fa2013-10-27 21:38:13 -0700131 CHECK(StringToVisibilityClusteringType(FLAGS_visibility_clustering,
132 &options->visibility_clustering_type));
Sameer Agarwalcbae8562012-09-02 13:50:43 -0700133 CHECK(StringToSparseLinearAlgebraLibraryType(
134 FLAGS_sparse_linear_algebra_library,
Sameer Agarwal367b65e2013-08-09 10:35:37 -0700135 &options->sparse_linear_algebra_library_type));
136 CHECK(StringToDenseLinearAlgebraLibraryType(
137 FLAGS_dense_linear_algebra_library,
138 &options->dense_linear_algebra_library_type));
Keir Mierle8ebb0732012-04-30 23:09:08 -0700139 options->num_linear_solver_threads = FLAGS_num_threads;
140}
141
142void SetOrdering(BALProblem* bal_problem, Solver::Options* options) {
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700143 const int num_points = bal_problem->num_points();
144 const int point_block_size = bal_problem->point_block_size();
145 double* points = bal_problem->mutable_points();
146
147 const int num_cameras = bal_problem->num_cameras();
148 const int camera_block_size = bal_problem->camera_block_size();
149 double* cameras = bal_problem->mutable_cameras();
150
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700151 if (options->use_inner_iterations) {
152 if (FLAGS_blocks_for_inner_iterations == "cameras") {
153 LOG(INFO) << "Camera blocks for inner iterations";
Sameer Agarwalbb05be32014-04-13 14:22:19 -0700154 options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700155 for (int i = 0; i < num_cameras; ++i) {
Sameer Agarwalba8d9672012-10-02 00:48:57 -0700156 options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 0);
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700157 }
158 } else if (FLAGS_blocks_for_inner_iterations == "points") {
159 LOG(INFO) << "Point blocks for inner iterations";
Sameer Agarwalbb05be32014-04-13 14:22:19 -0700160 options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700161 for (int i = 0; i < num_points; ++i) {
Sameer Agarwalba8d9672012-10-02 00:48:57 -0700162 options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 0);
163 }
164 } else if (FLAGS_blocks_for_inner_iterations == "cameras,points") {
165 LOG(INFO) << "Camera followed by point blocks for inner iterations";
Sameer Agarwalbb05be32014-04-13 14:22:19 -0700166 options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
Sameer Agarwalba8d9672012-10-02 00:48:57 -0700167 for (int i = 0; i < num_cameras; ++i) {
168 options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 0);
169 }
170 for (int i = 0; i < num_points; ++i) {
171 options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 1);
172 }
173 } else if (FLAGS_blocks_for_inner_iterations == "points,cameras") {
174 LOG(INFO) << "Point followed by camera blocks for inner iterations";
Sameer Agarwalbb05be32014-04-13 14:22:19 -0700175 options->inner_iteration_ordering.reset(new ParameterBlockOrdering);
Sameer Agarwalba8d9672012-10-02 00:48:57 -0700176 for (int i = 0; i < num_cameras; ++i) {
177 options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 1);
178 }
179 for (int i = 0; i < num_points; ++i) {
180 options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 0);
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700181 }
182 } else if (FLAGS_blocks_for_inner_iterations == "automatic") {
183 LOG(INFO) << "Choosing automatic blocks for inner iterations";
184 } else {
185 LOG(FATAL) << "Unknown block type for inner iterations: "
186 << FLAGS_blocks_for_inner_iterations;
187 }
188 }
189
Keir Mierle8ebb0732012-04-30 23:09:08 -0700190 // Bundle adjustment problems have a sparsity structure that makes
191 // them amenable to more specialized and much more efficient
192 // solution strategies. The SPARSE_SCHUR, DENSE_SCHUR and
193 // ITERATIVE_SCHUR solvers make use of this specialized
Sameer Agarwal65625f72012-09-17 12:06:57 -0700194 // structure.
Keir Mierle8ebb0732012-04-30 23:09:08 -0700195 //
196 // This can either be done by specifying Options::ordering_type =
197 // ceres::SCHUR, in which case Ceres will automatically determine
198 // the right ParameterBlock ordering, or by manually specifying a
199 // suitable ordering vector and defining
200 // Options::num_eliminate_blocks.
Sameer Agarwal65625f72012-09-17 12:06:57 -0700201 if (FLAGS_ordering == "automatic") {
Keir Mierle8ebb0732012-04-30 23:09:08 -0700202 return;
203 }
204
Sameer Agarwal2c94eed2012-10-01 16:34:37 -0700205 ceres::ParameterBlockOrdering* ordering =
206 new ceres::ParameterBlockOrdering;
Sameer Agarwal91c9bfe2012-09-10 17:41:38 -0700207
Keir Mierle8ebb0732012-04-30 23:09:08 -0700208 // The points come before the cameras.
209 for (int i = 0; i < num_points; ++i) {
Sameer Agarwal2c94eed2012-10-01 16:34:37 -0700210 ordering->AddElementToGroup(points + point_block_size * i, 0);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700211 }
212
213 for (int i = 0; i < num_cameras; ++i) {
214 // When using axis-angle, there is a single parameter block for
215 // the entire camera.
Sameer Agarwal2c94eed2012-10-01 16:34:37 -0700216 ordering->AddElementToGroup(cameras + camera_block_size * i, 1);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700217 // If quaternions are used, there are two blocks, so add the
218 // second block to the ordering.
219 if (FLAGS_use_quaternions) {
Sameer Agarwal2c94eed2012-10-01 16:34:37 -0700220 ordering->AddElementToGroup(cameras + camera_block_size * i + 4, 1);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700221 }
222 }
223
Sameer Agarwalbb05be32014-04-13 14:22:19 -0700224 options->linear_solver_ordering.reset(ordering);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700225}
226
227void SetMinimizerOptions(Solver::Options* options) {
228 options->max_num_iterations = FLAGS_num_iterations;
229 options->minimizer_progress_to_stdout = true;
230 options->num_threads = FLAGS_num_threads;
Keir Mierlef7898fb2012-05-05 20:55:08 -0700231 options->eta = FLAGS_eta;
Sameer Agarwalfa015192012-06-11 14:21:42 -0700232 options->max_solver_time_in_seconds = FLAGS_max_solver_time;
Sameer Agarwala8f87d72012-08-08 10:38:31 -0700233 options->use_nonmonotonic_steps = FLAGS_nonmonotonic_steps;
Sameer Agarwal1c70ae92013-06-30 12:50:43 -0700234 if (FLAGS_line_search) {
235 options->minimizer_type = ceres::LINE_SEARCH;
236 }
237
Sameer Agarwalcbae8562012-09-02 13:50:43 -0700238 CHECK(StringToTrustRegionStrategyType(FLAGS_trust_region_strategy,
239 &options->trust_region_strategy_type));
240 CHECK(StringToDoglegType(FLAGS_dogleg, &options->dogleg_type));
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700241 options->use_inner_iterations = FLAGS_inner_iterations;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700242}
243
244void SetSolverOptionsFromFlags(BALProblem* bal_problem,
245 Solver::Options* options) {
Sameer Agarwalaa9a83c2012-05-29 17:40:17 -0700246 SetMinimizerOptions(options);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700247 SetLinearSolver(options);
248 SetOrdering(bal_problem, options);
Keir Mierle8ebb0732012-04-30 23:09:08 -0700249}
250
251void BuildProblem(BALProblem* bal_problem, Problem* problem) {
252 const int point_block_size = bal_problem->point_block_size();
253 const int camera_block_size = bal_problem->camera_block_size();
254 double* points = bal_problem->mutable_points();
255 double* cameras = bal_problem->mutable_cameras();
256
257 // Observations is 2*num_observations long array observations =
258 // [u_1, u_2, ... , u_n], where each u_i is two dimensional, the x
259 // and y positions of the observation.
260 const double* observations = bal_problem->observations();
261
262 for (int i = 0; i < bal_problem->num_observations(); ++i) {
263 CostFunction* cost_function;
264 // Each Residual block takes a point and a camera as input and
265 // outputs a 2 dimensional residual.
266 if (FLAGS_use_quaternions) {
267 cost_function = new AutoDiffCostFunction<
Sameer Agarwal5476df52012-08-09 21:46:19 -0700268 SnavelyReprojectionErrorWithQuaternions, 2, 4, 6, 3>(
269 new SnavelyReprojectionErrorWithQuaternions(
Keir Mierle8ebb0732012-04-30 23:09:08 -0700270 observations[2 * i + 0],
271 observations[2 * i + 1]));
272 } else {
273 cost_function =
274 new AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>(
275 new SnavelyReprojectionError(observations[2 * i + 0],
276 observations[2 * i + 1]));
277 }
278
279 // If enabled use Huber's loss function.
280 LossFunction* loss_function = FLAGS_robustify ? new HuberLoss(1.0) : NULL;
281
282 // Each observation correponds to a pair of a camera and a point
283 // which are identified by camera_index()[i] and point_index()[i]
284 // respectively.
285 double* camera =
286 cameras + camera_block_size * bal_problem->camera_index()[i];
287 double* point = points + point_block_size * bal_problem->point_index()[i];
288
289 if (FLAGS_use_quaternions) {
290 // When using quaternions, we split the camera into two
291 // parameter blocks. One of size 4 for the quaternion and the
292 // other of size 6 containing the translation, focal length and
293 // the radial distortion parameters.
294 problem->AddResidualBlock(cost_function,
295 loss_function,
296 camera,
297 camera + 4,
298 point);
299 } else {
300 problem->AddResidualBlock(cost_function, loss_function, camera, point);
301 }
302 }
303
304 if (FLAGS_use_quaternions && FLAGS_use_local_parameterization) {
305 LocalParameterization* quaternion_parameterization =
306 new QuaternionParameterization;
307 for (int i = 0; i < bal_problem->num_cameras(); ++i) {
308 problem->SetParameterization(cameras + camera_block_size * i,
309 quaternion_parameterization);
310 }
311 }
312}
313
314void SolveProblem(const char* filename) {
315 BALProblem bal_problem(filename, FLAGS_use_quaternions);
316 Problem problem;
Sameer Agarwal5476df52012-08-09 21:46:19 -0700317
Sameer Agarwal2c648db2013-03-05 15:20:15 -0800318 srand(FLAGS_random_seed);
Sameer Agarwal36a33092012-08-10 19:52:09 -0700319 bal_problem.Normalize();
Sameer Agarwal5476df52012-08-09 21:46:19 -0700320 bal_problem.Perturb(FLAGS_rotation_sigma,
321 FLAGS_translation_sigma,
322 FLAGS_point_sigma);
323
Keir Mierle8ebb0732012-04-30 23:09:08 -0700324 BuildProblem(&bal_problem, &problem);
325 Solver::Options options;
326 SetSolverOptionsFromFlags(&bal_problem, &options);
Sameer Agarwal1b7f3b52012-08-09 21:46:19 -0700327 options.solver_log = FLAGS_solver_log;
Sameer Agarwal9123e2f2012-09-18 21:49:06 -0700328 options.gradient_tolerance = 1e-16;
329 options.function_tolerance = 1e-16;
Keir Mierle8ebb0732012-04-30 23:09:08 -0700330 Solver::Summary summary;
331 Solve(options, &problem, &summary);
332 std::cout << summary.FullReport() << "\n";
333}
334
335} // namespace examples
336} // namespace ceres
337
338int main(int argc, char** argv) {
339 google::ParseCommandLineFlags(&argc, &argv, true);
340 google::InitGoogleLogging(argv[0]);
341 if (FLAGS_input.empty()) {
342 LOG(ERROR) << "Usage: bundle_adjustment_example --input=bal_problem";
343 return 1;
344 }
345
346 CHECK(FLAGS_use_quaternions || !FLAGS_use_local_parameterization)
347 << "--use_local_parameterization can only be used with "
348 << "--use_quaternions.";
349 ceres::examples::SolveProblem(FLAGS_input.c_str());
350 return 0;
351}