• 手撕 视觉slam14讲 ch13 代码(5)双目初始化 StereoInit()


    上一篇,我们分析了Frontend::AddFrame()函数,将会根据前端状态变量FrontendStatus,运行不同的三个函数,StereoInit(),Track()和Reset(),首先肯定是双目初始化StereoInit()函数:

    双目初始化的步骤也很简单:就是根据左右目之间的光流匹配,寻找可以三角化的地图点,成功时建立初始地图:

    • 首先用 DetectFeatures() 函数对左目提GFTT特征点
    • 然后用FindFeaturesInRight() 函数进行左右目光流来匹配左右目的特征点。根据左目特征点的位置来找右边对应特征点的位置。
    • 如果匹配到的特征点数量大于num_features_init_(默认100个),就进行 BuildInitMap() 函数来进行地图初始化。根据双目的相对位置和匹配的特征点把特征点进行三角化,计算出特征点的 3D位置 。
    • 地图初始化成功后就改前端状态为TRACKING_GOOD,并把当前帧图像和地图点送到 viewer_ 线程里用做显示。
    1. //双目初始化
    2. //根据左右目之间的光流匹配,寻找可以三角化的地图点,成功时建立初始地图
    3. bool Frontend::StereoInit(){
    4. //提取左目的GFTT特征点(数量)
    5. int num_features_left = DetectFeatures();
    6. // 右目光流追踪
    7. int num_coor_features=FindFeaturesInRight();
    8. //如果匹配到的特征点数量小于num_features_init_,默认100个,就返回false
    9. if (num_coor_features < num_features_init_)
    10. {
    11. return false;
    12. }
    13. //初始化地图
    14. bool build_map_success= BuildInitMap();
    15. //如果地图初始化成功就改前端状态为TRACKING_GOOD,并把当前帧和地图点传到viewer_线程里
    16. if (build_map_success)
    17. {
    18. status_=FrontendStatus::TRACKING_GOOD;
    19. //地图在可视化端的操作,添加当前帧并更新整个地图
    20. if (viewer_)
    21. {
    22. viewer_->AddCurrentFrame(current_frame_);
    23. viewer_->UpdateMap();
    24. }
    25. return true; //地图初始化成功,返回ture
    26. }
    27. return false; //地图初始化失败,返回false
    28. }

    接下来我们具体看一下函数实现:

    DetectFeatures()函数:

    • 第一步,通过mask的方式,来使得特征提取均匀化,就是在已经存在特征点的地方,画一个20x20的矩形框,在这个范围内不再提取新的特征点;
    • 第二步,在第一步的mask的基础上,提取新的特征点;
    • 最后,把这些特征点push_back到当前帧的特征点里面去。关联当前帧current_frame_和检测到的新特征点的像素位置kp,同时统计这两次检测到的特征点数量
    1. /*提取左目的GFTT特征点(数量)
    2. //opencv中mask的作用就是创建感兴趣区域,即待处理的区域。
    3. 通常,mask大小创建分为两步,先创建与原图一致,类型为CV_8UC1或者CV_8UC3的全零图(即黑色图)。如mask = Mat::zeros(image.size(),CV_8UC1);
    4. 然后用rect类或者fillPoly()函数将原图中待处理的区域(感兴趣区域)置为1。
    5. */
    6. int Frontend::DetectFeatures(){
    7. cv::Mat mask(current_frame_->left_img_.size(),CV_8UC1, 255);
    8. //循环遍历当前帧上的左侧图像特征,并绘制边框
    9. for(auto feat : current_frame_->features_left_){
    10. /*
    11. void cv::rectangle(cv::InputOutputArray img, cv::Point pt1, cv::Point pt2,
    12. const cv::Scalar &color, int thickness = 1, int lineType = 8, int shift = 0)
    13. 绘制一个简单的、厚的或向上填充的矩形。函数cv::rectangle绘制一个矩形轮廓或填充矩形,其两个相对的角分别为pt1和pt2。
    14. position_.pt————————>关键点坐标
    15. inline cv::Point2f::Point_(float _x, float _y)------>关键点上下左右10距离的矩形,color为0,就是黑色填充满
    16. */
    17. cv::rectangle(mask,feat->position_.pt-cv::Point2f(10,10),feat->position_.pt+cv::Point2f(10,10),0,CV_FILLED);
    18. }
    19. //建立一个关键点的vector
    20. std::vectorkeypoints;
    21. //提取左图特征点
    22. /*
    23. virtual void cv::Feature2D::detect(cv::InputArray image, std::vector &keypoints, cv::InputArray mask = noArray())
    24. 重载:
    25. 检测图像(第一种变体)或图像集(第二种变体)中的关键点。
    26. 参数:
    27. image – 图像.
    28. keypoints – The detected keypoints. In the second variant of the method keypoints[i] is a set of keypoints detected in images[i] .
    29. 检测到的关键点。在该方法的第二种变体中,keypoints[i]是在图像[i]中检测到的一组关键点。
    30. mask – Mask specifying where to look for keypoints (optional). It must be a 8-bit integer matrix with non-zero values in the region of interest.
    31. 指定在何处查找关键点的掩码(可选)。它必须是一个8位整数矩阵,在感兴趣的区域中具有非零值。
    32. GFTT角点
    33. */
    34. gftt_->detect(current_frame_->left_img_,keypoints,mask);
    35. //关联current_frame_和kp,同时统计这两次检测到的特征点数量
    36. int cnt_detected = 0;
    37. for(auto &kp : keypoints){
    38. current_frame_->features_left_.push_back(
    39. Feature::Ptr(new Feature(current_frame_,kp))
    40. );
    41. cnt_detected++;
    42. }
    43. LOG(INFO) << "Detect " << cnt_detected << " new features";
    44. return cnt_detected;
    45. }

    FindFeaturesInRight() 函数:

    • 第一步:进行赋初值。如果当前特征点有在地图上有对应的点,那么将根据特征点的3D POSE和当前帧的位姿反求出特征点在当前帧的像素坐标。如果没有对应特征点,右目的特征点初值就是和左目一样。这样可以加快光流的计算速度同时可以一点程度上避免光流找到错误的点
    • 第二步:调用OpenCV中的LK光流法来追踪右目特征点的位置
    • 第三步:把匹配上的特征点 push_back 到当前帧的右目特征点里面去,没匹配上就放个空指针。
    • 最后统计一下匹配上的特征点数目。
    1. // 右目光流追踪
    2. int Frontend::FindFeaturesInRight(){
    3. //赋初值
    4. std::vectorkps_left,kps_right;
    5. // 这里把当前帧左目的特征点位置放到 kps_left 这个临时变量里面。
    6. // 如果当前特征点有在地图上有对应的点,那么将根据特征点的3D POSE和当前帧的位姿反求出特征点在当前帧的像素坐标。如果没有对应特征点,右目的特征点初值就是和左目一样。
    7. for(auto &kp : current_frame_->features_left_){
    8. kps_left.push_back(kp->position_.pt);
    9. auto mp =kp->map_point_.lock();//检查是否上锁
    10. // 如果当前特征点有在地图上有对应的点
    11. if (mp)
    12. {
    13. // use projected points as initial guess(使用投影点作为初始估计值)//tzy
    14. auto px=camera_right_->world2pixel(mp->Pos(),current_frame_->Pose());
    15. //存入右侧图像的关键点
    16. kps_right.push_back(cv::Point2f(px[0],px[1]));
    17. }
    18. //否则,使用左侧相机特征点坐标为初始值
    19. else{
    20. kps_right.push_back(kp->position_.pt);
    21. }
    22. }
    23. // 开始使用LK流来估计右侧图像中的点
    24. std::vector status;
    25. Mat error;
    26. //opencv自带的光流跟踪函数
    27. /*
    28. CV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg,
    29. InputArray prevPts, InputOutputArray nextPts,
    30. OutputArray status, OutputArray err,
    31. Size winSize = Size(21,21), int maxLevel = 3,
    32. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01),
    33. int flags = 0, double minEigThreshold = 1e-4 );
    34. Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids.
    35. */
    36. cv::calcOpticalFlowPyrLK(current_frame_->left_img_,
    37. current_frame_->right_img_, kps_left, kps_right,
    38. status, error,
    39. cv::Size(11, 11), 3,
    40. cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 30, 0.01),
    41. cv::OPTFLOW_USE_INITIAL_FLOW); // 最后一个参数flag,使用初始估计,存储在nextPts中;如果未设置标志,则将prevPts复制到nextPts并将其视为初始估计
    42. // 统计匹配上的特征点个数,并存储
    43. int num_good_pts;
    44. for (size_t i = 0; i < status.size(); ++i)
    45. {
    46. // 为真表示光流追踪成功
    47. if (status[i])
    48. {
    49. cv::KeyPoint kp(kps_right[i], 7); // 右目关键点的直径为7
    50. Feature::Ptr feat(new Feature(current_frame_, kp));
    51. feat->is_on_left_image_ = false;
    52. current_frame_->features_right_.push_back(feat);
    53. num_good_pts++;
    54. }
    55. else
    56. { // 光流追踪未成功,就放个空指针
    57. current_frame_->features_right_.push_back(nullptr);
    58. }
    59. }
    60. // 输出操作日志
    61. LOG(INFO) << "Find " << num_good_pts << " in the right image.";
    62. return num_good_pts; // 返回成功匹配的点对数量
    63. }

    BuildInitMap() 函数:

    首先,如果上一步光流追踪中匹配到的特征点数量大于num_features_init_(默认100个),才进行地图初始化:

    • 第一步:设置两个相机的位置,通过 VisualOdometry::Init() 函数,系统初始化的时候调用了 Frontend::SetCameras() 函数,然后在 Dataset::Init() 函数里面有对每个相机的pose进行实际的赋值。
    • 第二步:计算每个特征点在两个相机的平面的归一化坐标。
    • 第三步:使用 algorithm.h 文件中的 triangulation() 函数,来算这个特征点在世界坐标系下的3D 位置,(通过构建线性方程,然后SVD分解来计算特征点的位置)
    1. bool Frontend::BuildInitMap(){
    2. //设置左右两个相机的位置(获取pose)
    3. std::vectorposes{camera_left_->pose(),camera_right_->pose()};
    4. size_t cnt_init_landmarks= 0; //设置地图标志初始值
    5. //循环左侧图像特征点 (获取 特征点归一化坐标)
    6. for (size_t i = 0; i < current_frame_->features_left_.size(); ++i)
    7. {
    8. //判断右侧图像是否有对应特征点,有则继续向下执行,没有就continue
    9. if (current_frame_->features_right_[i]== nullptr) continue;
    10. // create map point from triangulation (开始获取三角化所需的 特征点归一化坐标)
    11. std::vectorpoints{
    12. camera_left_->pixel2camera(Vec2(current_frame_->features_left_[i]->position_.pt.x,current_frame_->features_left_[i]->position_.pt.y)),
    13. camera_right_->pixel2camera( Vec2(current_frame_->features_right_[i]->position_.pt.x,current_frame_->features_right_[i]->position_.pt.y))};
    14. //新建一个三维0矩阵
    15. Vec3 pworld =Vec3::Zero();
    16. // 尝试对每一对匹配点进行三角化
    17. /*
    18. inline bool myslam::triangulation(const std::vector &poses, std::vector points, Vec3 &pt_world)
    19. linear triangulation with SVD 线性三角测量
    20. 参数:
    21. poses – poses,
    22. points – points in normalized plane
    23. pt_world – triangulated point in the world
    24. 返回:
    25. true if success
    26. */
    27. if (triangulation(poses,points,pworld) &&pworld[2]>0)
    28. {
    29. //创建地图存储数据
    30. //创建一个新地图,用于信息更新
    31. auto new_map_point = MapPoint::CreateNewMappoint();
    32. new_map_point->SetPos(pworld);
    33. //将观测到的特征点加入新地图
    34. new_map_point->AddObservation(current_frame_->features_left_[i]);
    35. new_map_point->AddObservation(current_frame_->features_right_[i]);
    36. //当前帧的地图点指向新的地图点—>更新当前帧上的地图点
    37. current_frame_->features_left_[i]->map_point_ = new_map_point;
    38. current_frame_->features_right_[i]->map_point_ = new_map_point;
    39. //初始化地图点makr+1
    40. cnt_init_landmarks++;
    41. //在地图中插入当前新的更新点
    42. map_->InsertMapPoint(new_map_point);
    43. }
    44. }
    45. //把初始化的这一帧设置为关键帧
    46. current_frame_->SetKeyFrame();
    47. //在地图中插入关键帧
    48. map_->InsertKeyFrame(current_frame_);
    49. //后端更新地图(在后端更新)
    50. backend_->UpdateMap();
    51. //输出操作日志
    52. LOG(INFO) << "Initial map created with " << cnt_init_landmarks
    53. << " map points";
    54. //返回:单个图像构建初始地图成功
    55. return true;
    56. }

    其中triangulation() 三角化函数:

    实现的推导过程中可以看一下这篇博客里的SVD分解的部分

    1. // 通过构建线性方程,然后SVD分解来计算特征点的位置。
    2. /**
    3. * linear triangulation with SVD
    4. * @param poses poses,
    5. * @param points points in normalized plane
    6. * @param pt_world triangulated point in the world
    7. * @return true if success
    8. */
    9. inline bool triangulation(const std::vector &poses,
    10. const std::vector points, Vec3 &pt_world) {
    11. MatXX A(2 * poses.size(), 4);
    12. VecX b(2 * poses.size());
    13. b.setZero();
    14. for (size_t i = 0; i < poses.size(); ++i) {
    15. Mat34 m = poses[i].matrix3x4();
    16. A.block<1, 4>(2 * i, 0) = points[i][0] * m.row(2) - m.row(0);
    17. A.block<1, 4>(2 * i + 1, 0) = points[i][1] * m.row(2) - m.row(1);
    18. }
    19. // Eigen::ComputeThinU和Eigen::ComputeThinV是两个参数,用于指定只计算矩阵的前k个奇异向量,其中k是矩阵的秩。这样可以加快计算速度并减小内存占用
    20. auto svd = A.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV);
    21. /*
    22. 取SVD分解得到v矩阵的最有一列作为解:svd.matrixV().col(3)
    23. 深度值是svd.matrixV()(3, 3)
    24. head<3>() 是取前三个值
    25. */
    26. pt_world = (svd.matrixV().col(3) / svd.matrixV()(3, 3)).head<3>();
    27. if (svd.singularValues()[3] / svd.singularValues()[2] < 1e-2) {
    28. return true;
    29. }
    30. return false;// 解质量不好,放弃
    31. }

  • 相关阅读:
    CocosCreator | 2.3.3及后续版本浏览器无法断点和控制台不显示错误代码路径的解决方案(cocos代码报错无法定位的问题)
    C#:实现迪杰斯特拉算法​(附完整源码)
    Java版 招投标系统简介 招投标系统源码 java招投标系统 招投标系统功能设计
    Qt源码编译aarch等架构可参考
    家长杂志家长杂志社家长编辑部2022年第30期目录
    【开源】基于JAVA的服装店库存管理系统
    星期几(冬季每日一题 6)
    对称加密和非对称加密
    npm ERR! fatal: early EOF npm ERR! fatal: index-pack failed
    关于AM437x Linux+qt开发笔记(2)
  • 原文地址:https://blog.csdn.net/weixin_62952541/article/details/133172976