tracking线程

Tracking线程的主要工作是从图像中提取ORB特征,根据上一帧进行姿态估计或者进行通过全局重定位初始化位姿,然后跟踪已经重建的局部地图,优化位姿,再根据一些规则确定新的关键帧,将这些关键帧送给localmapping线程

1. 基本流程

首先从主线程system中的GrabImageMonocular()函数开始,进行图像的预处理和Frame的构造,Frame构造完成后真正进入Tracking。

↓↓↓主要看下面这张图↓↓↓

↑↑↑主要看上面这张图↑↑↑

2. 各部分详解

Tracking构造函数

Tracking线程在构造时主要是读取了一些参数,包括:

  1. 相机参数:
    相机内参矩阵、
    畸变校正矩阵、
    双目摄像头基线、
    相机的帧数、
    颜色通道、
    深度相机深度与距离的转化因子
  2. ORB特征提取相关参数:
    每一帧提取的特征点数、
    图像建立金字塔时的变化尺度、
    尺度金字塔的层数、
    提取fast特征点的默认阈值、
    提取fast特征点的最小阈值(如果默认阈值提取不出足够fast特征点,则使用最小阈值)

具体代码如下

  1. Tracking::Tracking(System *pSys, ORBVocabulary* pVoc, FrameDrawer *pFrameDrawer, MapDrawer *pMapDrawer, Map *pMap, KeyFrameDatabase* pKFDB, const string &strSettingPath, const int sensor):
  2. mState(NO_IMAGES_YET), mSensor(sensor), mbOnlyTracking(false), mbVO(false), mpORBVocabulary(pVoc),
  3. mpKeyFrameDB(pKFDB), mpInitializer(static_cast<Initializer*>(NULL)), mpSystem(pSys), mpViewer(NULL),
  4. mpFrameDrawer(pFrameDrawer), mpMapDrawer(pMapDrawer), mpMap(pMap), mnLastRelocFrameId(0)
  5. {
  6. //读取相机内参数据
  7. // Load camera parameters from settings file
  8. cv::FileStorage fSettings(strSettingPath, cv::FileStorage::READ);//opencv的FileStorage类,用于实现数据的存取等操作
  9. float fx = fSettings["Camera.fx"];
  10. float fy = fSettings["Camera.fy"];
  11. float cx = fSettings["Camera.cx"];
  12. float cy = fSettings["Camera.cy"];
  13. //生成相机内参矩阵
  14. // |fx 0 cx|
  15. // K = |0 fy cy|
  16. // |0 0 1 |
  17. cv::Mat K = cv::Mat::eye(3,3,CV_32F);
  18. K.at<float>(0,0) = fx;
  19. K.at<float>(1,1) = fy;
  20. K.at<float>(0,2) = cx;
  21. K.at<float>(1,2) = cy;
  22. K.copyTo(mK);//把临时变量K中的数据copy到tracking类的成员变量中
  23. // 图像畸变矫正系数(畸变部分可以参考十四讲的5.1.2)
  24. // 通常只有鱼眼相机才进行校正,mono_kitti中并没有进行校正
  25. // [k1 k2 p1 p2 k3]
  26. cv::Mat DistCoef(4,1,CV_32F);
  27. DistCoef.at<float>(0) = fSettings["Camera.k1"];
  28. DistCoef.at<float>(1) = fSettings["Camera.k2"];
  29. DistCoef.at<float>(2) = fSettings["Camera.p1"];
  30. DistCoef.at<float>(3) = fSettings["Camera.p2"];
  31. const float k3 = fSettings["Camera.k3"];
  32. if(k3!=0)
  33. {
  34. DistCoef.resize(5);
  35. DistCoef.at<float>(4) = k3;
  36. }
  37. DistCoef.copyTo(mDistCoef);//把临时变量DistCoef中的数据copy到tracking类的成员变量中
  38. // 双目摄像头baseline * fx(双目相机能观测的最远距离)
  39. mbf = fSettings["Camera.bf"];
  40. //相机的帧数
  41. float fps = fSettings["Camera.fps"];
  42. if(fps==0)
  43. fps=30;
  44. // Max/Min Frames to insert keyframes and to check relocalisation
  45. //(用在关键帧插入和重定位时的阈值)
  46. mMinFrames = 0;
  47. mMaxFrames = fps;
  48. cout << endl << "Camera Parameters: " << endl;
  49. cout << "- fx: " << fx << endl;
  50. cout << "- fy: " << fy << endl;
  51. cout << "- cx: " << cx << endl;
  52. cout << "- cy: " << cy << endl;
  53. cout << "- k1: " << DistCoef.at<float>(0) << endl;
  54. cout << "- k2: " << DistCoef.at<float>(1) << endl;
  55. if(DistCoef.rows==5)
  56. cout << "- k3: " << DistCoef.at<float>(4) << endl;
  57. cout << "- p1: " << DistCoef.at<float>(2) << endl;
  58. cout << "- p2: " << DistCoef.at<float>(3) << endl;
  59. cout << "- fps: " << fps << endl;
  60. // 1:RGB 0:BGR
  61. int nRGB = fSettings["Camera.RGB"];
  62. mbRGB = nRGB;
  63. if(mbRGB)
  64. cout << "- color order: RGB (ignored if grayscale)" << endl;
  65. else
  66. cout << "- color order: BGR (ignored if grayscale)" << endl;
  67. // Load ORB parameters
  68. // 每一帧提取的特征点数 1000
  69. int nFeatures = fSettings["ORBextractor.nFeatures"];
  70. // 图像建立金字塔时的变化尺度 1.2
  71. float fScaleFactor = fSettings["ORBextractor.scaleFactor"];
  72. // 尺度金字塔的层数 8
  73. int nLevels = fSettings["ORBextractor.nLevels"];
  74. // 提取fast特征点的默认阈值 20
  75. int fIniThFAST = fSettings["ORBextractor.iniThFAST"];
  76. // 如果默认阈值提取不出足够fast特征点,则使用最小阈值 8
  77. int fMinThFAST = fSettings["ORBextractor.minThFAST"];
  78. // tracking过程都会用到mpORBextractorLeft作为特征点提取器
  79. mpORBextractorLeft = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  80. // 如果是双目,tracking过程中还会用用到mpORBextractorRight作为右目特征点提取器
  81. if(sensor==System::STEREO)
  82. mpORBextractorRight = new ORBextractor(nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  83. // 在单目初始化的时候,会用mpIniORBextractor来作为特征点提取器
  84. //单目初始化时要求的特征点数是平时的2倍
  85. if(sensor==System::MONOCULAR)
  86. mpIniORBextractor = new ORBextractor(2*nFeatures,fScaleFactor,nLevels,fIniThFAST,fMinThFAST);
  87. cout << endl << "ORB Extractor Parameters: " << endl;
  88. cout << "- Number of Features: " << nFeatures << endl;
  89. cout << "- Scale Levels: " << nLevels << endl;
  90. cout << "- Scale Factor: " << fScaleFactor << endl;
  91. cout << "- Initial Fast Threshold: " << fIniThFAST << endl;
  92. cout << "- Minimum Fast Threshold: " << fMinThFAST << endl;
  93. if(sensor==System::STEREO || sensor==System::RGBD)
  94. {
  95. // 判断一个3D点远/近的阈值
  96. //双目和深度相机在建图时会剔除比较远的点(这里不是很确定)
  97. mThDepth = mbf*(float)fSettings["ThDepth"]/fx;
  98. cout << endl << "Depth Threshold (Close/Far Points): " << mThDepth << endl;
  99. }
  100. if(sensor==System::RGBD)
  101. {
  102. // 深度相机disparity转化为depth时的因子,是相机本身的参数
  103. mDepthMapFactor = fSettings["DepthMapFactor"];
  104. if(fabs(mDepthMapFactor)<1e-5)
  105. mDepthMapFactor=1;
  106. else
  107. mDepthMapFactor = 1.0f/mDepthMapFactor;
  108. }
  109. }

入口——GrabImageMonocular()

这个函数主要完成以下几个功能
1、接受RGB、BGR或RGBA、BGRA图像(A可以理解为透明度)
2、将图像转为灰度图(mImGray)
3、把输入的图像构造成当前帧mCurrentFrame
4、进入Track()函数进行tracking过程
5、输出世界坐标系到该帧相机坐标系的变换矩阵Tcw
具体代码如下

  1. cv::Mat Tracking::GrabImageMonocular(const cv::Mat &im, const double &timestamp)
  2. {
  3. mImGray = im;
  4. // 步骤1:将RGB或RGBA图像转为灰度图像
  5. if(mImGray.channels()==3)
  6. {
  7. if(mbRGB)
  8. cvtColor(mImGray,mImGray,CV_RGB2GRAY);
  9. else
  10. cvtColor(mImGray,mImGray,CV_BGR2GRAY);
  11. }
  12. else if(mImGray.channels()==4)//在三通道的基础上增加了深度
  13. {
  14. if(mbRGB)
  15. cvtColor(mImGray,mImGray,CV_RGBA2GRAY);
  16. else
  17. cvtColor(mImGray,mImGray,CV_BGRA2GRAY);
  18. }
  19. // 步骤2:使用生成的灰度图构造Frame
  20. if(mState==NOT_INITIALIZED || mState==NO_IMAGES_YET)// 没有成功初始化的前一个状态就是NO_IMAGES_YET,这个状态只会在刚开机时才存在
  21. mCurrentFrame = Frame(mImGray,timestamp,mpIniORBextractor,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth);
  22. else
  23. mCurrentFrame = Frame(mImGray,timestamp,mpORBextractorLeft,mpORBVocabulary,mK,mDistCoef,mbf,mThDepth);
  24. // 步骤3:跟踪
  25. Track();
  26. //输出世界坐标系到该帧相机坐标系的变换矩阵Tcw
  27. return mCurrentFrame.mTcw.clone();
  28. }

其中Frame的构造函数如下

  1. Frame::Frame(const cv::Mat &imGray, const double &timeStamp, ORBextractor* extractor,ORBVocabulary* voc, cv::Mat &K, cv::Mat &distCoef, const float &bf, const float &thDepth)
  2. :mpORBvocabulary(voc),mpORBextractorLeft(extractor),mpORBextractorRight(static_cast<ORBextractor*>(NULL)),
  3. mTimeStamp(timeStamp), mK(K.clone()),mDistCoef(distCoef.clone()), mbf(bf), mThDepth(thDepth)
  4. {
  5. // Frame ID
  6. //记录这是第几帧
  7. mnId=nNextId++;
  8. // Scale Level Info
  9. //1.获取特征提取器相关参数
  10. mnScaleLevels = mpORBextractorLeft->GetLevels();
  11. mfScaleFactor = mpORBextractorLeft->GetScaleFactor();
  12. mfLogScaleFactor = log(mfScaleFactor);
  13. mvScaleFactors = mpORBextractorLeft->GetScaleFactors();
  14. mvInvScaleFactors = mpORBextractorLeft->GetInverseScaleFactors();
  15. mvLevelSigma2 = mpORBextractorLeft->GetScaleSigmaSquares();
  16. mvInvLevelSigma2 = mpORBextractorLeft->GetInverseScaleSigmaSquares();
  17. // ORB extraction
  18. // 2.ORB特征提取,得到特征点mvKeys和描述子mDescriptors
  19. ExtractORB(0,imGray);
  20. //提取出来的特征点的数目
  21. N = mvKeys.size();
  22. if(mvKeys.empty())
  23. return;
  24. // 调用OpenCV的矫正函数矫正orb提取的特征点(去畸变)
  25. UndistortKeyPoints();
  26. // Set no stereo information
  27. //单目情况下没有深度信息,mvuRight、mvDepth值都设置为-1
  28. mvuRight = vector<float>(N,-1);
  29. mvDepth = vector<float>(N,-1);
  30. //保存mappoint的vector向量
  31. mvpMapPoints = vector<MapPoint*>(N,static_cast<MapPoint*>(NULL));//static_cast<type>(B)把变量B转换为type类型的变量
  32. //标识异常关联的标志,值都设置为false
  33. mvbOutlier = vector<bool>(N,false);
  34. // This is done only for the first Frame (or after a change in the calibration)
  35. //4.对第一帧图像的灰度图计算图像边界
  36. //mbInitialComputations初始化的值为true,进行转换后值变为false,则后边进来的帧都不会进行图像边界计算的操作
  37. //转换后图像的边界信息会发生变化,这边先对帧计算出边界信息
  38. if(mbInitialComputations)
  39. {
  40. //计算图像边界
  41. ComputeImageBounds(imGray);
  42. /**
  43. * 此处需要重点理解:FRAME_GRID_COLS=64,FRAME_GRID_ROWS=48
  44. * static_cast<float>(FRAME_GRID_COLS)/static_cast<float>(mnMaxX-mnMinX)相当于把64平均分配到图像宽度中的每一个像素上,
  45. * 计算出每一个像素占用64的百分之多少。
  46. * static_cast<float>(FRAME_GRID_ROWS)/static_cast<float>(mnMaxY-mnMinY)相当于把48平均分配到图像高度中每一个像素上,
  47. * 计算出每一个像素占用48的百分之多少。
  48. * 后边使用关键点所在的像素坐标和这个值相乘,也就得到了在64*48的网格中关键点所在的坐标
  49. */
  50. mfGridElementWidthInv=static_cast<float>(FRAME_GRID_COLS)/static_cast<float>(mnMaxX-mnMinX);
  51. mfGridElementHeightInv=static_cast<float>(FRAME_GRID_ROWS)/static_cast<float>(mnMaxY-mnMinY);
  52. //从内参矩阵中获取相机内参各个参数
  53. fx = K.at<float>(0,0);
  54. fy = K.at<float>(1,1);
  55. cx = K.at<float>(0,2);
  56. cy = K.at<float>(1,2);
  57. invfx = 1.0f/fx;
  58. invfy = 1.0f/fy;
  59. //只有第一帧进行这些计算,后面所有的帧都不计算
  60. mbInitialComputations=false;
  61. }
  62. mb = mbf/fx;
  63. // 把每一帧分割成48x64个网格
  64. // 根据关键点的畸变矫正后的位置分在不同的网格里面.
  65. //5.根据关键点的位置将其分布在不同网格中
  66. AssignFeaturesToGrid();
  67. }

Tracking的“主函数”——Track()

这是tracking线程的主流程,包含了tracking线程中的各个部分及它们的状态判断,并在最后将轨迹记录下来。
注:其中的仅跟踪模式是用户在图形界面手动选择的,在这个模式下只进行跟踪和定位,不进行关键帧和地图点的更新

  1. {
  2. // track包含两部分:估计运动、跟踪局部地图
  3. //mState 共有四个状态
  4. //NO_IMAGES_YET(没有成功初始化的前一个状态就是NO_IMAGES_YET,这个状态只会在刚开机或复位时才存在)
  5. //NOT_INITIALIZED(在第一个状态之后就进入这个状态)
  6. //OK(正常状态)
  7. //LOST(跟丢了)
  8. if(mState==NO_IMAGES_YET)
  9. {
  10. mState = NOT_INITIALIZED;
  11. }
  12. // mLastProcessedState存储了Tracking最新的状态,用于FrameDrawer中的绘制
  13. mLastProcessedState=mState;
  14. // Get Map Mutex -> Map cannot be changed
  15. unique_lock<mutex> lock(mpMap->mMutexMapUpdate);
  16. // 步骤1:如果未初始化进行初始化
  17. if(mState==NOT_INITIALIZED)
  18. {
  19. if(mSensor==System::STEREO || mSensor==System::RGBD)
  20. StereoInitialization();
  21. else
  22. MonocularInitialization();
  23. mpFrameDrawer->Update(this);
  24. if(mState!=OK)
  25. return;
  26. }
  27. else// 步骤2:跟踪(正常运行状态,已经初始化好了)
  28. {
  29. // System is initialized. Track Frame.
  30. // bOK为临时变量,用于表示每个函数是否执行成功
  31. bool bOK;
  32. // Initial camera pose estimation using motion model or relocalization (if tracking is lost)
  33. // 在viewer中有个开关menuLocalizationMode,由它控制是否ActivateLocalizationMode,并最终管控mbOnlyTracking
  34. // mbOnlyTracking等于false表示正常VO模式(有地图更新),mbOnlyTracking等于true表示用户手动选择定位模式
  35. if(!mbOnlyTracking)
  36. {
  37. // Local Mapping is activated. This is the normal behaviour, unless
  38. // you explicitly activate the "only tracking" mode.
  39. // 正常初始化成功
  40. if(mState==OK)
  41. {
  42. // Local Mapping might have changed some MapPoints tracked in last frame
  43. // 检查并更新上一帧被替换的MapPoints
  44. // 更新Fuse函数和SearchAndFuse函数替换的MapPoints
  45. CheckReplacedInLastFrame();
  46. //TODO:当前帧和上一帧匹配并优化pose
  47. // 步骤2.1:选择跟踪参考帧还是上一帧(恒速模型)
  48. // 若运动速度为0或刚完成重定位,就用跟踪参考帧的模式
  49. // mCurrentFrame.mnId<mnLastRelocFrameId+2这个判断不应该有(Dada持怀疑态度)
  50. // 应该只要mVelocity不为空,就优先选择TrackWithMotionModel
  51. // mnLastRelocFrameId上一次重定位的那一帧
  52. if(mVelocity.empty() || mCurrentFrame.mnId<mnLastRelocFrameId+2)
  53. {
  54. //TrackReferenceKeyFrame是跟踪参考帧,不能根据固定运动速度模型预测当前帧的位姿态,通过bow加速匹配(SearchByBow)
  55. // 将上一帧的位姿作为当前帧的初始位姿
  56. // 通过BoW的方式在参考帧中找当前帧特征点的匹配点
  57. // 优化每个特征点都对应3D点重投影误差即可得到当前位姿
  58. bOK = TrackReferenceKeyFrame();
  59. }
  60. //正常情况下采用恒速模型,也就是跟踪上一帧的模式
  61. else
  62. {
  63. // 根据恒速模型设定当前帧的初始位姿
  64. // 通过投影的方式在参考帧中找当前帧特征点的匹配点
  65. // 优化每个特征点所对应3D点的投影误差即可得到位姿
  66. bOK = TrackWithMotionModel();
  67. //如果恒速模型跟踪失败了就采用跟踪参考帧的方式
  68. if(!bOK)
  69. bOK = TrackReferenceKeyFrame();
  70. }
  71. }
  72. //重定位
  73. else
  74. {
  75. // BOW搜索,PnP求解位姿
  76. bOK = Relocalization();
  77. }
  78. }
  79. else//用户选择只定位模式,不插入关键帧,局部地图不工作
  80. {
  81. // Localization Mode: Local Mapping is deactivated
  82. // 只进行跟踪tracking,局部地图不工作
  83. // 步骤2.1:跟踪上一帧或者参考帧或者重定位
  84. // tracking跟丢了
  85. if(mState==LOST)
  86. {
  87. //重定位
  88. bOK = Relocalization();
  89. }
  90. else
  91. {
  92. // mbVO是mbOnlyTracking为true时的才有的一个变量
  93. // mbVO为false表示此帧匹配了很多的MapPoints,跟踪很正常,
  94. // mbVO为true表明此帧匹配了很少的MapPoints,少于10个,要跪的节奏
  95. if(!mbVO)//跟踪正常
  96. {
  97. // In last frame we tracked enough MapPoints in the map
  98. // mbVO为false则表明此帧匹配了很多的mappoints点,非常好
  99. if(!mVelocity.empty())
  100. {
  101. bOK = TrackWithMotionModel();
  102. // 这个地方是不是应该加上:
  103. // if(!bOK)
  104. // bOK = TrackReferenceKeyFrame();
  105. }
  106. else
  107. {
  108. bOK = TrackReferenceKeyFrame();
  109. }
  110. }
  111. //mbVO为true, 跟踪不正常,则表明此帧匹配了很少的map point点,少于10个,要跪的节奏,既做跟踪又做定位
  112. //下面这一整段就是在跟踪不正常的时候采用恒速模型和重定位两种方式进行跟踪,但更相信重定位的
  113. else
  114. {
  115. // In last frame we tracked mainly "visual odometry" points.
  116. // We compute two camera poses, one from motion model and one doing relocalization.
  117. // If relocalization is sucessfull we choose that solution, otherwise we retain
  118. // the "visual odometry" solution.
  119. //在最后一帧,我们跟踪了主要的视觉里程计点
  120. //我们计算两个相机位姿,一个来自运动模型一个做重定位。如果重定位成功我们就选择这个思路,否则我们继续使用视觉里程计思路
  121. bool bOKMM = false;
  122. bool bOKReloc = false;
  123. vector<MapPoint*> vpMPsMM;
  124. vector<bool> vbOutMM;
  125. cv::Mat TcwMM;
  126. //有速度,采用恒速模型跟踪
  127. if(!mVelocity.empty())
  128. {
  129. bOKMM = TrackWithMotionModel();
  130. // 这三行没啥用?
  131. vpMPsMM = mCurrentFrame.mvpMapPoints;
  132. vbOutMM = mCurrentFrame.mvbOutlier;
  133. TcwMM = mCurrentFrame.mTcw.clone();
  134. }
  135. //重定位
  136. bOKReloc = Relocalization();
  137. // 重定位没有成功,但是如果跟踪成功
  138. if(bOKMM && !bOKReloc)
  139. {
  140. // 这三行没啥用?
  141. mCurrentFrame.SetPose(TcwMM);
  142. mCurrentFrame.mvpMapPoints = vpMPsMM;
  143. mCurrentFrame.mvbOutlier = vbOutMM;
  144. if(mbVO)
  145. {
  146. // 这段代码是不是有点多余?应该放到TrackLocalMap函数中统一做
  147. // 更新当前帧的MapPoints被观测程度
  148. for(int i =0; i<mCurrentFrame.N; i++)
  149. {
  150. if(mCurrentFrame.mvpMapPoints[i] && !mCurrentFrame.mvbOutlier[i])
  151. {
  152. mCurrentFrame.mvpMapPoints[i]->IncreaseFound();
  153. }
  154. }
  155. }
  156. }
  157. else if(bOKReloc)// 只要重定位成功整个跟踪过程正常进行(定位与跟踪,更相信重定位)
  158. {
  159. mbVO = false;
  160. }
  161. bOK = bOKReloc || bOKMM;
  162. }
  163. }
  164. }
  165. // 将最新的关键帧作为当前帧的参考帧reference frame
  166. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  167. // If we have an initial estimation of the camera pose and matching. Track the local map.
  168. // 步骤2.2:在帧间匹配得到初始的姿态后,现在对local map进行跟踪得到更多的匹配,并优化当前位姿
  169. // local map:当前帧、当前帧的MapPoints、与当前帧有共视关系的所有关键帧及它们的mappoints
  170. // 在步骤2.1中主要是两两跟踪(恒速模型跟踪上一帧、跟踪参考帧),这里搜索局部关键帧后搜集所有局部MapPoints,
  171. // 然后将局部地图中的MapPoints和当前帧进行投影匹配,得到更多匹配的MapPoints后进行Pose优化
  172. //TODO:当前帧和局部mappoint匹配优化pose
  173. if(!mbOnlyTracking)
  174. {
  175. if(bOK)
  176. bOK = TrackLocalMap();
  177. }
  178. else//用户选择了仅定位模式
  179. {
  180. // mbVO true means that there are few matches to MapPoints in the map. We cannot retrieve
  181. // a local map and therefore we do not perform TrackLocalMap(). Once the system relocalizes
  182. // the camera we will use the local map again.
  183. // 重定位成功
  184. if(bOK && !mbVO)//正常状态,没有跟丢
  185. bOK = TrackLocalMap();
  186. }
  187. if(bOK)
  188. mState = OK;
  189. else
  190. mState=LOST;
  191. // Update drawer
  192. mpFrameDrawer->Update(this);
  193. // If tracking were good, check if we insert a keyframe
  194. if(bOK)
  195. {
  196. // Update motion model
  197. if(!mLastFrame.mTcw.empty())
  198. {
  199. // 步骤2.3:更新恒速运动模型TrackWithMotionModel中的mVelocity
  200. cv::Mat LastTwc = cv::Mat::eye(4,4,CV_32F);
  201. mLastFrame.GetRotationInverse().copyTo(LastTwc.rowRange(0,3).colRange(0,3));//注意这里colRange(0,3)指的是从第0列开始,往右数3列,也就是0,1,2列
  202. mLastFrame.GetCameraCenter().copyTo(LastTwc.rowRange(0,3).col(3));
  203. mVelocity = mCurrentFrame.mTcw*LastTwc; // 为什么这个是速度呢,因为这个乘以上一帧的位姿Tcw就是当前帧的位姿Tcw
  204. }
  205. else
  206. mVelocity = cv::Mat();
  207. //在用户显示窗口中画当前帧的相机位姿
  208. mpMapDrawer->SetCurrentCameraPose(mCurrentFrame.mTcw);
  209. // Clean VO matches
  210. // 步骤2.4:在当前帧中清除UpdateLastFrame中为当前帧临时添加的MapPoints(只有深度和双目相机有)
  211. for(int i=0; i<mCurrentFrame.N; i++)
  212. {
  213. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  214. if(pMP)
  215. //如果该MapPoint没有被其他帧观察到(就是前面说的临时mappoints),则将该MapPoint去掉
  216. if(pMP->Observations()<1)
  217. {
  218. mCurrentFrame.mvbOutlier[i] = false;
  219. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  220. }
  221. }
  222. // Delete temporal MapPoints
  223. // 步骤2.5:清除临时的MapPoints,这些MapPoints在TrackWithMotionModel的UpdateLastFrame函数里生成(仅双目和rgbd)
  224. // 步骤2.4中只是在当前帧中将这些MapPoints剔除,这里从MapPoints数据库中删除
  225. // 这里生成的仅仅是为了提高双目或rgbd摄像头的帧间跟踪效果,用完以后就扔了,没有添加到地图中
  226. for(list<MapPoint*>::iterator lit = mlpTemporalPoints.begin(), lend = mlpTemporalPoints.end(); lit!=lend; lit++)
  227. {
  228. MapPoint* pMP = *lit;
  229. delete pMP;
  230. }
  231. // 这里不仅仅是清除mlpTemporalPoints,通过上面delete pMP还删除了指针指向的MapPoint
  232. mlpTemporalPoints.clear();
  233. // Check if we need to insert a new keyframe
  234. // 步骤2.6:检测并插入关键帧,对于双目会产生新的MapPoints
  235. if(NeedNewKeyFrame())
  236. CreateNewKeyFrame();
  237. // We allow points with high innovation (considererd outliers by the Huber Function)
  238. // pass to the new keyframe, so that bundle adjustment will finally decide
  239. // if they are outliers or not. We don't want next frame to estimate its position
  240. // with those points so we discard them in the frame.
  241. // 删除那些在bundle adjustment中检测为outlier的3D mappoint点
  242. for(int i=0; i<mCurrentFrame.N;i++)
  243. {
  244. if(mCurrentFrame.mvpMapPoints[i] && mCurrentFrame.mvbOutlier[i])
  245. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  246. }
  247. }
  248. // Reset if the camera get lost soon after initialization
  249. // 跟踪失败,并且Relocalization也没有搞定,只能重新Reset
  250. if(mState==LOST)
  251. {
  252. if(mpMap->KeyFramesInMap()<=5)//地图中的关键帧少于5个,说明初始化不久
  253. {
  254. cout << "Track lost soon after initialisation, reseting..." << endl;
  255. mpSystem->Reset();
  256. return;
  257. }
  258. }
  259. if(!mCurrentFrame.mpReferenceKF)
  260. mCurrentFrame.mpReferenceKF = mpReferenceKF;
  261. //Tracking完成的时候,记录当前帧为上一帧
  262. mLastFrame = Frame(mCurrentFrame);
  263. }
  264. //TODO: 至此,tracking结束

单目相机初始化——MonocularInitialization()

由于单目相机没有深度信息,所以要通过初始化确定一个初始的地图信息和初始位姿。
初始化一般使用两帧即可,但是需要有足够多的特征点以及足够多的匹配对。
找到了合适的两帧图像后,就可以利用RANSAC迭代来求解基础矩阵F和单应矩阵H。它们对应两种不同的通过几组2d点对求解位姿的方法。其中单应矩阵求解的方法要求地图点分布在3维空间中的一个平面上。(这部分是对极几何知识,参考十四讲的7.3)
那么我们选择哪一种方法来求解呢:对于两种方法求解出的位姿,分别计算重投影误差,得到两个模型的分数,通过比较分数来让ORB-SLAM系统自动选择使用哪个模型。
如果初始化成功,就将第一帧的位姿设为原点,第二帧的位姿就是根据F或H计算出的位姿变换矩阵。同时,利用全局BA对位姿和地图点进行优化。并将第一帧作为关键帧送给localmapping。
具体代码如下

  1. /**
  2. * @brief 单目的地图初始化
  3. *
  4. * 并行地计算基础矩阵和单应性矩阵,选取其中一个模型,恢复出最开始两帧之间的相对姿态以及点云
  5. * 得到初始两帧的匹配、相对运动、初始MapPoints
  6. */
  7. /**
  8. * 单目相机初始化函数
  9. * 功能:创建初始化器,并对前两个关键点数大于100的帧进行特征点匹配,根据匹配结果计算出当前帧的变换矩阵并在窗口中显示
  10. * 1. 第一次进入该方法,如果当前帧关键点数>100,将当前帧保存为初始帧和最近的一帧,并创建一个初始化器;
  11. * 2. 第二次进入该方法的时候,已经有初始化器了,如果当前帧中的关键点数>100,利用ORB匹配器,对当前帧和初始帧进行匹配,匹配关键点数小于100时失败;
  12. * 3. 利用匹配的关键点信息进行单应矩阵和基础矩阵的计算,进而计算出相机位姿的旋转矩阵和平移矩阵;
  13. * 4. 进行三角化判断,删除不能三角化的无用特征关键点;
  14. * 5. 由旋转矩阵和平移矩阵构造变换矩阵;
  15. * 6. 将三角化得到的3D点包装成MapPoints,在地图中显示;
  16. */
  17. void Tracking::MonocularInitialization()
  18. {
  19. // 如果单目初始器还没有被创建,则创建单目初始器
  20. if(!mpInitializer)
  21. {
  22. // Set Reference Frame
  23. // 单目初始帧提取的特征点数必须大于100,否则放弃该帧图像
  24. if(mCurrentFrame.mvKeys.size()>100)
  25. {
  26. // 步骤1:把当前帧作为初始化的第一帧,初始化需要两帧
  27. mInitialFrame = Frame(mCurrentFrame);
  28. // 把当前帧作为最近的一帧
  29. mLastFrame = Frame(mCurrentFrame);
  30. // mvbPrevMatched的大小代表提取出的特征点的个数,最大的情况就是所有特征点都被跟踪上
  31. mvbPrevMatched.resize(mCurrentFrame.mvKeysUn.size());
  32. //把特征点的坐标存到mvbPrevMatched中,用于下一帧到来时匹配
  33. for(size_t i=0; i<mCurrentFrame.mvKeysUn.size(); i++)
  34. mvbPrevMatched[i]=mCurrentFrame.mvKeysUn[i].pt;
  35. // 这两句是多余的,因为在上上面这个if条件下肯定不会有这种情况
  36. if(mpInitializer)
  37. delete mpInitializer;
  38. // 由当前帧构造初始器 1.0是参考误差,200是RANSAC迭代次数
  39. mpInitializer = new Initializer(mCurrentFrame,1.0,200);
  40. //mvIniMatches中所有的元素值设置为-1
  41. // mvIniMatches用在第二帧来的时候,存储了初始帧和第二帧之间匹配的特征点
  42. fill(mvIniMatches.begin(),mvIniMatches.end(),-1);
  43. return;
  44. }
  45. }
  46. //如果是第二次进入(这个时候初始化器已经创建好了)
  47. else
  48. {
  49. // Try to initialize
  50. // 步骤2:如果当前帧特征点数大于100,则得到用于单目初始化的第二帧
  51. // 如果当前帧特征点太少,重新构造初始器
  52. // 因此只有连续两帧的特征点个数都大于100时,才能继续进行初始化过程
  53. if((int)mCurrentFrame.mvKeys.size()<=100)
  54. {
  55. delete mpInitializer;
  56. mpInitializer = static_cast<Initializer*>(NULL);
  57. fill(mvIniMatches.begin(),mvIniMatches.end(),-1);
  58. return;
  59. }
  60. // Find correspondences
  61. // 步骤3:特征点数大于100,则在mInitialFrame与mCurrentFrame中找匹配的特征点对
  62. //matcher的第一个参数0.9是最优匹配和次优匹配距离之间的阈值,最优匹配的距离要小于次优匹配的0.9倍才能被认为是合格的匹配
  63. //matcher的第二个参数表示是否开启方向匹配
  64. ORBmatcher matcher(0.9,true);
  65. /**
  66. * 计算当前帧和初始化帧之间的匹配关系
  67. * 在mInitialFrame与mCurrentFrame中找匹配的特征点对
  68. * mvbPrevMatched为前一帧的特征点的坐标,存储了mInitialFrame中哪些点将进行接下来的匹配
  69. * mvIniMatches用于存储mInitialFrame,mCurrentFrame之间匹配的特征点
  70. * mvIniMatches[i]中i为前一帧匹配的关键点的索引下标(),值为当前帧的匹配的关键点的索引下标。对于没匹配上的i,mvIniMatches[i]的值是-1
  71. **/
  72. /*
  73. 最后一个参数是匹配的范围
  74. 我们认为初始化时帧A和帧B变化不大,对于帧A中坐标为(x,y)的特征点,只在帧B中(x,y)的一定范围内寻找匹配特征点
  75. */
  76. int nmatches = matcher.SearchForInitialization(mInitialFrame,mCurrentFrame,mvbPrevMatched,mvIniMatches,100);
  77. // Check if there are enough correspondences
  78. // 步骤4:如果初始化的两帧之间的匹配点太少,重新初始化
  79. if(nmatches<100)
  80. {
  81. delete mpInitializer;
  82. mpInitializer = static_cast<Initializer*>(NULL);
  83. return;
  84. }
  85. cv::Mat Rcw; // 当前旋转矩阵
  86. cv::Mat tcw; // 当前平移矩阵
  87. vector<bool> vbTriangulated; // 三角化对应关系(三角化是指通过在两处观察同一个点的夹角,确定该点的距离。参考十四讲7.5)Triangulated Correspondences (mvIniMatches)
  88. // 步骤5:通过H模型或F模型进行单目初始化,得到两帧间相对运动、初始MapPoints
  89. if(mpInitializer->Initialize(mCurrentFrame, mvIniMatches, Rcw, tcw, mvIniP3D, vbTriangulated))
  90. {
  91. // 步骤6:删除那些无法进行三角化的匹配点
  92. for(size_t i=0, iend=mvIniMatches.size(); i<iend;i++)
  93. {
  94. //判断该点是否可以三角化
  95. if(mvIniMatches[i]>=0 && !vbTriangulated[i])
  96. {
  97. //表示两帧对应的关键点不再匹配
  98. mvIniMatches[i]=-1;
  99. //关键点匹配个数-1
  100. nmatches--;
  101. }
  102. }
  103. // Set Frame Poses
  104. // 将初始化的第一帧作为世界坐标系,因此第一帧相机的姿态为单位矩阵
  105. mInitialFrame.SetPose(cv::Mat::eye(4,4,CV_32F));
  106. // 由Rcw和tcw构造Tcw,并赋值给mTcw,mTcw为世界坐标系到该帧的变换矩阵
  107. cv::Mat Tcw = cv::Mat::eye(4,4,CV_32F);
  108. Rcw.copyTo(Tcw.rowRange(0,3).colRange(0,3));//colRange(0,3)指的是从第0列开始,往右数3列,也就是0,1,2列,而不是0,1,2,3列
  109. tcw.copyTo(Tcw.rowRange(0,3).col(3));
  110. mCurrentFrame.SetPose(Tcw);
  111. // 步骤6:将三角化得到的3D点包装成MapPoints
  112. // Initialize函数会得到mvIniP3D,
  113. // mvIniP3D是cv::Point3f类型的一个容器,是个存放3D点的临时变量,
  114. // CreateInitialMapMonocular将3D点包装成MapPoint类型存入KeyFrame和Map中
  115. CreateInitialMapMonocular();
  116. }
  117. }
  118. }

2.1 位姿跟踪

恒速运动模型——TrackWithMotionModel()

先假设这次的帧间运动和上次的帧间运动相同,根据上上帧和上一帧的位姿粗略地估计一个当前位姿,再用最小化重投影误差(BA)的方法对位姿进行优化(注意这里的优化只优化位姿,不动地图点)
步骤:

  • 1.首先通过上一帧的位姿和速度来设置当前帧相机的位姿
  • 2.通过PnP方法估计相机位姿,再将上一帧的地图点投影到当前固定大小范围的帧平面上,如果匹配点少,那么扩大两倍的采点范围
  • 3.然后进行一次BA算法,优化相机的位姿
  • 4.优化位姿之后,对当前帧的关键点和地图点,抛弃无用的杂点,剩下的点供下一次操作使用

代码如下

  1. bool Tracking::TrackWithMotionModel()
  2. {
  3. ORBmatcher matcher(0.9,true);
  4. // Update last frame pose according to its reference keyframe
  5. // Create "visual odometry" points
  6. // 步骤1:对于双目或rgbd摄像头,根据深度值为上一关键帧生成新的MapPoints
  7. // (跟踪过程中需要将当前帧与上一帧进行特征点匹配,将上一帧的MapPoints投影到当前帧可以缩小匹配范围)
  8. // 因为在跟踪过程中去除了outlier的MapPoint,如果不及时增加MapPoint会逐渐减少
  9. // 这个函数的功能就是补充增加RGBD和双目相机上一帧的MapPoints数(但这个mappoint是临时的,仅在这两帧之间用,不参与局部地图构建)
  10. UpdateLastFrame();
  11. // 根据恒速运动模型估计当前帧的位姿
  12. // mVelocity为最近一次前后帧位姿之差,它乘以上上帧等于上一帧
  13. mCurrentFrame.SetPose(mVelocity*mLastFrame.mTcw);
  14. fill(mCurrentFrame.mvpMapPoints.begin(),mCurrentFrame.mvpMapPoints.end(),static_cast<MapPoint*>(NULL));
  15. // Project points seen in previous frame
  16. // 在前一帧观察投影点
  17. int th;//投影点的搜索范围系数
  18. if(mSensor!=System::STEREO)
  19. th=15;
  20. else
  21. th=7;//双目相机搜索范围系数比较小,Dada觉得是因为双目的本身两只眼,给它一个小的范围系数,最后的实际范围是一样的(这不是很清楚)
  22. // 步骤2:根据恒速运动模型进行对上一帧的MapPoints进行跟踪
  23. // 根据上一帧特征点对应的3D点投影的位置缩小特征点匹配范围
  24. int nmatches = matcher.SearchByProjection(mCurrentFrame,mLastFrame,th,mSensor==System::MONOCULAR);
  25. // If few matches, uses a wider window search
  26. // 如果跟踪的点少,则扩大搜索半径再来一次,
  27. if(nmatches<20)
  28. {
  29. fill(mCurrentFrame.mvpMapPoints.begin(),mCurrentFrame.mvpMapPoints.end(),static_cast<MapPoint*>(NULL));
  30. nmatches = matcher.SearchByProjection(mCurrentFrame,mLastFrame,2*th,mSensor==System::MONOCULAR); // 可以看到这里是2*th
  31. }
  32. //如果跟踪的点还是太少,就认为恒速运动模型跟踪失败
  33. if(nmatches<20)
  34. return false;
  35. // Optimize frame pose with all matches
  36. // 步骤3:优化位姿,only-pose BA优化,只优化位姿不优化地图点
  37. Optimizer::PoseOptimization(&mCurrentFrame);
  38. // Discard outliers
  39. // 步骤4:优化位姿后解除outlier的mvpMapPoints与当前帧特征点的对应关系
  40. int nmatchesMap = 0;//表示优化位姿后当前帧的特征点中还能与局部地图的mappoint匹配的特征点的数目
  41. for(int i =0; i<mCurrentFrame.N; i++)//这一帧图片中共有N个特征点
  42. {
  43. if(mCurrentFrame.mvpMapPoints[i])//如果这个特征点有对应的mappoint
  44. {
  45. if(mCurrentFrame.mvbOutlier[i])//优化位姿后这个mappoint在这个位姿下是不应该观测到的,就把这个特征点和这个mappoint的匹配解除
  46. {
  47. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  48. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  49. mCurrentFrame.mvbOutlier[i]=false;
  50. pMP->mbTrackInView = false;
  51. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  52. nmatches--;
  53. }
  54. else if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  55. nmatchesMap++;
  56. }
  57. }
  58. if(mbOnlyTracking)
  59. {
  60. mbVO = nmatchesMap<10;
  61. return nmatches>20;//当前帧与上一帧匹配的特征点数
  62. }
  63. return nmatchesMap>=10;//当前帧与局部地图匹配的特征点数
  64. }

跟踪参考关键帧——TrackReferenceKeyFrame()

当恒速运动模型的跟踪效果不好时,就根据参考关键帧来计算位姿。
这种方法先假设当前帧的位姿为参考关键帧的位姿,后面与恒速模型相似,进行BA优化求解位姿。
注:参考关键帧是指与当前帧共视程度最高的关键帧
步骤:

  • 1.按照关键帧进行Track的方法和运动模式恢复相机运动位姿的方法接近。首先求解当前帧的BOW向量。
  • 2.再搜索当前帧和关键帧之间的关键点匹配关系,如果这个匹配关系小于15对的话,就Track失败了。
  • 3.接着将当前帧的位置假定到上一帧的位置那里
  • 4.并通过最小二乘法优化相机的位姿。
  • 5.最后依然是抛弃无用的杂点,当match数大于等于10的时候,返回true成功。

具体代码如下:

  1. bool Tracking::TrackReferenceKeyFrame()
  2. {
  3. // Compute Bag of Words vector
  4. // 步骤1:将当前帧的描述子转化为BoW向量
  5. mCurrentFrame.ComputeBoW();
  6. // We perform first an ORB matching with the reference keyframe
  7. // If enough matches are found we setup a PnP solver
  8. ORBmatcher matcher(0.7,true);//这种跟踪上一帧的模式比恒速运动模型的跟踪模式对ORB特征匹配的要求更严格
  9. /**
  10. * vpMapPointMatches中存储的是当前帧特征点的下标,值为mpReferenceKF参考帧中对应的MapPoint,没匹配上的下标对应的值为NULL
  11. */
  12. vector<MapPoint*> vpMapPointMatches;
  13. // 步骤2:通过特征点的BoW加快当前帧与参考帧之间的特征点匹配,对上一个关键帧进行BOW搜索匹配点
  14. // 特征点的匹配关系由MapPoints进行维护
  15. int nmatches = matcher.SearchByBoW(mpReferenceKF,mCurrentFrame,vpMapPointMatches);
  16. if(nmatches<15)
  17. return false;
  18. // 步骤3:将上一帧的位姿态作为当前帧位姿的初始值
  19. mCurrentFrame.mvpMapPoints = vpMapPointMatches;
  20. mCurrentFrame.SetPose(mLastFrame.mTcw); // 用上一次的Tcw设置初值,在PoseOptimization可以收敛快一些
  21. // 步骤4:通过优化3D-2D的重投影误差来获得位姿(PnP,详见十四讲7.7)
  22. Optimizer::PoseOptimization(&mCurrentFrame);
  23. // Discard outliers
  24. // 步骤5:剔除优化后的outlier匹配点(MapPoints)(这一部分详细注释见TrackWithMotionModel函数)
  25. int nmatchesMap = 0;
  26. for(int i =0; i<mCurrentFrame.N; i++)
  27. {
  28. if(mCurrentFrame.mvpMapPoints[i])
  29. {
  30. if(mCurrentFrame.mvbOutlier[i])
  31. {
  32. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  33. mCurrentFrame.mvpMapPoints[i]=static_cast<MapPoint*>(NULL);
  34. mCurrentFrame.mvbOutlier[i]=false;
  35. pMP->mbTrackInView = false;
  36. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  37. nmatches--;
  38. }
  39. else if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  40. nmatchesMap++;
  41. }
  42. }
  43. return nmatchesMap>=10;
  44. }

Relocalization——重定位

当上面两种方法都跟踪失败时,对相机的位姿进行重定位。
重定位的主要思想是在以前的关键帧数据库中找到与当前帧相似的一些候选关键帧,根据这些候选关键帧的数据,与当前帧进行匹配,利用PnP算法通过RANSAC迭代的方式求解当前位姿。
步骤:
* 1. 先计算当前帧的BOW值,并从关键帧数据库中查找候选的匹配关键帧
* 2. 构建PnP求解器,标记杂点,准备好每个关键帧和当前帧的匹配点集
* 3. 用PnP算法求解位姿,进行若干次P4P Ransac迭代,并使用非线性最小二乘优化,直到发现一个有充足inliers支持的相机位置
* 4. 返回成功或失败

具体代码如下:

  1. bool Tracking::Relocalization()
  2. {
  3. // Compute Bag of Words Vector
  4. //步骤1:计算当前帧特征点的Bow映射
  5. mCurrentFrame.ComputeBoW();
  6. // Relocalization is performed when tracking is lost
  7. // Track Lost: Query KeyFrame Database for keyframe candidates for relocalisation
  8. //步骤2:找到与当前帧相似的候选关键帧
  9. vector<KeyFrame*> vpCandidateKFs = mpKeyFrameDB->DetectRelocalizationCandidates(&mCurrentFrame);
  10. //如果未找到候选帧,返回false
  11. if(vpCandidateKFs.empty())
  12. return false;
  13. const int nKFs = vpCandidateKFs.size();
  14. // We perform first an ORB matching with each candidate
  15. // If enough matches are found we setup a PnP solver
  16. //我们首先执行与每个候选匹配的ORB匹配
  17. //如果找到足够的匹配,我们设置一个PNP解算器
  18. ORBmatcher matcher(0.75,true);
  19. vector<PnPsolver*> vpPnPsolvers;
  20. vpPnPsolvers.resize(nKFs);
  21. vector<vector<MapPoint*> > vvpMapPointMatches;
  22. vvpMapPointMatches.resize(nKFs);
  23. vector<bool> vbDiscarded;
  24. vbDiscarded.resize(nKFs);
  25. int nCandidates=0;
  26. //遍历候选关键帧
  27. for(int i=0; i<nKFs; i++)
  28. {
  29. KeyFrame* pKF = vpCandidateKFs[i];
  30. if(pKF->isBad())
  31. vbDiscarded[i] = true;//去除不好的候选关键帧
  32. else
  33. {
  34. //步骤3:通过BoW进行匹配,计算出pKF中和mCurrentFrame匹配的关键点的MapPoint存入vvpMapPointMatches中。
  35. int nmatches = matcher.SearchByBoW(pKF,mCurrentFrame,vvpMapPointMatches[i]);
  36. if(nmatches<15)
  37. {
  38. //候选关键帧中匹配点数小于15的丢弃
  39. vbDiscarded[i] = true;
  40. continue;
  41. }
  42. else//用pnp求解
  43. {
  44. //候选关键帧中匹配点数大于15的构建PnP求解器。这个PnP求解器中的3D point为vvpMapPointMatches中的MapPoint,2D点为mCurrentFrame中的关键点
  45. //因为是重定位,所以就是求重定位的候选帧对应的MapPoint到当前帧的关键点之间的投影关系,通过投影关系确定当前帧的位姿,也就进行了重定位
  46. PnPsolver* pSolver = new PnPsolver(mCurrentFrame,vvpMapPointMatches[i]);
  47. //候选帧中匹配点数大于15的进行Ransac迭代
  48. pSolver->SetRansacParameters(0.99,10,300,4,0.5,5.991);
  49. vpPnPsolvers[i] = pSolver;
  50. nCandidates++;
  51. }
  52. }
  53. }
  54. // Alternatively perform some iterations of P4P RANSAC
  55. // Until we found a camera pose supported by enough inliers
  56. // 执行一些P4P RANSAC迭代,直到我们找到一个由足够的inliers支持的相机位姿
  57. bool bMatch = false;
  58. ORBmatcher matcher2(0.9,true);
  59. while(nCandidates>0 && !bMatch)
  60. {
  61. for(int i=0; i<nKFs; i++)
  62. {
  63. if(vbDiscarded[i])
  64. continue;
  65. // Perform 5 Ransac Iterations
  66. vector<bool> vbInliers;
  67. int nInliers;
  68. bool bNoMore;
  69. //步骤4:通过EPnP算法估计姿态
  70. PnPsolver* pSolver = vpPnPsolvers[i];
  71. cv::Mat Tcw = pSolver->iterate(5,bNoMore,vbInliers,nInliers);
  72. // If Ransac reachs max. iterations discard keyframe
  73. if(bNoMore)
  74. {
  75. vbDiscarded[i]=true;
  76. nCandidates--;
  77. }
  78. // If a Camera Pose is computed, optimize
  79. if(!Tcw.empty())
  80. {
  81. Tcw.copyTo(mCurrentFrame.mTcw);
  82. set<MapPoint*> sFound;
  83. const int np = vbInliers.size();
  84. for(int j=0; j<np; j++)
  85. {
  86. if(vbInliers[j])
  87. {
  88. mCurrentFrame.mvpMapPoints[j]=vvpMapPointMatches[i][j];
  89. sFound.insert(vvpMapPointMatches[i][j]);
  90. }
  91. else
  92. mCurrentFrame.mvpMapPoints[j]=NULL;
  93. }
  94. //步骤5:通过PoseOptimization对姿态进行优化求解
  95. int nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  96. if(nGood<10)
  97. continue;
  98. for(int io =0; io<mCurrentFrame.N; io++)
  99. if(mCurrentFrame.mvbOutlier[io])
  100. mCurrentFrame.mvpMapPoints[io]=static_cast<MapPoint*>(NULL);
  101. // If few inliers, search by projection in a coarse window and optimize again
  102. //步骤6:如果内点比较少,在一个大概的窗口中投影并再次进行位姿优化
  103. if(nGood<50)
  104. {
  105. int nadditional =matcher2.SearchByProjection(mCurrentFrame,vpCandidateKFs[i],sFound,10,100);
  106. if(nadditional+nGood>=50)
  107. {
  108. nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  109. // If many inliers but still not enough, search by projection again in a narrower window
  110. // the camera has been already optimized with many points
  111. if(nGood>30 && nGood<50)
  112. {
  113. sFound.clear();
  114. for(int ip =0; ip<mCurrentFrame.N; ip++)
  115. if(mCurrentFrame.mvpMapPoints[ip])
  116. sFound.insert(mCurrentFrame.mvpMapPoints[ip]);
  117. nadditional =matcher2.SearchByProjection(mCurrentFrame,vpCandidateKFs[i],sFound,3,64);
  118. // Final optimization
  119. if(nGood+nadditional>=50)
  120. {
  121. nGood = Optimizer::PoseOptimization(&mCurrentFrame);
  122. for(int io =0; io<mCurrentFrame.N; io++)
  123. if(mCurrentFrame.mvbOutlier[io])
  124. mCurrentFrame.mvpMapPoints[io]=NULL;
  125. }
  126. }
  127. }
  128. }
  129. // If the pose is supported by enough inliers stop ransacs and continue
  130. if(nGood>=50)
  131. {
  132. bMatch = true;
  133. break;
  134. }
  135. }
  136. }
  137. }
  138. if(!bMatch)
  139. {
  140. return false;
  141. }
  142. else
  143. {
  144. mnLastRelocFrameId = mCurrentFrame.mnId;
  145. return true;
  146. }
  147. }

2.2 TrackLocalMap()——局部地图跟踪

局部地图由局部关键帧(LocalKeyFrames)和它们的地图点(LocalMapPoints)组成。
局部关键帧包含:

  • 与当前帧有共视关系的关键帧
  • 与上一组得到的关键帧共视关系较好的关键帧

这一部分主要是对它们进行更新,更新后再进行位姿的BA优化(这是第二次优化,第一次在位姿跟踪的部分。这次同样也是只优化位姿不优化地图点)
步骤:

  • 更新局部地图:UpdateLocalMap(),这里面包含UpdateLocalKeyFrames()和UpdateLocalPoints()
  • 在局部地图中查找与当前帧匹配的地图点:SearchLocalPoints()
  • 进行位姿优化:Optimizer::PoseOptimization()
  • 判断局部地图是否跟踪成功
    跟踪失败的条件为:
  1. 第一种情况:在刚进行重定位后,对跟踪的要求比较严格,当前帧的MapPoints被其他关键帧观测到50个以下就认为跟踪失败

  2. 第二种情况:正常状态,当前帧的MapPoints被其他关键帧观测到30个以下。
    具体代码如下:

  1. bool Tracking::TrackLocalMap()
  2. {
  3. // We have an estimation of the camera pose and some map points tracked in the frame.
  4. // We retrieve the local map and try to find matches to points in the local map.
  5. // Update Local KeyFrames and Local Points
  6. // 步骤1:更新局部关键帧mvpLocalKeyFrames和局部地图点mvpLocalMapPoints
  7. UpdateLocalMap();
  8. // 步骤2:在局部地图中查找与当前帧匹配的MapPoints
  9. SearchLocalPoints();
  10. // Optimize Pose,位姿优化(还是只优化位姿不优化地图点)
  11. // 在这个函数之前,在Relocalization、TrackReferenceKeyFrame、TrackWithMotionModel中都有位姿优化,
  12. // 步骤3:更新局部所有MapPoints后对位姿再次优化
  13. Optimizer::PoseOptimization(&mCurrentFrame);
  14. // Update MapPoints Statistics
  15. // 步骤3:更新当前帧的MapPoints被观测程度,并统计跟踪局部地图的效果
  16. mnMatchesInliers = 0;//表示当前帧的mappoint中能被其他关键帧观测到的个数
  17. for(int i=0; i<mCurrentFrame.N; i++)//遍历当前帧所有特征点
  18. {
  19. if(mCurrentFrame.mvpMapPoints[i])//这个特征点有相应的mappoint匹配
  20. {
  21. if(!mCurrentFrame.mvbOutlier[i])//mvbOutlier是指优化位姿后被排除在视野外的匹配对
  22. {
  23. // 由于当前帧的MapPoints可以被当前帧观测到,其被观测统计量加1
  24. mCurrentFrame.mvpMapPoints[i]->IncreaseFound();//这个加的是被普通帧观测到的次数
  25. if(!mbOnlyTracking)//用户选择正常模式
  26. {
  27. // 该MapPoint被其它关键帧观测到过
  28. if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)//这个Observations表示的是这个mappoint被关键帧观测到的次数
  29. mnMatchesInliers++;
  30. }
  31. else//用户选择仅跟踪定位模模式,不建图,不添加关键帧
  32. // 记录当前帧跟踪到的MapPoints,用于统计跟踪效果
  33. mnMatchesInliers++;
  34. }
  35. else if(mSensor==System::STEREO)
  36. mCurrentFrame.mvpMapPoints[i] = static_cast<MapPoint*>(NULL);
  37. }
  38. }
  39. // Decide if the tracking was succesful
  40. // More restrictive if there was a relocalization recently
  41. // 步骤4:决定是否跟踪成功
  42. //在刚进行重定位后,对跟踪的要求比较严格,要求当前帧的MapPoints被其他关键帧观测到50个以上
  43. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && mnMatchesInliers<50)
  44. return false;
  45. //正常状态要求当前帧的MapPoints被其他关键帧观测到30个以上
  46. if(mnMatchesInliers<30)
  47. return false;
  48. else
  49. return true;
  50. }
  51. /**
  52. * @brief 判断当前帧是否为关键帧
  53. * @return true if needed
  54. */
  55. /**
  56. * 函数功能:判断是否需要生成新的关键帧
  57. * 确定关键帧的标准(必须要同时满足):
  58. * 1.在上一全局重定位后,过了20帧;
  59. * 2.很久没有插入关键帧或localmapper空闲或跟踪要跟丢了(避免关键帧过密)
  60. * 3.当前帧跟踪到大于50个点;(当前帧跟踪状态良好)
  61. * 4.当前帧观测到的地图点中,参考关键帧也观测到的地图点的比例小于90%(单目)(确保新关键帧观测到了足够多的新环境)
  62. */
  63. bool Tracking::NeedNewKeyFrame()
  64. {
  65. // 步骤1:如果用户在界面上选择仅跟踪定位,那么将不插入关键帧
  66. // 由于插入关键帧过程中会生成MapPoint,因此用户选择仅跟踪定位后地图上的点云和关键帧都不会再增加
  67. if(mbOnlyTracking)
  68. return false;
  69. // If Local Mapping is freezed by a Loop Closure do not insert keyframes
  70. // 如果局部地图被回环检测线程使用,则不插入关键帧
  71. if(mpLocalMapper->isStopped() || mpLocalMapper->stopRequested())
  72. return false;
  73. const int nKFs = mpMap->KeyFramesInMap();//关键帧数
  74. // Do not insert keyframes if not enough frames have passed from last relocalisation
  75. // 步骤2:判断是否距离上一次重定位的时间太短
  76. // mCurrentFrame.mnId是当前帧的ID
  77. // mnLastRelocFrameId是最近一次重定位帧的ID
  78. // mMaxFrames等于图像输入的帧率
  79. // 如果距离上一次重定位超过1s(mMaxFrames个图像就是1s),则考虑插入关键帧
  80. // 或关键帧比较少,则考虑插入关键帧
  81. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && nKFs>mMaxFrames)
  82. return false;
  83. // Tracked MapPoints in the reference keyframe
  84. // 步骤3:得到参考关键帧跟踪到的MapPoints数量
  85. // 在UpdateLocalKeyFrames函数中会将与当前关键帧共视程度最高的关键帧设定为当前帧的参考关键帧
  86. int nMinObs = 3;
  87. if(nKFs<=2)
  88. nMinObs=2;
  89. //获取参考关键帧跟踪到的MapPoints数量
  90. int nRefMatches = mpReferenceKF->TrackedMapPoints(nMinObs);//关键帧中,大于等于minObs的MapPoints的数量,一个高质量的MapPoint会被多个KeyFrame观测到
  91. // Local Mapping accept keyframes?
  92. // 步骤4:查询局部地图管理器是否繁忙
  93. bool bLocalMappingIdle = mpLocalMapper->AcceptKeyFrames();
  94. // Stereo & RGB-D: Ratio of close "matches to map"/"total matches"
  95. // "total matches = matches to map + visual odometry matches"
  96. // Visual odometry matches will become MapPoints if we insert a keyframe.
  97. // This ratio measures how many MapPoints we could create if we insert a keyframe.
  98. // 步骤5:对于双目或RGBD摄像头,统计总的可以添加的MapPoints数量和跟踪到地图中的MapPoints数量
  99. int nMap = 0;
  100. int nTotal= 0;
  101. if(mSensor!=System::MONOCULAR)// 双目或rgbd
  102. {
  103. for(int i =0; i<mCurrentFrame.N; i++)//遍历当前帧所有特征点
  104. {
  105. if(mCurrentFrame.mvDepth[i]>0 && mCurrentFrame.mvDepth[i]<mThDepth)//剔除掉一些比较远的点
  106. {
  107. nTotal++;// 总的可以添加mappoints数
  108. if(mCurrentFrame.mvpMapPoints[i])
  109. if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  110. nMap++;// 被关键帧观测到的mappoints数,即观测到地图中的MapPoints数量
  111. }
  112. }
  113. }
  114. else
  115. {
  116. // There are no visual odometry matches in the monocular case
  117. nMap=1;
  118. nTotal=1;
  119. }
  120. const float ratioMap = (float)nMap/(float)(std::max(1,nTotal));//被关键帧观测到的mappoints数占当前帧中mappoint总数的比例
  121. // 步骤6:决策是否需要插入关键帧
  122. // Thresholds
  123. // 设定inlier阈值,和之前帧特征点匹配的inlier比例
  124. float thRefRatio = 0.75f;
  125. if(nKFs<2)
  126. thRefRatio = 0.4f;// 如果关键帧只有一帧,那么插入关键帧的阈值设置很低
  127. if(mSensor==System::MONOCULAR)
  128. thRefRatio = 0.9f;
  129. // MapPoints中和地图关联的比例阈值
  130. float thMapRatio = 0.35f;
  131. if(mnMatchesInliers>300)//mnMatchesInliers表示当前帧和参考帧共视点的数量
  132. thMapRatio = 0.20f;
  133. // Condition 1a: More than "MaxFrames" have passed from last keyframe insertion
  134. // 很长时间没有插入关键帧
  135. const bool c1a = mCurrentFrame.mnId>=mnLastKeyFrameId+mMaxFrames;
  136. // Condition 1b: More than "MinFrames" have passed and Local Mapping is idle
  137. // localMapper处于空闲状态
  138. const bool c1b = (mCurrentFrame.mnId>=mnLastKeyFrameId+mMinFrames && bLocalMappingIdle);
  139. // Condition 1c: tracking is weak
  140. // 跟踪要跪的节奏,0.25和0.3是一个比较低的阈值
  141. //第一个条件表示当前帧和参考帧重复度太低(因为参考关键帧是和当前帧共视点最多的了)
  142. //第二个条件表示当前帧的地图点大部分都没有被关键帧观测到
  143. const bool c1c = mSensor!=System::MONOCULAR && (mnMatchesInliers<nRefMatches*0.25 || ratioMap<0.3f) ;
  144. // Condition 2: Few tracked points compared to reference keyframe. Lots of visual odometry compared to map matches.
  145. // 阈值比c1c要高,与之前参考帧(最近的一个关键帧)重复度不是太高
  146. const bool c2 = ((mnMatchesInliers<nRefMatches*thRefRatio || ratioMap<thMapRatio) && mnMatchesInliers>15);
  147. if((c1a||c1b||c1c)&&c2)
  148. {
  149. // If the mapping accepts keyframes, insert keyframe.
  150. // Otherwise send a signal to interrupt BA
  151. //如果mapping接受关键帧,则插入关键帧,否则发送信号中断BA
  152. if(bLocalMappingIdle)
  153. {
  154. return true;
  155. }
  156. else
  157. {
  158. mpLocalMapper->InterruptBA();
  159. if(mSensor!=System::MONOCULAR)//这后面不是很清楚
  160. {
  161. // 队列里不能阻塞太多关键帧
  162. // tracking插入关键帧不是直接插入,而且先插入到mlNewKeyFrames中,
  163. // 然后localmapper再逐个pop出来插入到mspKeyFrames
  164. if(mpLocalMapper->KeyframesInQueue()<3)
  165. return true;
  166. else
  167. return false;
  168. }
  169. else
  170. return false;
  171. }
  172. }
  173. else
  174. return false;
  175. }

