blob: 55f3b70048c2cb0b0ac251623821bf32d93341f1 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2015 Google Inc. All rights reserved.
3// http://ceres-solver.org/
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// Copyright (c) 2014 libmv authors.
30//
31// Permission is hereby granted, free of charge, to any person obtaining a copy
32// of this software and associated documentation files (the "Software"), to
33// deal in the Software without restriction, including without limitation the
34// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
35// sell copies of the Software, and to permit persons to whom the Software is
36// furnished to do so, subject to the following conditions:
37//
38// The above copyright notice and this permission notice shall be included in
39// all copies or substantial portions of the Software.
40//
41// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
44// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
46// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
47// IN THE SOFTWARE.
48//
49// Author: sergey.vfx@gmail.com (Sergey Sharybin)
50//
51// This file demonstrates solving for a homography between two sets of points.
52// A homography describes a transformation between a sets of points on a plane,
53// perspectively projected into two images. The first step is to solve a
54// homogeneous system of equations via singular value decomposition, giving an
55// algebraic solution for the homography, then solving for a final solution by
56// minimizing the symmetric transfer error in image space with Ceres (called the
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080057// Gold Standard Solution in "Multiple View Geometry"). The routines are based
58// on the routines from the Libmv library.
Austin Schuh70cc9552019-01-21 19:46:48 -080059//
60// This example demonstrates custom exit criterion by having a callback check
61// for image-space error.
62
63#include "ceres/ceres.h"
64#include "glog/logging.h"
65
66typedef Eigen::NumTraits<double> EigenDouble;
67
68typedef Eigen::MatrixXd Mat;
69typedef Eigen::VectorXd Vec;
70typedef Eigen::Matrix<double, 3, 3> Mat3;
71typedef Eigen::Matrix<double, 2, 1> Vec2;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080072typedef Eigen::Matrix<double, Eigen::Dynamic, 8> MatX8;
Austin Schuh70cc9552019-01-21 19:46:48 -080073typedef Eigen::Vector3d Vec3;
74
75namespace {
76
77// This structure contains options that controls how the homography
78// estimation operates.
79//
80// Defaults should be suitable for a wide range of use cases, but
81// better performance and accuracy might require tweaking.
82struct EstimateHomographyOptions {
83 // Default settings for homography estimation which should be suitable
84 // for a wide range of use cases.
85 EstimateHomographyOptions()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080086 : max_num_iterations(50), expected_average_symmetric_distance(1e-16) {}
Austin Schuh70cc9552019-01-21 19:46:48 -080087
88 // Maximal number of iterations for the refinement step.
89 int max_num_iterations;
90
91 // Expected average of symmetric geometric distance between
92 // actual destination points and original ones transformed by
93 // estimated homography matrix.
94 //
95 // Refinement will finish as soon as average of symmetric
96 // geometric distance is less or equal to this value.
97 //
98 // This distance is measured in the same units as input points are.
99 double expected_average_symmetric_distance;
100};
101
102// Calculate symmetric geometric cost terms:
103//
104// forward_error = D(H * x1, x2)
105// backward_error = D(H^-1 * x2, x1)
106//
107// Templated to be used with autodifferentiation.
108template <typename T>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800109void SymmetricGeometricDistanceTerms(const Eigen::Matrix<T, 3, 3>& H,
110 const Eigen::Matrix<T, 2, 1>& x1,
111 const Eigen::Matrix<T, 2, 1>& x2,
Austin Schuh70cc9552019-01-21 19:46:48 -0800112 T forward_error[2],
113 T backward_error[2]) {
114 typedef Eigen::Matrix<T, 3, 1> Vec3;
115 Vec3 x(x1(0), x1(1), T(1.0));
116 Vec3 y(x2(0), x2(1), T(1.0));
117
118 Vec3 H_x = H * x;
119 Vec3 Hinv_y = H.inverse() * y;
120
121 H_x /= H_x(2);
122 Hinv_y /= Hinv_y(2);
123
124 forward_error[0] = H_x(0) - y(0);
125 forward_error[1] = H_x(1) - y(1);
126 backward_error[0] = Hinv_y(0) - x(0);
127 backward_error[1] = Hinv_y(1) - x(1);
128}
129
130// Calculate symmetric geometric cost:
131//
132// D(H * x1, x2)^2 + D(H^-1 * x2, x1)^2
133//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800134double SymmetricGeometricDistance(const Mat3& H,
135 const Vec2& x1,
136 const Vec2& x2) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800137 Vec2 forward_error, backward_error;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800138 SymmetricGeometricDistanceTerms<double>(
139 H, x1, x2, forward_error.data(), backward_error.data());
140 return forward_error.squaredNorm() + backward_error.squaredNorm();
Austin Schuh70cc9552019-01-21 19:46:48 -0800141}
142
143// A parameterization of the 2D homography matrix that uses 8 parameters so
144// that the matrix is normalized (H(2,2) == 1).
145// The homography matrix H is built from a list of 8 parameters (a, b,...g, h)
146// as follows
147//
148// |a b c|
149// H = |d e f|
150// |g h 1|
151//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800152template <typename T = double>
Austin Schuh70cc9552019-01-21 19:46:48 -0800153class Homography2DNormalizedParameterization {
154 public:
155 typedef Eigen::Matrix<T, 8, 1> Parameters; // a, b, ... g, h
156 typedef Eigen::Matrix<T, 3, 3> Parameterized; // H
157
158 // Convert from the 8 parameters to a H matrix.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800159 static void To(const Parameters& p, Parameterized* h) {
160 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800161 *h << p(0), p(1), p(2),
162 p(3), p(4), p(5),
163 p(6), p(7), 1.0;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800164 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800165 }
166
167 // Convert from a H matrix to the 8 parameters.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800168 static void From(const Parameterized& h, Parameters* p) {
169 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800170 *p << h(0, 0), h(0, 1), h(0, 2),
171 h(1, 0), h(1, 1), h(1, 2),
172 h(2, 0), h(2, 1);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800173 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800174 }
175};
176
177// 2D Homography transformation estimation in the case that points are in
178// euclidean coordinates.
179//
180// x = H y
181//
182// x and y vector must have the same direction, we could write
183//
184// crossproduct(|x|, * H * |y| ) = |0|
185//
186// | 0 -1 x2| |a b c| |y1| |0|
187// | 1 0 -x1| * |d e f| * |y2| = |0|
188// |-x2 x1 0| |g h 1| |1 | |0|
189//
190// That gives:
191//
192// (-d+x2*g)*y1 + (-e+x2*h)*y2 + -f+x2 |0|
193// (a-x1*g)*y1 + (b-x1*h)*y2 + c-x1 = |0|
194// (-x2*a+x1*d)*y1 + (-x2*b+x1*e)*y2 + -x2*c+x1*f |0|
195//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800196bool Homography2DFromCorrespondencesLinearEuc(const Mat& x1,
197 const Mat& x2,
198 Mat3* H,
199 double expected_precision) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800200 assert(2 == x1.rows());
201 assert(4 <= x1.cols());
202 assert(x1.rows() == x2.rows());
203 assert(x1.cols() == x2.cols());
204
205 int n = x1.cols();
206 MatX8 L = Mat::Zero(n * 3, 8);
207 Mat b = Mat::Zero(n * 3, 1);
208 for (int i = 0; i < n; ++i) {
209 int j = 3 * i;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800210 L(j, 0) = x1(0, i); // a
211 L(j, 1) = x1(1, i); // b
212 L(j, 2) = 1.0; // c
Austin Schuh70cc9552019-01-21 19:46:48 -0800213 L(j, 6) = -x2(0, i) * x1(0, i); // g
214 L(j, 7) = -x2(0, i) * x1(1, i); // h
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800215 b(j, 0) = x2(0, i); // i
Austin Schuh70cc9552019-01-21 19:46:48 -0800216
217 ++j;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800218 L(j, 3) = x1(0, i); // d
219 L(j, 4) = x1(1, i); // e
220 L(j, 5) = 1.0; // f
Austin Schuh70cc9552019-01-21 19:46:48 -0800221 L(j, 6) = -x2(1, i) * x1(0, i); // g
222 L(j, 7) = -x2(1, i) * x1(1, i); // h
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800223 b(j, 0) = x2(1, i); // i
Austin Schuh70cc9552019-01-21 19:46:48 -0800224
225 // This ensures better stability
226 // TODO(julien) make a lite version without this 3rd set
227 ++j;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800228 L(j, 0) = x2(1, i) * x1(0, i); // a
229 L(j, 1) = x2(1, i) * x1(1, i); // b
230 L(j, 2) = x2(1, i); // c
Austin Schuh70cc9552019-01-21 19:46:48 -0800231 L(j, 3) = -x2(0, i) * x1(0, i); // d
232 L(j, 4) = -x2(0, i) * x1(1, i); // e
233 L(j, 5) = -x2(0, i); // f
234 }
235 // Solve Lx=B
236 const Vec h = L.fullPivLu().solve(b);
237 Homography2DNormalizedParameterization<double>::To(h, H);
238 return (L * h).isApprox(b, expected_precision);
239}
240
241// Cost functor which computes symmetric geometric distance
242// used for homography matrix refinement.
243class HomographySymmetricGeometricCostFunctor {
244 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800245 HomographySymmetricGeometricCostFunctor(const Vec2& x, const Vec2& y)
246 : x_(x), y_(y) {}
Austin Schuh70cc9552019-01-21 19:46:48 -0800247
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800248 template <typename T>
Austin Schuh70cc9552019-01-21 19:46:48 -0800249 bool operator()(const T* homography_parameters, T* residuals) const {
250 typedef Eigen::Matrix<T, 3, 3> Mat3;
251 typedef Eigen::Matrix<T, 2, 1> Vec2;
252
253 Mat3 H(homography_parameters);
254 Vec2 x(T(x_(0)), T(x_(1)));
255 Vec2 y(T(y_(0)), T(y_(1)));
256
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800257 SymmetricGeometricDistanceTerms<T>(H, x, y, &residuals[0], &residuals[2]);
Austin Schuh70cc9552019-01-21 19:46:48 -0800258 return true;
259 }
260
261 const Vec2 x_;
262 const Vec2 y_;
263};
264
265// Termination checking callback. This is needed to finish the
266// optimization when an absolute error threshold is met, as opposed
267// to Ceres's function_tolerance, which provides for finishing when
268// successful steps reduce the cost function by a fractional amount.
269// In this case, the callback checks for the absolute average reprojection
270// error and terminates when it's below a threshold (for example all
271// points < 0.5px error).
272class TerminationCheckingCallback : public ceres::IterationCallback {
273 public:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800274 TerminationCheckingCallback(const Mat& x1,
275 const Mat& x2,
276 const EstimateHomographyOptions& options,
277 Mat3* H)
Austin Schuh70cc9552019-01-21 19:46:48 -0800278 : options_(options), x1_(x1), x2_(x2), H_(H) {}
279
280 virtual ceres::CallbackReturnType operator()(
281 const ceres::IterationSummary& summary) {
282 // If the step wasn't successful, there's nothing to do.
283 if (!summary.step_is_successful) {
284 return ceres::SOLVER_CONTINUE;
285 }
286
287 // Calculate average of symmetric geometric distance.
288 double average_distance = 0.0;
289 for (int i = 0; i < x1_.cols(); i++) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800290 average_distance +=
291 SymmetricGeometricDistance(*H_, x1_.col(i), x2_.col(i));
Austin Schuh70cc9552019-01-21 19:46:48 -0800292 }
293 average_distance /= x1_.cols();
294
295 if (average_distance <= options_.expected_average_symmetric_distance) {
296 return ceres::SOLVER_TERMINATE_SUCCESSFULLY;
297 }
298
299 return ceres::SOLVER_CONTINUE;
300 }
301
302 private:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800303 const EstimateHomographyOptions& options_;
304 const Mat& x1_;
305 const Mat& x2_;
306 Mat3* H_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800307};
308
309bool EstimateHomography2DFromCorrespondences(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800310 const Mat& x1,
311 const Mat& x2,
312 const EstimateHomographyOptions& options,
313 Mat3* H) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800314 assert(2 == x1.rows());
315 assert(4 <= x1.cols());
316 assert(x1.rows() == x2.rows());
317 assert(x1.cols() == x2.cols());
318
319 // Step 1: Algebraic homography estimation.
320 // Assume algebraic estimation always succeeds.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800321 Homography2DFromCorrespondencesLinearEuc(
322 x1, x2, H, EigenDouble::dummy_precision());
Austin Schuh70cc9552019-01-21 19:46:48 -0800323
324 LOG(INFO) << "Estimated matrix after algebraic estimation:\n" << *H;
325
326 // Step 2: Refine matrix using Ceres minimizer.
327 ceres::Problem problem;
328 for (int i = 0; i < x1.cols(); i++) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800329 HomographySymmetricGeometricCostFunctor*
330 homography_symmetric_geometric_cost_function =
331 new HomographySymmetricGeometricCostFunctor(x1.col(i), x2.col(i));
Austin Schuh70cc9552019-01-21 19:46:48 -0800332
333 problem.AddResidualBlock(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800334 new ceres::AutoDiffCostFunction<HomographySymmetricGeometricCostFunctor,
335 4, // num_residuals
336 9>(
337 homography_symmetric_geometric_cost_function),
Austin Schuh70cc9552019-01-21 19:46:48 -0800338 NULL,
339 H->data());
340 }
341
342 // Configure the solve.
343 ceres::Solver::Options solver_options;
344 solver_options.linear_solver_type = ceres::DENSE_QR;
345 solver_options.max_num_iterations = options.max_num_iterations;
346 solver_options.update_state_every_iteration = true;
347
348 // Terminate if the average symmetric distance is good enough.
349 TerminationCheckingCallback callback(x1, x2, options, H);
350 solver_options.callbacks.push_back(&callback);
351
352 // Run the solve.
353 ceres::Solver::Summary summary;
354 ceres::Solve(solver_options, &problem, &summary);
355
356 LOG(INFO) << "Summary:\n" << summary.FullReport();
357 LOG(INFO) << "Final refined matrix:\n" << *H;
358
359 return summary.IsSolutionUsable();
360}
361
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800362} // namespace
Austin Schuh70cc9552019-01-21 19:46:48 -0800363
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800364int main(int argc, char** argv) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800365 google::InitGoogleLogging(argv[0]);
366
367 Mat x1(2, 100);
368 for (int i = 0; i < x1.cols(); ++i) {
369 x1(0, i) = rand() % 1024;
370 x1(1, i) = rand() % 1024;
371 }
372
373 Mat3 homography_matrix;
374 // This matrix has been dumped from a Blender test file of plane tracking.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800375 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800376 homography_matrix << 1.243715, -0.461057, -111.964454,
377 0.0, 0.617589, -192.379252,
378 0.0, -0.000983, 1.0;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800379 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800380
381 Mat x2 = x1;
382 for (int i = 0; i < x2.cols(); ++i) {
383 Vec3 homogenous_x1 = Vec3(x1(0, i), x1(1, i), 1.0);
384 Vec3 homogenous_x2 = homography_matrix * homogenous_x1;
385 x2(0, i) = homogenous_x2(0) / homogenous_x2(2);
386 x2(1, i) = homogenous_x2(1) / homogenous_x2(2);
387
388 // Apply some noise so algebraic estimation is not good enough.
389 x2(0, i) += static_cast<double>(rand() % 1000) / 5000.0;
390 x2(1, i) += static_cast<double>(rand() % 1000) / 5000.0;
391 }
392
393 Mat3 estimated_matrix;
394
395 EstimateHomographyOptions options;
396 options.expected_average_symmetric_distance = 0.02;
397 EstimateHomography2DFromCorrespondences(x1, x2, options, &estimated_matrix);
398
399 // Normalize the matrix for easier comparison.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800400 estimated_matrix /= estimated_matrix(2, 2);
Austin Schuh70cc9552019-01-21 19:46:48 -0800401
402 std::cout << "Original matrix:\n" << homography_matrix << "\n";
403 std::cout << "Estimated matrix:\n" << estimated_matrix << "\n";
404
405 return EXIT_SUCCESS;
406}