ceres_p1.cpp
#include <iostream>
#include <ceres/ceres.h>
using namespace std;
struct CostFunction_model {
template <class T>
bool operator () (const T* const x, T* residual) const {
// g(x) = 10 - x的残差方程
residual[0] = T(10.0) - x[0];
return true;
}
};
int main(int argc, char** argv) {
// 未知数的初始值
double init_x = 4.0;
double temp_x = init_x; // 备份
// 建立Problem
ceres::Problem problem;
// 建立残差方程
ceres::CostFunction* costFunction = new ceres::AutoDiffCostFunction<CostFunction_model, 1, 1>(new CostFunction_model);
problem.AddResidualBlock(costFunction, NULL, &init_x);
// 求解方程
ceres::Solver::Options options;
options.linear_solver_type = ceres::DENSE_QR;
// 输出到cout
options.minimizer_progress_to_stdout = true;
// 优化信息
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
cout<<summary.BriefReport()<<endl;
cout<<"init_x = "<<temp_x<<endl<<"options_x = "<<init_x<<endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required( VERSION 2.8 )
project( ceres )
set( CMAKE_BUILD_TYPE "Release" )
set( CMAKE_CXX_FLAGS "-std=c++11 -O3" )
# 添加cmake模块以使用ceres库
list( APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules )
# 寻找Ceres库并添加它的头文件
find_package( Ceres REQUIRED )
include_directories( ${CERES_INCLUDE_DIRS} )
# OpenCV
# find_package( OpenCV REQUIRED )
# include_directories( ${OpenCV_DIRS} )
add_executable( ceres_1 ceres_p1.cpp )
target_link_libraries( ceres_1 ${CERES_LIBRARIES} )