Blame examples/libmv_homography.cc

Packit ea1746
// Ceres Solver - A fast non-linear least squares minimizer
Packit ea1746
// Copyright 2015 Google Inc. All rights reserved.
Packit ea1746
// http://ceres-solver.org/
Packit ea1746
//
Packit ea1746
// Redistribution and use in source and binary forms, with or without
Packit ea1746
// modification, are permitted provided that the following conditions are met:
Packit ea1746
//
Packit ea1746
// * Redistributions of source code must retain the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer.
Packit ea1746
// * Redistributions in binary form must reproduce the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer in the documentation
Packit ea1746
//   and/or other materials provided with the distribution.
Packit ea1746
// * Neither the name of Google Inc. nor the names of its contributors may be
Packit ea1746
//   used to endorse or promote products derived from this software without
Packit ea1746
//   specific prior written permission.
Packit ea1746
//
Packit ea1746
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
Packit ea1746
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Packit ea1746
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
Packit ea1746
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
Packit ea1746
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Packit ea1746
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
Packit ea1746
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
Packit ea1746
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
Packit ea1746
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
Packit ea1746
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
Packit ea1746
// POSSIBILITY OF SUCH DAMAGE.
Packit ea1746
//
Packit ea1746
// Copyright (c) 2014 libmv authors.
Packit ea1746
//
Packit ea1746
// Permission is hereby granted, free of charge, to any person obtaining a copy
Packit ea1746
// of this software and associated documentation files (the "Software"), to
Packit ea1746
// deal in the Software without restriction, including without limitation the
Packit ea1746
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
Packit ea1746
// sell copies of the Software, and to permit persons to whom the Software is
Packit ea1746
// furnished to do so, subject to the following conditions:
Packit ea1746
//
Packit ea1746
// The above copyright notice and this permission notice shall be included in
Packit ea1746
// all copies or substantial portions of the Software.
Packit ea1746
//
Packit ea1746
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Packit ea1746
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Packit ea1746
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Packit ea1746
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Packit ea1746
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
Packit ea1746
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
Packit ea1746
// IN THE SOFTWARE.
Packit ea1746
//
Packit ea1746
// Author: sergey.vfx@gmail.com (Sergey Sharybin)
Packit ea1746
//
Packit ea1746
// This file demonstrates solving for a homography between two sets of points.
Packit ea1746
// A homography describes a transformation between a sets of points on a plane,
Packit ea1746
// perspectively projected into two images. The first step is to solve a
Packit ea1746
// homogeneous system of equations via singular value decompposition, giving an
Packit ea1746
// algebraic solution for the homography, then solving for a final solution by
Packit ea1746
// minimizing the symmetric transfer error in image space with Ceres (called the
Packit ea1746
// Gold Standard Solution in "Multiple View Geometry"). The routines are based on
Packit ea1746
// the routines from the Libmv library.
Packit ea1746
//
Packit ea1746
// This example demonstrates custom exit criterion by having a callback check
Packit ea1746
// for image-space error.
Packit ea1746
Packit ea1746
#include "ceres/ceres.h"
Packit ea1746
#include "glog/logging.h"
Packit ea1746
Packit ea1746
typedef Eigen::NumTraits<double> EigenDouble;
Packit ea1746
Packit ea1746
typedef Eigen::MatrixXd Mat;
Packit ea1746
typedef Eigen::VectorXd Vec;
Packit ea1746
typedef Eigen::Matrix<double, 3, 3> Mat3;
Packit ea1746
typedef Eigen::Matrix<double, 2, 1> Vec2;
Packit ea1746
typedef Eigen::Matrix<double, Eigen::Dynamic,  8> MatX8;
Packit ea1746
typedef Eigen::Vector3d Vec3;
Packit ea1746
Packit ea1746
namespace {
Packit ea1746
Packit ea1746
// This structure contains options that controls how the homography
Packit ea1746
// estimation operates.
Packit ea1746
//
Packit ea1746
// Defaults should be suitable for a wide range of use cases, but
Packit ea1746
// better performance and accuracy might require tweaking.
Packit ea1746
struct EstimateHomographyOptions {
Packit ea1746
  // Default settings for homography estimation which should be suitable
Packit ea1746
  // for a wide range of use cases.
Packit ea1746
  EstimateHomographyOptions()
Packit ea1746
    :  max_num_iterations(50),
Packit ea1746
       expected_average_symmetric_distance(1e-16) {}
Packit ea1746
Packit ea1746
  // Maximal number of iterations for the refinement step.
Packit ea1746
  int max_num_iterations;
Packit ea1746
Packit ea1746
  // Expected average of symmetric geometric distance between
Packit ea1746
  // actual destination points and original ones transformed by
Packit ea1746
  // estimated homography matrix.
Packit ea1746
  //
Packit ea1746
  // Refinement will finish as soon as average of symmetric
Packit ea1746
  // geometric distance is less or equal to this value.
Packit ea1746
  //
Packit ea1746
  // This distance is measured in the same units as input points are.
Packit ea1746
  double expected_average_symmetric_distance;
Packit ea1746
};
Packit ea1746
Packit ea1746
// Calculate symmetric geometric cost terms:
Packit ea1746
//
Packit ea1746
// forward_error = D(H * x1, x2)
Packit ea1746
// backward_error = D(H^-1 * x2, x1)
Packit ea1746
//
Packit ea1746
// Templated to be used with autodifferenciation.
Packit ea1746
template <typename T>
Packit ea1746
void SymmetricGeometricDistanceTerms(const Eigen::Matrix<T, 3, 3> &H,
Packit ea1746
                                     const Eigen::Matrix<T, 2, 1> &x1,
Packit ea1746
                                     const Eigen::Matrix<T, 2, 1> &x2,
Packit ea1746
                                     T forward_error[2],
Packit ea1746
                                     T backward_error[2]) {
Packit ea1746
  typedef Eigen::Matrix<T, 3, 1> Vec3;
Packit ea1746
  Vec3 x(x1(0), x1(1), T(1.0));
Packit ea1746
  Vec3 y(x2(0), x2(1), T(1.0));
Packit ea1746
Packit ea1746
  Vec3 H_x = H * x;
Packit ea1746
  Vec3 Hinv_y = H.inverse() * y;
Packit ea1746
Packit ea1746
  H_x /= H_x(2);
Packit ea1746
  Hinv_y /= Hinv_y(2);
Packit ea1746
Packit ea1746
  forward_error[0] = H_x(0) - y(0);
Packit ea1746
  forward_error[1] = H_x(1) - y(1);
Packit ea1746
  backward_error[0] = Hinv_y(0) - x(0);
Packit ea1746
  backward_error[1] = Hinv_y(1) - x(1);
Packit ea1746
}
Packit ea1746
Packit ea1746
// Calculate symmetric geometric cost:
Packit ea1746
//
Packit ea1746
//   D(H * x1, x2)^2 + D(H^-1 * x2, x1)^2
Packit ea1746
//
Packit ea1746
double SymmetricGeometricDistance(const Mat3 &H,
Packit ea1746
                                  const Vec2 &x1,
Packit ea1746
                                  const Vec2 &x2) {
Packit ea1746
  Vec2 forward_error, backward_error;
Packit ea1746
  SymmetricGeometricDistanceTerms<double>(H,
Packit ea1746
                                          x1,
Packit ea1746
                                          x2,
Packit ea1746
                                          forward_error.data(),
Packit ea1746
                                          backward_error.data());
Packit ea1746
  return forward_error.squaredNorm() +
Packit ea1746
         backward_error.squaredNorm();
Packit ea1746
}
Packit ea1746
Packit ea1746
// A parameterization of the 2D homography matrix that uses 8 parameters so
Packit ea1746
// that the matrix is normalized (H(2,2) == 1).
Packit ea1746
// The homography matrix H is built from a list of 8 parameters (a, b,...g, h)
Packit ea1746
// as follows
Packit ea1746
//
Packit ea1746
//         |a b c|
Packit ea1746
//     H = |d e f|
Packit ea1746
//         |g h 1|
Packit ea1746
//
Packit ea1746
template<typename T = double>
Packit ea1746
class Homography2DNormalizedParameterization {
Packit ea1746
 public:
Packit ea1746
  typedef Eigen::Matrix<T, 8, 1> Parameters;     // a, b, ... g, h
Packit ea1746
  typedef Eigen::Matrix<T, 3, 3> Parameterized;  // H
Packit ea1746
Packit ea1746
  // Convert from the 8 parameters to a H matrix.
Packit ea1746
  static void To(const Parameters &p, Parameterized *h) {
Packit ea1746
    *h << p(0), p(1), p(2),
Packit ea1746
          p(3), p(4), p(5),
Packit ea1746
          p(6), p(7), 1.0;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Convert from a H matrix to the 8 parameters.
Packit ea1746
  static void From(const Parameterized &h, Parameters *p) {
Packit ea1746
    *p << h(0, 0), h(0, 1), h(0, 2),
Packit ea1746
          h(1, 0), h(1, 1), h(1, 2),
Packit ea1746
          h(2, 0), h(2, 1);
Packit ea1746
  }
Packit ea1746
};
Packit ea1746
Packit ea1746
// 2D Homography transformation estimation in the case that points are in
Packit ea1746
// euclidean coordinates.
Packit ea1746
//
Packit ea1746
//   x = H y
Packit ea1746
//
Packit ea1746
// x and y vector must have the same direction, we could write
Packit ea1746
//
Packit ea1746
//   crossproduct(|x|, * H * |y| ) = |0|
Packit ea1746
//
Packit ea1746
//   | 0 -1  x2|   |a b c|   |y1|    |0|
Packit ea1746
//   | 1  0 -x1| * |d e f| * |y2| =  |0|
Packit ea1746
//   |-x2  x1 0|   |g h 1|   |1 |    |0|
Packit ea1746
//
Packit ea1746
// That gives:
Packit ea1746
//
Packit ea1746
//   (-d+x2*g)*y1    + (-e+x2*h)*y2 + -f+x2          |0|
Packit ea1746
//   (a-x1*g)*y1     + (b-x1*h)*y2  + c-x1         = |0|
Packit ea1746
//   (-x2*a+x1*d)*y1 + (-x2*b+x1*e)*y2 + -x2*c+x1*f  |0|
Packit ea1746
//
Packit ea1746
bool Homography2DFromCorrespondencesLinearEuc(
Packit ea1746
    const Mat &x1,
Packit ea1746
    const Mat &x2,
Packit ea1746
    Mat3 *H,
Packit ea1746
    double expected_precision) {
Packit ea1746
  assert(2 == x1.rows());
Packit ea1746
  assert(4 <= x1.cols());
Packit ea1746
  assert(x1.rows() == x2.rows());
Packit ea1746
  assert(x1.cols() == x2.cols());
Packit ea1746
Packit ea1746
  int n = x1.cols();
Packit ea1746
  MatX8 L = Mat::Zero(n * 3, 8);
Packit ea1746
  Mat b = Mat::Zero(n * 3, 1);
Packit ea1746
  for (int i = 0; i < n; ++i) {
Packit ea1746
    int j = 3 * i;
Packit ea1746
    L(j, 0) =  x1(0, i);             // a
Packit ea1746
    L(j, 1) =  x1(1, i);             // b
Packit ea1746
    L(j, 2) =  1.0;                  // c
Packit ea1746
    L(j, 6) = -x2(0, i) * x1(0, i);  // g
Packit ea1746
    L(j, 7) = -x2(0, i) * x1(1, i);  // h
Packit ea1746
    b(j, 0) =  x2(0, i);             // i
Packit ea1746
Packit ea1746
    ++j;
Packit ea1746
    L(j, 3) =  x1(0, i);             // d
Packit ea1746
    L(j, 4) =  x1(1, i);             // e
Packit ea1746
    L(j, 5) =  1.0;                  // f
Packit ea1746
    L(j, 6) = -x2(1, i) * x1(0, i);  // g
Packit ea1746
    L(j, 7) = -x2(1, i) * x1(1, i);  // h
Packit ea1746
    b(j, 0) =  x2(1, i);             // i
Packit ea1746
Packit ea1746
    // This ensures better stability
Packit ea1746
    // TODO(julien) make a lite version without this 3rd set
Packit ea1746
    ++j;
Packit ea1746
    L(j, 0) =  x2(1, i) * x1(0, i);  // a
Packit ea1746
    L(j, 1) =  x2(1, i) * x1(1, i);  // b
Packit ea1746
    L(j, 2) =  x2(1, i);             // c
Packit ea1746
    L(j, 3) = -x2(0, i) * x1(0, i);  // d
Packit ea1746
    L(j, 4) = -x2(0, i) * x1(1, i);  // e
Packit ea1746
    L(j, 5) = -x2(0, i);             // f
Packit ea1746
  }
Packit ea1746
  // Solve Lx=B
Packit ea1746
  const Vec h = L.fullPivLu().solve(b);
Packit ea1746
  Homography2DNormalizedParameterization<double>::To(h, H);
Packit ea1746
  return (L * h).isApprox(b, expected_precision);
Packit ea1746
}
Packit ea1746
Packit ea1746
// Cost functor which computes symmetric geometric distance
Packit ea1746
// used for homography matrix refinement.
Packit ea1746
class HomographySymmetricGeometricCostFunctor {
Packit ea1746
 public:
Packit ea1746
  HomographySymmetricGeometricCostFunctor(const Vec2 &x,
Packit ea1746
                                          const Vec2 &y)
Packit ea1746
      : x_(x), y_(y) { }
Packit ea1746
Packit ea1746
  template<typename T>
Packit ea1746
  bool operator()(const T* homography_parameters, T* residuals) const {
Packit ea1746
    typedef Eigen::Matrix<T, 3, 3> Mat3;
Packit ea1746
    typedef Eigen::Matrix<T, 2, 1> Vec2;
Packit ea1746
Packit ea1746
    Mat3 H(homography_parameters);
Packit ea1746
    Vec2 x(T(x_(0)), T(x_(1)));
Packit ea1746
    Vec2 y(T(y_(0)), T(y_(1)));
Packit ea1746
Packit ea1746
    SymmetricGeometricDistanceTerms<T>(H,
Packit ea1746
                                       x,
Packit ea1746
                                       y,
Packit ea1746
                                       &residuals[0],
Packit ea1746
                                       &residuals[2]);
Packit ea1746
    return true;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  const Vec2 x_;
Packit ea1746
  const Vec2 y_;
Packit ea1746
};
Packit ea1746
Packit ea1746
// Termination checking callback. This is needed to finish the
Packit ea1746
// optimization when an absolute error threshold is met, as opposed
Packit ea1746
// to Ceres's function_tolerance, which provides for finishing when
Packit ea1746
// successful steps reduce the cost function by a fractional amount.
Packit ea1746
// In this case, the callback checks for the absolute average reprojection
Packit ea1746
// error and terminates when it's below a threshold (for example all
Packit ea1746
// points < 0.5px error).
Packit ea1746
class TerminationCheckingCallback : public ceres::IterationCallback {
Packit ea1746
 public:
Packit ea1746
  TerminationCheckingCallback(const Mat &x1, const Mat &x2,
Packit ea1746
                              const EstimateHomographyOptions &options,
Packit ea1746
                              Mat3 *H)
Packit ea1746
      : options_(options), x1_(x1), x2_(x2), H_(H) {}
Packit ea1746
Packit ea1746
  virtual ceres::CallbackReturnType operator()(
Packit ea1746
      const ceres::IterationSummary& summary) {
Packit ea1746
    // If the step wasn't successful, there's nothing to do.
Packit ea1746
    if (!summary.step_is_successful) {
Packit ea1746
      return ceres::SOLVER_CONTINUE;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    // Calculate average of symmetric geometric distance.
Packit ea1746
    double average_distance = 0.0;
Packit ea1746
    for (int i = 0; i < x1_.cols(); i++) {
Packit ea1746
      average_distance += SymmetricGeometricDistance(*H_,
Packit ea1746
                                                     x1_.col(i),
Packit ea1746
                                                     x2_.col(i));
Packit ea1746
    }
Packit ea1746
    average_distance /= x1_.cols();
Packit ea1746
Packit ea1746
    if (average_distance <= options_.expected_average_symmetric_distance) {
Packit ea1746
      return ceres::SOLVER_TERMINATE_SUCCESSFULLY;
Packit ea1746
    }
Packit ea1746
Packit ea1746
    return ceres::SOLVER_CONTINUE;
Packit ea1746
  }
Packit ea1746
Packit ea1746
 private:
Packit ea1746
  const EstimateHomographyOptions &options_;
Packit ea1746
  const Mat &x1;;
Packit ea1746
  const Mat &x2;;
Packit ea1746
  Mat3 *H_;
Packit ea1746
};
Packit ea1746
Packit ea1746
bool EstimateHomography2DFromCorrespondences(
Packit ea1746
    const Mat &x1,
Packit ea1746
    const Mat &x2,
Packit ea1746
    const EstimateHomographyOptions &options,
Packit ea1746
    Mat3 *H) {
Packit ea1746
  assert(2 == x1.rows());
Packit ea1746
  assert(4 <= x1.cols());
Packit ea1746
  assert(x1.rows() == x2.rows());
Packit ea1746
  assert(x1.cols() == x2.cols());
Packit ea1746
Packit ea1746
  // Step 1: Algebraic homography estimation.
Packit ea1746
  // Assume algebraic estimation always succeeds.
Packit ea1746
  Homography2DFromCorrespondencesLinearEuc(x1,
Packit ea1746
                                           x2,
Packit ea1746
                                           H,
Packit ea1746
                                           EigenDouble::dummy_precision());
Packit ea1746
Packit ea1746
  LOG(INFO) << "Estimated matrix after algebraic estimation:\n" << *H;
Packit ea1746
Packit ea1746
  // Step 2: Refine matrix using Ceres minimizer.
Packit ea1746
  ceres::Problem problem;
Packit ea1746
  for (int i = 0; i < x1.cols(); i++) {
Packit ea1746
    HomographySymmetricGeometricCostFunctor
Packit ea1746
        *homography_symmetric_geometric_cost_function =
Packit ea1746
            new HomographySymmetricGeometricCostFunctor(x1.col(i),
Packit ea1746
                                                        x2.col(i));
Packit ea1746
Packit ea1746
    problem.AddResidualBlock(
Packit ea1746
        new ceres::AutoDiffCostFunction<
Packit ea1746
            HomographySymmetricGeometricCostFunctor,
Packit ea1746
            4,  // num_residuals
Packit ea1746
            9>(homography_symmetric_geometric_cost_function),
Packit ea1746
        NULL,
Packit ea1746
        H->data());
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Configure the solve.
Packit ea1746
  ceres::Solver::Options solver_options;
Packit ea1746
  solver_options.linear_solver_type = ceres::DENSE_QR;
Packit ea1746
  solver_options.max_num_iterations = options.max_num_iterations;
Packit ea1746
  solver_options.update_state_every_iteration = true;
Packit ea1746
Packit ea1746
  // Terminate if the average symmetric distance is good enough.
Packit ea1746
  TerminationCheckingCallback callback(x1, x2, options, H);
Packit ea1746
  solver_options.callbacks.push_back(&callback);
Packit ea1746
Packit ea1746
  // Run the solve.
Packit ea1746
  ceres::Solver::Summary summary;
Packit ea1746
  ceres::Solve(solver_options, &problem, &summary);
Packit ea1746
Packit ea1746
  LOG(INFO) << "Summary:\n" << summary.FullReport();
Packit ea1746
  LOG(INFO) << "Final refined matrix:\n" << *H;
Packit ea1746
Packit ea1746
  return summary.IsSolutionUsable();
Packit ea1746
}
Packit ea1746
Packit ea1746
}  // namespace libmv
Packit ea1746
Packit ea1746
int main(int argc, char **argv) {
Packit ea1746
  google::InitGoogleLogging(argv[0]);
Packit ea1746
Packit ea1746
  Mat x1(2, 100);
Packit ea1746
  for (int i = 0; i < x1.cols(); ++i) {
Packit ea1746
    x1(0, i) = rand() % 1024;
Packit ea1746
    x1(1, i) = rand() % 1024;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  Mat3 homography_matrix;
Packit ea1746
  // This matrix has been dumped from a Blender test file of plane tracking.
Packit ea1746
  homography_matrix << 1.243715, -0.461057, -111.964454,
Packit ea1746
                       0.0,       0.617589, -192.379252,
Packit ea1746
                       0.0,      -0.000983,    1.0;
Packit ea1746
Packit ea1746
  Mat x2 = x1;
Packit ea1746
  for (int i = 0; i < x2.cols(); ++i) {
Packit ea1746
    Vec3 homogenous_x1 = Vec3(x1(0, i), x1(1, i), 1.0);
Packit ea1746
    Vec3 homogenous_x2 = homography_matrix * homogenous_x1;
Packit ea1746
    x2(0, i) = homogenous_x2(0) / homogenous_x2(2);
Packit ea1746
    x2(1, i) = homogenous_x2(1) / homogenous_x2(2);
Packit ea1746
Packit ea1746
    // Apply some noise so algebraic estimation is not good enough.
Packit ea1746
    x2(0, i) += static_cast<double>(rand() % 1000) / 5000.0;
Packit ea1746
    x2(1, i) += static_cast<double>(rand() % 1000) / 5000.0;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  Mat3 estimated_matrix;
Packit ea1746
Packit ea1746
  EstimateHomographyOptions options;
Packit ea1746
  options.expected_average_symmetric_distance = 0.02;
Packit ea1746
  EstimateHomography2DFromCorrespondences(x1, x2, options, &estimated_matrix);
Packit ea1746
Packit ea1746
  // Normalize the matrix for easier comparison.
Packit ea1746
  estimated_matrix /= estimated_matrix(2 ,2);
Packit ea1746
Packit ea1746
  std::cout << "Original matrix:\n" << homography_matrix << "\n";
Packit ea1746
  std::cout << "Estimated matrix:\n" << estimated_matrix << "\n";
Packit ea1746
Packit ea1746
  return EXIT_SUCCESS;
Packit ea1746
}