準備工作:
eigen、gflags-2.2.2、glog-0.3.5、Ceres solver、cmake
遇到的問題:
編譯選擇X64 debug和release兩個版本,注意,需要分別對gflags、glog、ceres編譯出它們所對應的debug和release版本,否則可能會報錯:
錯誤原因是生成的Ceres生成的config.h文件出錯。
開始編譯
編譯gflas
打開cmake,在source code中選擇準備的gflags,如下:
我最終需要的環境是64位,故在編譯時選擇Visual Studio 15 2017 Win64 。
配置完成後點擊generate,在vs2017中打開,分辨在release和debug兩種模式下生成解決方案。兩種模式下分別成功生成4個。
編譯glog
指定先前生成的gflags的位置,如下:
配置完成後點擊generate,在vs2017中打開,分辨在release和debug兩種模式下生成解決方案。兩種模式下分別成功生成7個。
編譯Ceres-solver
同理,在source code中選擇剛纔下載的ceres-solver,並指定編譯位置,選擇編譯器。 點擊config,這時候需要指定之前所下載的eigen庫,並將EIGENSPARSE選上 。
再次點擊config,指定之前生成的gflags和glog,如下:
再次點擊config,指定CMAKE_BUILD_TYPE,如下:
配置完成後點擊generate,在vs2017中打開,分辨在release和debug兩種模式下生成解決方案。兩種模式下分別成功生成13個。
vs2017使用前提工作
新建文件Ceres,將ceres、gflags、glog、eigen的源碼解壓後放入文件中,並在文件中新建include和lib文件,如下:
將一下目錄拷貝到include文件中:
1、gflagsbuild\include\下的gflags文件夾。
2、glogbuild\下的glog文件夾。
3、ceres\include\下的ceres文件夾。
4、ceres-build\config\ceres\internal文件下的config.h拷貝到ceres裏的internal文件夾中
5、eigen-eigen-c1659a20ca60\下的Eigen文件夾。
注:gflagsbuild、glogbuild是編譯後的目錄,另外兩個是解壓縮後的目錄。
如下:
將以下內容拷貝到lib目錄中:
1、gflagsbuild\lib\Debug下的gflags_nothreads_static.lib和gflags_static.lib。
2、glogbuild\Debug下的glog.lib。
3、ceresbuild\lib\Debug下的ceres-debug.lib。
如下:
然後新建vs控制檯工程,打開項目-項目屬性-VC/VC++目錄,將上面的include和lib路徑添加到包含目錄和庫目錄中。
打開項目-項目屬性-C/C+±常規,將上面的include路徑添加到附加包含目錄中。
打開項目-項目屬性-連接器-輸入,編輯附加依賴項,將之前lib目錄下的鏈接庫名添加到裏面,最後點擊確定,應用,即可。
示例代碼如下:
#include <ceres\ceres.h>
#include <glog\logging.h>
using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solver;
//using ceres::Solve;
struct CostFunctor {
template <typename T>
bool operator()(const T* const x, T* residual) const {
residual[0] = T(10.0) - x[0];
return true;
}
};
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
// The variable to solve for with its initial value.
double initial_x = 5.0;
double x = initial_x;
// Build the problem.
Problem problem;
// Set up the only cost function (also known as residual). This uses
// auto-differentiation to obtain the derivative (jacobian).
CostFunction* cost_function =
new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
problem.AddResidualBlock(cost_function, NULL, &x);
// Run the solver!
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";
return 0;
}
運行結果如下: