Pose3SLAMExample_g2o.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* ----------------------------------------------------------------------------
  2. * GTSAM Copyright 2010, Georgia Tech Research Corporation,
  3. * Atlanta, Georgia 30332-0415
  4. * All Rights Reserved
  5. * Authors: Frank Dellaert, et al. (see THANKS for the full author list)
  6. * See LICENSE for the license information
  7. * -------------------------------------------------------------------------- */
  8. /**
  9. * @file Pose3SLAMExample_g2o.cpp
  10. * @brief A 3D Pose SLAM example that reads input from g2o, and initializes the Pose3 using InitializePose3
  11. * Syntax for the script is ./Pose3SLAMExample_g2o input.g2o output.g2o
  12. * @date Aug 25, 2014
  13. * @author Luca Carlone
  14. */
  15. #include <gtsam/slam/dataset.h>
  16. #include <gtsam/slam/BetweenFactor.h>
  17. #include <gtsam/nonlinear/GaussNewtonOptimizer.h>
  18. #include <fstream>
  19. using namespace std;
  20. using namespace gtsam;
  21. int main(const int argc, const char* argv[]) {
  22. // Read graph from file
  23. string g2oFile;
  24. if (argc < 2)
  25. g2oFile = findExampleDataFile("pose3example.txt");
  26. else
  27. g2oFile = argv[1];
  28. NonlinearFactorGraph::shared_ptr graph;
  29. Values::shared_ptr initial;
  30. bool is3D = true;
  31. boost::tie(graph, initial) = readG2o(g2oFile, is3D);
  32. // Add prior on the first key
  33. auto priorModel = noiseModel::Diagonal::Variances(
  34. (Vector(6) << 1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4).finished());
  35. Key firstKey = 0;
  36. for (const auto key_value : *initial) {
  37. std::cout << "Adding prior to g2o file " << std::endl;
  38. firstKey = key_value.key;
  39. graph->addPrior(firstKey, Pose3(), priorModel);
  40. break;
  41. }
  42. std::cout << "Optimizing the factor graph" << std::endl;
  43. GaussNewtonParams params;
  44. params.setVerbosity("TERMINATION"); // show info about stopping conditions
  45. GaussNewtonOptimizer optimizer(*graph, *initial, params);
  46. Values result = optimizer.optimize();
  47. std::cout << "Optimization complete" << std::endl;
  48. std::cout << "initial error=" << graph->error(*initial) << std::endl;
  49. std::cout << "final error=" << graph->error(result) << std::endl;
  50. if (argc < 3) {
  51. result.print("result");
  52. } else {
  53. const string outputFile = argv[2];
  54. std::cout << "Writing results to file: " << outputFile << std::endl;
  55. NonlinearFactorGraph::shared_ptr graphNoKernel;
  56. Values::shared_ptr initial2;
  57. boost::tie(graphNoKernel, initial2) = readG2o(g2oFile);
  58. writeG2o(*graphNoKernel, result, outputFile);
  59. std::cout << "done! " << std::endl;
  60. }
  61. return 0;
  62. }