ORBSLAM3跑tum数据集的轨迹与真实轨迹对齐并输出轨迹文件C++代码
时间: 2023-12-14 16:37:34 浏览: 234
ORBSLAM跑数据集
以下是ORBSLAM3跑TUM数据集时对齐轨迹并输出轨迹文件的C++代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
#include "ORBSLAM3/System.h"
#include "ORBSLAM3/Map.h"
#include "ORBSLAM3/MapPoint.h"
#include "ORBSLAM3/KeyFrame.h"
#include "ORBSLAM3/Converter.h"
using namespace std;
int main(int argc, char** argv)
{
if(argc != 3)
{
cerr << "Usage: ./run_tum path_to_vocabulary path_to_settings" << endl;
return 1;
}
ORBSLAM3::System* pSLAM = new ORBSLAM3::System(argv[1], argv[2], ORBSLAM3::System::MONOCULAR, true);
ifstream fGroundTruth("groundtruth.txt");
if(!fGroundTruth.is_open())
{
cerr << "Failed to open groundtruth.txt" << endl;
return -1;
}
vector<double> groundTruthTimestamps;
vector<Eigen::Matrix4d> groundTruthPoses;
string line;
while(getline(fGroundTruth, line))
{
stringstream ss(line);
double timestamp;
Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();
for(int i=0; i<12; i++)
{
ss >> pose(i/4, i%4);
}
ss >> timestamp;
groundTruthTimestamps.push_back(timestamp);
groundTruthPoses.push_back(pose);
}
fGroundTruth.close();
// Run the SLAM system on each frame
ifstream fAssociation("associate.txt");
if(!fAssociation.is_open())
{
cerr << "Failed to open associate.txt" << endl;
return -1;
}
ofstream fTrajectory("trajectory.txt");
if(!fTrajectory.is_open())
{
cerr << "Failed to open trajectory.txt" << endl;
return -1;
}
fTrajectory << fixed << setprecision(6);
string leftImgFile, rightImgFile, lineGT;
while(getline(fAssociation, line))
{
stringstream ss(line);
ss >> groundTruthTimestamps[0] >> leftImgFile >> groundTruthTimestamps[1] >> rightImgFile;
cv::Mat leftImg = cv::imread(leftImgFile, CV_LOAD_IMAGE_GRAYSCALE);
double timestamp = groundTruthTimestamps[0];
// Pass the image to ORBSLAM3 for tracking
pSLAM->TrackMonocular(leftImg, timestamp);
// Get the current pose estimation from ORBSLAM3
Eigen::Matrix4d poseEstimate = pSLAM->GetCurrentPose();
// Find the corresponding ground truth pose
Eigen::Matrix4d groundTruthPose;
for(int i=0; i<groundTruthTimestamps.size(); i++)
{
if(abs(groundTruthTimestamps[i] - timestamp) < 0.001)
{
groundTruthPose = groundTruthPoses[i];
break;
}
}
// Align the ORBSLAM3 pose estimate to the ground truth pose
Eigen::Matrix4d alignedPoseEstimate = groundTruthPose.inverse() * poseEstimate;
// Write the aligned pose estimate to the output file
Eigen::Quaterniond q(alignedPoseEstimate.block<3,3>(0,0));
Eigen::Vector3d t(alignedPoseEstimate.block<3,1>(0,3));
fTrajectory << timestamp << " " << t.x() << " " << t.y() << " " << t.z() << " " << q.x() << " " << q.y() << " " << q.z() << " " << q.w() << endl;
}
fAssociation.close();
fTrajectory.close();
delete pSLAM;
return 0;
}
```
这个代码的作用是读取TUM数据集的ground truth轨迹和图像,然后使用ORBSLAM3对每一帧图像进行跟踪,并将ORBSLAM3的位姿估计与ground truth对齐,最后输出对齐后的轨迹文件trajectory.txt。你需要将路径path_to_vocabulary和path_to_settings替换为你的ORB-SLAM3词汇文件和设置文件的路径,并将图像和ground truth轨迹文件的路径设置为正确的路径。
阅读全文