更新局部关键帧——UpdateLocalKeyFrames()

局部关键帧的选取策略如下:

  • 策略1:能观测到当前帧MapPoints的关键帧作为局部关键帧
  • 策略2:与策略1得到的局部关键帧共视程度很高的关键帧作为局部关键帧
    策略2.1:最佳共视的10帧
    策略2.2:自己的子关键帧
    策略2.3:自己的父关键帧

代码如下:

  1. void Tracking::UpdateLocalKeyFrames()
  2. {
  3. // Each map point vote for the keyframes in which it has been observed
  4. // 步骤1:遍历当前帧的MapPoints,记录所有能观测到当前帧MapPoints的关键帧
  5. map<KeyFrame*,int> keyframeCounter;//keyframeCounter中最后存放的就是对应关键帧可以看到当前帧mCurrentFrame里多少个MapPoint
  6. for(int i=0; i<mCurrentFrame.N; i++)
  7. {
  8. if(mCurrentFrame.mvpMapPoints[i])
  9. {
  10. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  11. if(!pMP->isBad())//这个Bad是在local BA里面判别的,大致是这个地图点被观测的帧数小于2(具体不是很清楚,暂时留在这里)
  12. {
  13. // 能观测到当前帧MapPoints的关键帧
  14. //这两步操作不是很清楚(原理懂,代码不是很清楚)
  15. const map<KeyFrame*,size_t> observations = pMP->GetObservations();
  16. for(map<KeyFrame*,size_t>::const_iterator it=observations.begin(), itend=observations.end(); it!=itend; it++)
  17. keyframeCounter[it->first]++;
  18. }
  19. else
  20. {
  21. mCurrentFrame.mvpMapPoints[i]=NULL;
  22. }
  23. }
  24. }
  25. if(keyframeCounter.empty())
  26. return;
  27. int max=0;
  28. KeyFrame* pKFmax= static_cast<KeyFrame*>(NULL);//pKFmax表示能看到MapPoint点数最多的关键帧
  29. // 步骤2:更新局部关键帧(mvpLocalKeyFrames),添加局部关键帧有三个策略
  30. // 先清空局部关键帧
  31. mvpLocalKeyFrames.clear();
  32. mvpLocalKeyFrames.reserve(3*keyframeCounter.size());
  33. // All keyframes that observe a map point are included in the local map. Also check which keyframe shares most points
  34. // V-D K1: shares the map points with current frame
  35. // 策略1:能观测到当前帧MapPoints的关键帧作为局部关键帧
  36. for(map<KeyFrame*,int>::const_iterator it=keyframeCounter.begin(), itEnd=keyframeCounter.end(); it!=itEnd; it++)
  37. {
  38. KeyFrame* pKF = it->first;
  39. if(pKF->isBad())
  40. continue;
  41. if(it->second>max)//it->second表示pKF这个关键帧可以看到多少个MapPoint
  42. {
  43. max=it->second;
  44. pKFmax=pKF;//pKFmax表示能看到MapPoint点数最多的关键帧
  45. }
  46. //mvpLocalKeyFrames里边存放的是能看到当前帧对应的MapPoint的关键帧列表
  47. mvpLocalKeyFrames.push_back(it->first);
  48. // mnTrackReferenceForFrame防止重复添加局部关键帧
  49. pKF->mnTrackReferenceForFrame = mCurrentFrame.mnId;
  50. }
  51. // Include also some not-already-included keyframes that are neighbors to already-included keyframes
  52. // V-D K2: neighbors to K1 in the covisibility graph
  53. // 策略2:与策略1得到的局部关键帧共视程度很高的关键帧作为局部关键帧
  54. for(vector<KeyFrame*>::const_iterator itKF=mvpLocalKeyFrames.begin(), itEndKF=mvpLocalKeyFrames.end(); itKF!=itEndKF; itKF++)
  55. {
  56. // Limit the number of keyframes
  57. if(mvpLocalKeyFrames.size()>80)
  58. break;
  59. KeyFrame* pKF = *itKF;
  60. // 策略2.1:最佳共视的10帧
  61. const vector<KeyFrame*> vNeighs = pKF->GetBestCovisibilityKeyFrames(10);
  62. for(vector<KeyFrame*>::const_iterator itNeighKF=vNeighs.begin(), itEndNeighKF=vNeighs.end(); itNeighKF!=itEndNeighKF; itNeighKF++)
  63. {
  64. KeyFrame* pNeighKF = *itNeighKF;
  65. if(!pNeighKF->isBad())
  66. {
  67. // mnTrackReferenceForFrame防止重复添加局部关键帧
  68. if(pNeighKF->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  69. {
  70. mvpLocalKeyFrames.push_back(pNeighKF);
  71. pNeighKF->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  72. break;
  73. }
  74. }
  75. }
  76. // 策略2.2:自己的子关键帧
  77. const set<KeyFrame*> spChilds = pKF->GetChilds();
  78. for(set<KeyFrame*>::const_iterator sit=spChilds.begin(), send=spChilds.end(); sit!=send; sit++)
  79. {
  80. KeyFrame* pChildKF = *sit;
  81. if(!pChildKF->isBad())
  82. {
  83. if(pChildKF->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  84. {
  85. mvpLocalKeyFrames.push_back(pChildKF);
  86. pChildKF->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  87. break;
  88. }
  89. }
  90. }
  91. // 策略2.3:自己的父关键帧
  92. KeyFrame* pParent = pKF->GetParent();
  93. if(pParent)
  94. {
  95. // mnTrackReferenceForFrame防止重复添加局部关键帧
  96. if(pParent->mnTrackReferenceForFrame!=mCurrentFrame.mnId)
  97. {
  98. mvpLocalKeyFrames.push_back(pParent);
  99. pParent->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  100. break;
  101. }
  102. }
  103. }

更新局部地图点——UpdateLocalPoints()

局部地图点:局部关键帧对应的地图点
代码如下:

  1. void Tracking::UpdateLocalPoints()
  2. {
  3. // 步骤1:清空局部MapPoints
  4. mvpLocalMapPoints.clear();
  5. // 步骤2:遍历局部关键帧mvpLocalKeyFrames
  6. for(vector<KeyFrame*>::const_iterator itKF=mvpLocalKeyFrames.begin(), itEndKF=mvpLocalKeyFrames.end(); itKF!=itEndKF; itKF++)
  7. {
  8. KeyFrame* pKF = *itKF;
  9. const vector<MapPoint*> vpMPs = pKF->GetMapPointMatches();
  10. // 步骤2:将局部关键帧的每个MapPoints添加到mvpLocalMapPoints
  11. for(vector<MapPoint*>::const_iterator itMP=vpMPs.begin(), itEndMP=vpMPs.end(); itMP!=itEndMP; itMP++)
  12. {
  13. MapPoint* pMP = *itMP;
  14. if(!pMP)
  15. continue;
  16. // mnTrackReferenceForFrame防止重复添加局部MapPoint
  17. if(pMP->mnTrackReferenceForFrame==mCurrentFrame.mnId)
  18. continue;
  19. if(!pMP->isBad())
  20. {
  21. mvpLocalMapPoints.push_back(pMP);
  22. pMP->mnTrackReferenceForFrame=mCurrentFrame.mnId;
  23. }
  24. }
  25. }
  26. }

获取局部地图和当前帧的匹配关系SearchLocalPoints()

在局部地图中查找在当前帧视野范围内的点,将视野范围内的点和当前帧的特征点进行投影匹配
代码如下:

  1. void Tracking::SearchLocalPoints()
  2. {
  3. // Do not search map points already matched
  4. // 步骤1:遍历当前帧的mvpMapPoints,标记这些MapPoints不参与之后的搜索
  5. // 因为当前的mvpMapPoints一定在当前帧的视野中
  6. for(vector<MapPoint*>::iterator vit=mCurrentFrame.mvpMapPoints.begin(), vend=mCurrentFrame.mvpMapPoints.end(); vit!=vend; vit++)
  7. {
  8. MapPoint* pMP = *vit;
  9. if(pMP)
  10. {
  11. if(pMP->isBad())
  12. {
  13. *vit = static_cast<MapPoint*>(NULL);
  14. }
  15. else
  16. {
  17. // 更新能观测到该点的帧数加1
  18. pMP->IncreaseVisible();
  19. // 标记该点被当前帧观测到
  20. pMP->mnLastFrameSeen = mCurrentFrame.mnId;
  21. // 标记该点将来不被投影,因为已经匹配过
  22. pMP->mbTrackInView = false;
  23. }
  24. }
  25. }
  26. int nToMatch=0;//局部地图中除了当前帧的mvpMapPoints之外的点,在当前视野内的数目
  27. // Project points in frame and check its visibility
  28. // 步骤2:将所有局部MapPoints投影到当前帧,判断是否在视野范围内,然后进行投影匹配
  29. for(vector<MapPoint*>::iterator vit=mvpLocalMapPoints.begin(), vend=mvpLocalMapPoints.end(); vit!=vend; vit++)
  30. {
  31. MapPoint* pMP = *vit;
  32. // 已经被当前帧观测到MapPoint不再判断是否能被当前帧观测到
  33. if(pMP->mnLastFrameSeen == mCurrentFrame.mnId)
  34. continue;
  35. if(pMP->isBad())
  36. continue;
  37. // Project (this fills MapPoint variables for matching)
  38. // 步骤2.1:判断LocalMapPoints中的点是否在在视野内
  39. if(mCurrentFrame.isInFrustum(pMP,0.5))//0.5表示当前帧对该mappoint的观测视角与该mappoint被观测的平均视角差的余弦值不能超过0.5,也就是60度
  40. {
  41. // 观测到该点的帧数加1,该MapPoint在某些帧的视野范围内
  42. pMP->IncreaseVisible();
  43. // 只有在视野范围内的MapPoints才参与之后的投影匹配
  44. nToMatch++;
  45. }
  46. }
  47. if(nToMatch>0)
  48. {
  49. ORBmatcher matcher(0.8);
  50. int th = 1;
  51. if(mSensor==System::RGBD)
  52. th=3;
  53. // If the camera has been relocalised recently, perform a coarser search
  54. // 如果不久前进行过重定位,那么进行一个更加宽泛的搜索,阈值需要增大
  55. if(mCurrentFrame.mnId<mnLastRelocFrameId+2)
  56. th=5;
  57. // 步骤2.2:对视野范围内的MapPoints通过投影进行特征点匹配
  58. matcher.SearchByProjection(mCurrentFrame,mvpLocalMapPoints,th);
  59. }
  60. }

2.3 新关键帧的生成判断和生成

判断能否生成新的关键帧

确定关键帧的标准(必须要同时满足):

  • 1.局部地图没有被回环检测线程使用;
  • 2.距离上一次重定位时间比较长,或者比较短但是关键帧总数比较少
  • 3.很久没有插入关键帧或localmapper空闲或跟踪要跟丢了
  • 4.当前帧观测到的地图点中,参考关键帧也观测到的地图点的比例小于90%(单目)(确保新关键帧观测到了足够多的新环境)
    代码如下:
  1. bool Tracking::NeedNewKeyFrame()
  2. {
  3. // 步骤1:如果用户在界面上选择仅跟踪定位,那么将不插入关键帧
  4. // 由于插入关键帧过程中会生成MapPoint,因此用户选择仅跟踪定位后地图上的点云和关键帧都不会再增加
  5. if(mbOnlyTracking)
  6. return false;
  7. // If Local Mapping is freezed by a Loop Closure do not insert keyframes
  8. // 如果局部地图被回环检测线程使用,则不插入关键帧
  9. if(mpLocalMapper->isStopped() || mpLocalMapper->stopRequested())
  10. return false;
  11. const int nKFs = mpMap->KeyFramesInMap();//关键帧数
  12. // Do not insert keyframes if not enough frames have passed from last relocalisation
  13. // 步骤2:判断是否距离上一次重定位的时间太短
  14. // mCurrentFrame.mnId是当前帧的ID
  15. // mnLastRelocFrameId是最近一次重定位帧的ID
  16. // mMaxFrames等于图像输入的帧率
  17. // 如果距离上一次重定位超过1s(mMaxFrames个图像就是1s),则考虑插入关键帧
  18. // 或关键帧比较少,则考虑插入关键帧
  19. if(mCurrentFrame.mnId<mnLastRelocFrameId+mMaxFrames && nKFs>mMaxFrames)
  20. return false;
  21. // Tracked MapPoints in the reference keyframe
  22. // 步骤3:得到参考关键帧跟踪到的MapPoints数量
  23. // 在UpdateLocalKeyFrames函数中会将与当前关键帧共视程度最高的关键帧设定为当前帧的参考关键帧
  24. int nMinObs = 3;
  25. if(nKFs<=2)
  26. nMinObs=2;
  27. //获取参考关键帧跟踪到的MapPoints数量
  28. int nRefMatches = mpReferenceKF->TrackedMapPoints(nMinObs);//关键帧中,大于等于minObs的MapPoints的数量,一个高质量的MapPoint会被多个KeyFrame观测到
  29. // Local Mapping accept keyframes?
  30. // 步骤4:查询局部地图管理器是否繁忙
  31. bool bLocalMappingIdle = mpLocalMapper->AcceptKeyFrames();
  32. // Stereo & RGB-D: Ratio of close "matches to map"/"total matches"
  33. // "total matches = matches to map + visual odometry matches"
  34. // Visual odometry matches will become MapPoints if we insert a keyframe.
  35. // This ratio measures how many MapPoints we could create if we insert a keyframe.
  36. // 步骤5:对于双目或RGBD摄像头,统计总的可以添加的MapPoints数量和跟踪到地图中的MapPoints数量
  37. int nMap = 0;
  38. int nTotal= 0;
  39. if(mSensor!=System::MONOCULAR)// 双目或rgbd
  40. {
  41. for(int i =0; i<mCurrentFrame.N; i++)//遍历当前帧所有特征点
  42. {
  43. if(mCurrentFrame.mvDepth[i]>0 && mCurrentFrame.mvDepth[i]<mThDepth)//剔除掉一些比较远的点
  44. {
  45. nTotal++;// 总的可以添加mappoints数
  46. if(mCurrentFrame.mvpMapPoints[i])
  47. if(mCurrentFrame.mvpMapPoints[i]->Observations()>0)
  48. nMap++;// 被关键帧观测到的mappoints数,即观测到地图中的MapPoints数量
  49. }
  50. }
  51. }
  52. else
  53. {
  54. // There are no visual odometry matches in the monocular case
  55. nMap=1;
  56. nTotal=1;
  57. }
  58. const float ratioMap = (float)nMap/(float)(std::max(1,nTotal));//被关键帧观测到的mappoints数占当前帧中mappoint总数的比例
  59. // 步骤6:决策是否需要插入关键帧
  60. // Thresholds
  61. // 设定inlier阈值,和之前帧特征点匹配的inlier比例
  62. float thRefRatio = 0.75f;
  63. if(nKFs<2)
  64. thRefRatio = 0.4f;// 如果关键帧只有一帧,那么插入关键帧的阈值设置很低
  65. if(mSensor==System::MONOCULAR)
  66. thRefRatio = 0.9f;
  67. // MapPoints中和地图关联的比例阈值
  68. float thMapRatio = 0.35f;
  69. if(mnMatchesInliers>300)//mnMatchesInliers表示当前帧和参考帧共视点的数量
  70. thMapRatio = 0.20f;
  71. // Condition 1a: More than "MaxFrames" have passed from last keyframe insertion
  72. // 很长时间没有插入关键帧
  73. const bool c1a = mCurrentFrame.mnId>=mnLastKeyFrameId+mMaxFrames;
  74. // Condition 1b: More than "MinFrames" have passed and Local Mapping is idle
  75. // localMapper处于空闲状态
  76. const bool c1b = (mCurrentFrame.mnId>=mnLastKeyFrameId+mMinFrames && bLocalMappingIdle);
  77. // Condition 1c: tracking is weak
  78. // 跟踪要跪的节奏,0.25和0.3是一个比较低的阈值
  79. //第一个条件表示当前帧和参考帧重复度太低(因为参考关键帧是和当前帧共视点最多的了)
  80. //第二个条件表示当前帧的地图点大部分都没有被关键帧观测到
  81. const bool c1c = mSensor!=System::MONOCULAR && (mnMatchesInliers<nRefMatches*0.25 || ratioMap<0.3f) ;
  82. // Condition 2: Few tracked points compared to reference keyframe. Lots of visual odometry compared to map matches.
  83. // 阈值比c1c要高,与之前参考帧(最近的一个关键帧)重复度不是太高
  84. const bool c2 = ((mnMatchesInliers<nRefMatches*thRefRatio || ratioMap<thMapRatio) && mnMatchesInliers>15);
  85. if((c1a||c1b||c1c)&&c2)
  86. {
  87. // If the mapping accepts keyframes, insert keyframe.
  88. // Otherwise send a signal to interrupt BA
  89. //如果mapping接受关键帧,则插入关键帧,否则发送信号中断BA
  90. if(bLocalMappingIdle)
  91. {
  92. return true;
  93. }
  94. else
  95. {
  96. mpLocalMapper->InterruptBA();
  97. if(mSensor!=System::MONOCULAR)//这后面不是很清楚
  98. {
  99. // 队列里不能阻塞太多关键帧
  100. // tracking插入关键帧不是直接插入,而且先插入到mlNewKeyFrames中,
  101. // 然后localmapper再逐个pop出来插入到mspKeyFrames
  102. if(mpLocalMapper->KeyframesInQueue()<3)
  103. return true;
  104. else
  105. return false;
  106. }
  107. else
  108. return false;
  109. }
  110. }
  111. else
  112. return false;
  113. }

关键帧的生成

步骤:

  • 1:用当前帧构造成关键帧
  • 2:将当前关键帧设置为当前帧的参考关键帧
  • 3:对于双目或rgbd摄像头,为当前帧生成新的MapPoints
  1. void Tracking::CreateNewKeyFrame()
  2. {
  3. if(!mpLocalMapper->SetNotStop(true))
  4. return;
  5. // 步骤1:将当前帧构造成关键帧
  6. KeyFrame* pKF = new KeyFrame(mCurrentFrame,mpMap,mpKeyFrameDB);
  7. // 步骤2:将当前关键帧设置为当前帧的参考关键帧
  8. // 在UpdateLocalKeyFrames函数中会将与当前关键帧共视程度最高的关键帧设定为当前帧的参考关键帧
  9. mpReferenceKF = pKF;
  10. mCurrentFrame.mpReferenceKF = pKF;
  11. // 这段代码和UpdateLastFrame中的那一部分代码功能相同
  12. // 步骤3:对于双目或rgbd摄像头,为当前帧生成新的MapPoints
  13. if(mSensor!=System::MONOCULAR)
  14. {
  15. // 根据Tcw计算mRcw、mtcw和mRwc、mOw
  16. mCurrentFrame.UpdatePoseMatrices();
  17. // We sort points by the measured depth by the stereo/RGBD sensor.
  18. // We create all those MapPoints whose depth < mThDepth.
  19. // If there are less than 100 close points we create the 100 closest.
  20. // 步骤3.1:得到当前帧深度小于阈值的特征点
  21. // 创建新的MapPoint, depth < mThDepth
  22. vector<pair<float,int> > vDepthIdx;
  23. vDepthIdx.reserve(mCurrentFrame.N);
  24. for(int i=0; i<mCurrentFrame.N; i++)
  25. {
  26. float z = mCurrentFrame.mvDepth[i];
  27. if(z>0)
  28. {
  29. vDepthIdx.push_back(make_pair(z,i));
  30. }
  31. }
  32. if(!vDepthIdx.empty())
  33. {
  34. // 步骤3.2:按照深度从小到大排序
  35. sort(vDepthIdx.begin(),vDepthIdx.end());
  36. // 步骤3.3:将距离比较近的点包装成MapPoints
  37. int nPoints = 0;
  38. for(size_t j=0; j<vDepthIdx.size();j++)
  39. {
  40. int i = vDepthIdx[j].second;
  41. bool bCreateNew = false;
  42. MapPoint* pMP = mCurrentFrame.mvpMapPoints[i];
  43. if(!pMP)
  44. bCreateNew = true;
  45. else if(pMP->Observations()<1)
  46. {
  47. bCreateNew = true;
  48. mCurrentFrame.mvpMapPoints[i] = static_cast<MapPoint*>(NULL);
  49. }
  50. if(bCreateNew)
  51. {
  52. cv::Mat x3D = mCurrentFrame.UnprojectStereo(i);
  53. MapPoint* pNewMP = new MapPoint(x3D,pKF,mpMap);
  54. // 这些添加属性的操作是每次创建MapPoint后都要做的
  55. pNewMP->AddObservation(pKF,i);
  56. pKF->AddMapPoint(pNewMP,i);
  57. pNewMP->ComputeDistinctiveDescriptors();
  58. pNewMP->UpdateNormalAndDepth();
  59. mpMap->AddMapPoint(pNewMP);
  60. mCurrentFrame.mvpMapPoints[i]=pNewMP;
  61. nPoints++;
  62. }
  63. else
  64. {
  65. nPoints++;
  66. }
  67. // 这里决定了双目和rgbd摄像头时地图点云的稠密程度
  68. // 但是仅仅为了让地图稠密直接改这些不太好,
  69. // 因为这些MapPoints会参与之后整个slam过程
  70. if(vDepthIdx[j].first>mThDepth && nPoints>100)
  71. break;
  72. }
  73. }
  74. }
  75. /**
  76. * 往LocalMapping线程的mlNewKeyFrames队列中插入新生成的keyframe
  77. * LocalMapping线程中检测到有队列中有keyframe插入后线程会run起来
  78. */
  79. mpLocalMapper->InsertKeyFrame(pKF);
  80. mpLocalMapper->SetNotStop(false);
  81. mnLastKeyFrameId = mCurrentFrame.mnId;
  82. mpLastKeyFrame = pKF;
  83. }

其他相关知识

三角化

三角化是指通过在两处观察同一个点的夹角,确定该点的距离。(详见十四讲7.5)

Mat类的rowRange和colRange

colRange(0,3)指的是从第0列开始,往右数3列,也就是0,1,2列,而不是0,1,2,3列
这个成员函数出现在T矩阵和R,t矩阵之间转化的时候,比如单目相机初始化的这段。所以取R矩阵的这行和下面取t矩阵的那行并不冲突。

  1. // 由Rcw和tcw构造Tcw,并赋值给mTcw,mTcw为世界坐标系到该帧的变换矩阵
  2. cv::Mat Tcw = cv::Mat::eye(4,4,CV_32F);
  3. Rcw.copyTo(Tcw.rowRange(0,3).colRange(0,3));
  4. tcw.copyTo(Tcw.rowRange(0,3).col(3));
  5. mCurrentFrame.SetPose(Tcw);

map类

这里只做简单介绍,详见这篇文章

  • map的定义
    map是STL的一个关联容器,它提供一对一的hash(可以理解为映射)。
  • map的组成
    map对象是模板类,需要关键字key和存储对象value两个模板参数。key 和 value可以是任意你需要的类型,包括自定义类型。每个key只能在这个map中出现一次(就像数组的下标,只不过key可以是任意类型任意值)。
  • map的构造
    map的构造函数有6种,我们最常用下面这种方式构造一个map
  1. map<int, string> mapStudent;
    • map的基本操作
      begin() 返回指向map头部的迭代器

      clear() 删除所有元素

      count() 返回指定元素出现的次数

      empty() 如果map为空则返回true

      end() 返回指向map末尾的迭代器

      equal_range() 返回特殊条目的迭代器对

      erase() 删除一个元素

      find() 查找一个元素

      get_allocator() 返回map的配置器

      insert() 插入元素

      key_comp() 返回比较元素key的函数

      lower_bound() 返回键值>=给定元素的第一个位置

      max_size() 返回可以容纳的最大元素个数

      rbegin() 返回一个指向map尾部的逆向迭代器

      rend() 返回一个指向map头部的逆向迭代器

      size() 返回map中元素的个数

      swap() 交换两个map

      upper_bound() 返回键值>给定元素的第一个位置

      value_comp() 返回比较元素value的函数

ORB-SLAM2-tracking线程的更多相关文章

  1. ORB SLAM2在Ubuntu 16.04上的运行配置

    http://www.mamicode.com/info-detail-1773781.html 安装依赖 安装OpenGL 1. 安装opengl Library$sudo apt-get inst ...

  2. ORB-SLAM2 论文&代码学习 ——Tracking 线程

    本文要点: ORB-SLAM2 Tracking 线程 论文内容介绍 ORB-SLAM2 Tracking 线程 代码结构介绍 写在前面 上一篇文章中我们已经对 ORB-SLAM2 系统有了一个概览性 ...

  3. orb slam2 双目摄像头

    主要参考了http://blog.csdn.net/awww797877/article/details/51171099这篇文章,其中需要添加的是:export ROS_PACKAGE_PATH=$ ...

  4. 关于ORB SLAM2资源整理(持续更新)

    ORB SLAM2源码讲解(吴博) https://www.youtube.com/watch?v=2GVE7FTW7AU 泡泡机器人视频整理: http://space.bilibili.com/3 ...

  5. 重读ORB_SLAM之Tracking线程难点

    1. 初始化 当获取第一帧图像与深度图后,首先设置第一帧位姿为4*4单位矩阵,然后为整个map添加关键帧与地图点.且更新地图点与关键帧的联系,例如地图点被哪个关键帧观测到,而此关键帧又包含哪些地图点. ...

  6. ORB SLAM2 学习笔记

    cd ~/Documents/demos/ORB_SLAM2 ./Examples/RGB-D/rgbd_tum Vocabulary/ORBvoc.txt Examples/RGB-D/TUM1.y ...

  7. Ubuntu14.04 使用本地摄像头跑ORB SLAM2(暂未完成)

    嗯 这个方法我暂时弄不出来,用了另外一个方法:SLAM14讲 第一次课 使用摄像头或视频运行 ORB-SLAM2 前面的准备: Ubuntu14.04安装 ROS 安装步骤和问题总结 Ubuntu14 ...

  8. orb slam2

  9. 使用 evo 工具评测 VI ORB SLAM2 在 EuRoC 上的结果

    http://www.liuxiao.org/2017/11/%E4%BD%BF%E7%94%A8-evo-%E5%B7%A5%E5%85%B7%E8%AF%84%E6%B5%8B-vi-orb-sl ...

  10. Ubuntu16.04+Ros+Usb_Cam ORB SLAM2

    转载自:https://www.jianshu.com/p/dbf39b9e4617亲测可用 1.其中编译ORB_SLAM2的   ./build.sh 和 ./build_ros.sh之前需要修改文 ...

随机推荐

  1. pandas的学习6-合并concat

    import pandas as pd import numpy as np ''' pandas处理多组数据的时候往往会要用到数据的合并处理,使用 concat是一种基本的合并方式. 而且conca ...

  2. CTF练习②

    参考的文章链接 :https://www.cnblogs.com/chrysanthemum/p/11657008.html 这个题是强网杯的一道SQL注入的题,网上有不少的在线靶场和writeup, ...

  3. 怎样用Python自制好看的指数估值图

    对于以定投指数的方式理财的朋友,最需要关注的指标便是各个指数的估值,在指数低估时买入,高估时卖出,那如何制作一张估值图来跟踪指数的估值情况呢?本文就从0到1介绍如何用 Matplotlib 画一张漂亮 ...

  4. C# 锁与死锁

    什么是死锁: 所谓死锁,是指多个进程在运行过程中因争夺资源而造成的一种僵局,当进程处于这种僵持状态时,若无外力作用,它们都将无法再向前推进. 因此我们举个例子来描述,如果此时有一个线程A,按照先锁a再 ...

  5. VS挂接崩溃包

    主要用来在用户机器上对目标进程生成dump文件,定位"卡死".Crash等问题.推荐相关工具DumpTool,WinCrashReport. DumpTool 下载 WinCras ...

  6. sql 中 foreach 中传入多个不同的参数问题

    <!--查找某用户绑定的药物不良反应报告列表--> <select id="selectSurveyListByUserProId" resultType=&qu ...

  7. MM-采购模块相关业务

    采购模块主要业务流程: 1.收集采购需求(采购申请单),系统采购申请单单据可以由需求部门手工产生,也可以由系统的MRP(物料需求计划)来产生. 2,货源确定,用来确定所申请的物料,通过何种方式向供应商 ...

  8. [leetcode]House Robber1,2

    /** * 一. * You are a professional robber planning to rob houses along a street.Each house has a cert ...

  9. 关于try catch块执行流程

    代码: package test; public class FinallyTest { public static void main(String[] args) { try { // proce ...

  10. 伯俊BOS2.0关于订金单的处理方案

    订金单功能调整设计 一.     功能确认 BPOS关于订金的使用对应的是"预收单",原"预收单"设置有商品明细,根据客户对订金的需求,取消原有"商品 ...