ORBSLAM3跑tum数据集的轨迹与真实轨迹对齐并输出对齐后轨迹文件C++代码
时间: 2023-12-14 08:37:31 浏览: 172
以下是使用 ORBSLAM3 跑 TUM 数据集并输出对齐后轨迹文件的 C++ 代码示例:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
#include <opencv2/core/core.hpp>
#include "System.h"
using namespace std;
int main(int argc, char **argv)
{
if(argc != 4)
{
cerr << endl << "Usage: ./mono_tum path_to_vocabulary path_to_settings path_to_dataset" << endl;
return 1;
}
ORB_SLAM3::System SLAM(argv[1],argv[2],ORB_SLAM3::System::MONOCULAR,true);
ifstream fGroundTruth;
fGroundTruth.open(argv[3] + string("/groundtruth.txt"));
if(!fGroundTruth.is_open())
{
cerr << endl << "Failed to open file: " << argv[3] + string("/groundtruth.txt") << endl;
return 1;
}
ofstream fTrajectory;
fTrajectory.open("trajectory.txt");
if(!fTrajectory.is_open())
{
cerr << endl << "Failed to open file: trajectory.txt" << endl;
return 1;
}
string sLine;
int nLineNum = 0;
while(getline(fGroundTruth,sLine))
{
if(sLine.empty() || sLine[0] == '#')
continue;
nLineNum++;
double t;
float tx, ty, tz, qx, qy, qz, qw;
stringstream ss;
ss << sLine;
ss >> t >> tx >> ty >> tz >> qx >> qy >> qz >> qw;
cv::Mat Tcw = SLAM.TrackMonocular(cv::Mat(),cv::Mat(),t);
if(!Tcw.empty())
{
cv::Mat Rwc = Tcw.rowRange(0,3).colRange(0,3).t();
cv::Mat twc = -Rwc*Tcw.rowRange(0,3).col(3);
float x = twc.at<float>(0);
float y = twc.at<float>(1);
float z = twc.at<float>(2);
float roll, pitch, yaw;
ORB_SLAM3::Converter::QuaternionToEuler(qw,qx,qy,qz,roll,pitch,yaw);
float scale = 1.0f;
if(nLineNum > 1)
{
getline(fGroundTruth,sLine);
double tPrev;
float txPrev, tyPrev, tzPrev, qxPrev, qyPrev, qzPrev, qwPrev;
stringstream ssPrev;
ssPrev << sLine;
ssPrev >> tPrev >> txPrev >> tyPrev >> tzPrev >> qxPrev >> qyPrev >> qzPrev >> qwPrev;
cv::Mat Twc = cv::Mat::eye(4,4,CV_32F);
ORB_SLAM3::Converter::QuaternionToMat(qxPrev,qyPrev,qzPrev,qwPrev,Twc.rowRange(0,3).colRange(0,3));
Twc.at<float>(0,3) = txPrev;
Twc.at<float>(1,3) = tyPrev;
Twc.at<float>(2,3) = tzPrev;
cv::Mat Ow = Twc.rowRange(0,3).col(3);
cv::Mat OwPrev = cv::Mat(3,1,CV_32F);
OwPrev.at<float>(0) = txPrev;
OwPrev.at<float>(1) = tyPrev;
OwPrev.at<float>(2) = tzPrev;
cv::Mat v = Ow - OwPrev;
scale = cv::norm(v);
}
fTrajectory << fixed << setprecision(6) << t << " "
<< x << " " << y << " " << z << " "
<< roll << " " << pitch << " " << yaw << " "
<< scale << endl;
}
}
fGroundTruth.close();
fTrajectory.close();
SLAM.Shutdown();
return 0;
}
```
注意事项:
1. 代码中的 `path_to_vocabulary` 和 `path_to_settings` 分别表示 ORB_SLAM3 的词汇文件和配置文件路径,需要根据实际情况进行修改。
2. 代码中的 `path_to_dataset` 表示 TUM 数据集所在的文件夹路径,需要根据实际情况进行修改。
3. 输出的对齐轨迹文件为 `trajectory.txt`,每行数据包括时间戳、位置坐标、欧拉角和尺度因子,用空格分隔。
4. 代码中使用了 Ground Truth 数据进行轨迹对齐,需要保证 TUM 数据集中的 `groundtruth.txt` 文件是存在并且格式正确的。如果没有 Ground Truth 数据,可以使用其它方法进行轨迹对齐。
希望对你有帮助!
阅读全文