ceres的基本使用
全部来自于官网ceres官方教材链接
推荐一个博客,感觉写的不错Ceres Solver 官方教程学习笔记
使用ceres时CMakeLists写法
cmake_minimum_required(VERSION 3.0.2)
project(usetools)
find_package(Ceres REQUIRED)
include_directories(
${CERES_INCLUDE_DIRS}
)
add_executable(ceres_learning src/ceres_learning.cpp)
target_link_libraries(ceres_learning ${CERES_LIBRARIES})
ceres三种求导方式基本写法
#include <iostream>
#include "ceres/ceres.h"
#include "glog/logging.h"
using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::NumericDiffCostFunction;
using ceres::Problem;
using ceres::SizedCostFunction;
using ceres::Solve;
using ceres::Solver;
// A templated cost functor that implements the residual r = 10 -
// x. The method operator() is templated so that we can then use an
// automatic differentiation wrapper around it to generate its
// derivatives.
// 自动求导
struct CostFunctor
{
template <typename T>
bool operator()(const T* const x, T *residual) const
{
residual[0] = T(10.0) - x[0];
return true;
}
};
// 数值求导
struct NumericDiffCostFunctor
{
bool operator()(const double * const x, double *residual) const
{
residual[0] = 10.0 - x[0];
return true;
}
};
// 解析求导
class QuadraticCostFunction : public ceres::SizedCostFunction<1, 1>
{
public:
virtual ~QuadraticCostFunction() {}
virtual bool Evaluate(double const *const *parameters,
double *residual,
double **jacobians) const
{
const double x = parameters[0][0];
residual[0] = 10 - x;
if (jacobians != nullptr && jacobians[0] != nullptr)
{
jacobians[0][0] = -1;
}
return true;
}
};
int main(int argc, char **argv)
{
google::InitGoogleLogging(argv[0]);
// The variable to solve for with its initial value. It will be
double initial_x = 5.0;
double x = initial_x;
Problem problem;
// CostFunction *cost_function = new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
// CostFunction *cost_function = new NumericDiffCostFunction<NumericDiffCostFunctor, ceres::CENTRAL, 1, 1>(new NumericDiffCostFunctor);
CostFunction *cost_function = new QuadraticCostFunction;
problem.AddResidualBlock(cost_function, nullptr, &x);
Solver::Options options;
options.linear_solver_type = ceres::DENSE_QR;
options.minimizer_progress_to_stdout = true;
Solver::Summary summary;
Solve(options, &problem, &summary);
std::cout << summary.BriefReport() << '\n';
std::cout << "x : " << initial_x << " -> " << x << '\n';
}