当前位置:   article > 正文

无人驾驶学习笔记 - A-LOAM 算法代码解析总结_a-loam 代码

a-loam 代码

目录

1、概述

2、scanRegistration.cpp

2.1、代码注释

2.1.1、主函数

2.1.2、removeClosedPointCloud(雷达周边过近点移除)

2.1.3 laserCloudHandler激光处理回调函数

2.2、总结概括

3、LaserOdometry.cpp

3.1、代码注释

3.2、总结概括

4、laserMapping.cpp

4.1、代码注释

4.2、总结概括

5、lidarFactor.cpp

6、参考连接


PS: 在看了loam的论文和代码以后,紧接着看了A-LOAM,核心算法没有太大变换,应用了ceres 替代了手推高斯推导,LOAM代码中大量的基于欧拉角转来转去的推导实在容易劝退众生。A-LOAM相对整体结构也更清楚,避免遗忘,将代码的学习总结于此。

该总结包括代码和文字总共有6万字左右,建议结合目录阅读,首先要熟悉loam Aloam 论文中核心的方法,然后可以先阅读每一部分的总结概括,有了认知以后再去每个节点的详细注释中学习

1、概述

A-LOAM 的运行节点关系图如下

         关于 A-LOAM 算法原理可以参考:  无人驾驶学习笔记 - LOAM 算法论文核心关键点总结_ppipp1109的博客-CSDN博客

本文总结主要从扫描匹配、低精度里程计、高精度建图三部分对应的函数讲解

2、scanRegistration.cpp

        scanRegistration.cpp用来读取激光雷达数据并且对激光雷达数据进行整理,去除无效点云以及激光雷达周围的点云,并且计算每一个点的曲率,按照提前设定好的曲率范围来分离出不同类型的点。

2.1、代码注释

2.1.1、主函数

  1. int main(int argc, char **argv)
  2. {
  3. ros::init(argc, argv, "scanRegistration");
  4. ros::NodeHandle nh;
  5. // 从配置文件中获取多少线的激光雷达
  6. nh.param<int>("scan_line", N_SCANS, 16);
  7. // 最小有效距离
  8. nh.param<double>("minimum_range", MINIMUM_RANGE, 0.1);
  9. printf("scan line number %d \n", N_SCANS);
  10. // 只有线束是16 32 64的才可以继续
  11. if(N_SCANS != 16 && N_SCANS != 32 && N_SCANS != 64)
  12. {
  13. printf("only support velodyne with 16, 32 or 64 scan line!");
  14. return 0;
  15. }
  16. ros::Subscriber subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>("/velodyne_points", 100, laserCloudHandler);
  17. pubLaserCloud = nh.advertise<sensor_msgs::PointCloud2>("/velodyne_cloud_2", 100);
  18. pubCornerPointsSharp = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_sharp", 100);
  19. pubCornerPointsLessSharp = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_less_sharp", 100);
  20. pubSurfPointsFlat = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_flat", 100);
  21. pubSurfPointsLessFlat = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_less_flat", 100);
  22. pubRemovePoints = nh.advertise<sensor_msgs::PointCloud2>("/laser_remove_points", 100);
  23. if(PUB_EACH_LINE)
  24. {
  25. for(int i = 0; i < N_SCANS; i++)
  26. {
  27. ros::Publisher tmp = nh.advertise<sensor_msgs::PointCloud2>("/laser_scanid_" + std::to_string(i), 100);
  28. pubEachScan.push_back(tmp);
  29. }
  30. }
  31. ros::spin();
  32. return 0;
  33. }

2.1.2、removeClosedPointCloud(雷达周边过近点移除)

  1. void removeClosedPointCloud(const pcl::PointCloud<PointT> &cloud_in,
  2. pcl::PointCloud<PointT> &cloud_out, float thres)
  3. {
  4. // 假如输入输出点云不使用同一个变量,则需要将输出点云的时间戳和容器大小与输入点云同步
  5. if (&cloud_in != &cloud_out)
  6. {
  7. cloud_out.header = cloud_in.header;
  8. cloud_out.points.resize(cloud_in.points.size());
  9. }
  10. size_t j = 0;
  11. // 把点云距离小于给定阈值的去除掉,也就是距离雷达过近的点去除
  12. for (size_t i = 0; i < cloud_in.points.size(); ++i)
  13. {
  14. if (cloud_in.points[i].x * cloud_in.points[i].x + cloud_in.points[i].y * cloud_in.points[i].y + cloud_in.points[i].z * cloud_in.points[i].z < thres * thres)
  15. continue;
  16. cloud_out.points[j] = cloud_in.points[i];
  17. j++;
  18. }
  19. if (j != cloud_in.points.size())
  20. {
  21. cloud_out.points.resize(j);
  22. }
  23. // 这里是对每条扫描线上的点云进行直通滤波,因此设置点云的高度为1,宽度为数量,稠密点云
  24. cloud_out.height = 1;
  25. cloud_out.width = static_cast<uint32_t>(j);
  26. cloud_out.is_dense = true;
  27. }

2.1.3 laserCloudHandler激光处理回调函数

预处理

  1. void laserCloudHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloudMsg)
  2. {
  3. // 如果系统没有初始化的话,就等几帧
  4. if (!systemInited)
  5. {
  6. systemInitCount++;
  7. if (systemInitCount >= systemDelay)
  8. {
  9. systemInited = true;
  10. }
  11. else
  12. return;
  13. }
  14. //作者自己设计的计时类,以构造函数为起始时间,以toc()函数为终止时间,并返回时间间隔(ms)
  15. TicToc t_whole;
  16. TicToc t_prepare;
  17. //每条扫描线上的可以计算曲率的点云点的起始索引和结束索引
  18. //分别用scanStartInd数组和scanEndInd数组记录
  19. std::vector<int> scanStartInd(N_SCANS, 0);
  20. std::vector<int> scanEndInd(N_SCANS, 0);
  21. pcl::PointCloud<pcl::PointXYZ> laserCloudIn;
  22. // 把点云从ros格式转到pcl的格式
  23. pcl::fromROSMsg(*laserCloudMsg, laserCloudIn);
  24. std::vector<int> indices;
  25. // 去除掉点云中的nan点
  26. pcl::removeNaNFromPointCloud(laserCloudIn, laserCloudIn, indices);
  27. // 去除距离小于阈值的点
  28. removeClosedPointCloud(laserCloudIn, laserCloudIn, MINIMUM_RANGE);

        计算点云角度范围,目的是求解点所在的扫描线,并通过论文中方法,对齐时间戳,根据时间占比求出所有点对应的角度范围。其中根据扫描范围在不同象限做了不同处理,考虑了扫描范围在二三象限时候,对角度进行加2pi将其约束到 -pi/2 - 3/2 * pi范围内。类似地如果扫描范围在一四象限,需要将结束点角度也减2pi。详细解释可参考下文的3.2.2节

A_LOAM源码解析1——scanRegistration - 知乎

  1. // 计算起始点和结束点的角度,由于激光雷达是顺时针旋转,这里取反就相当于转成了逆时针
  2. int cloudSize = laserCloudIn.points.size();
  3. float startOri = -atan2(laserCloudIn.points[0].y, laserCloudIn.points[0].x);
  4. // atan2范围是[-Pi,PI],这里加上2PI是为了保证起始到结束相差2PI符合实际
  5. float endOri = -atan2(laserCloudIn.points[cloudSize - 1].y,
  6. laserCloudIn.points[cloudSize - 1].x) +
  7. 2 * M_PI;
  8. // 通过上面的公式,endOri - startOri理应在pi~3pi之间
  9. // 正常情况下在这个范围内:pi < endOri - startOri < 3*pi,异常则修正
  10. // 如果出现了异常,不认为是扫描点本身的问题,而是公式先验地+2pi出了问题
  11. // 总有一些例外,比如这里大于3PI,和小于PI,就需要做一些调整到合理范围
  12. //扫描场在右半部分(一、四象限)的情况
  13. if (endOri - startOri > 3 * M_PI)
  14. {
  15. endOri -= 2 * M_PI;
  16. }
  17. //扫描场在左半部分(二、三象限)的情况
  18. else if (endOri - startOri < M_PI)
  19. {
  20. endOri += 2 * M_PI;
  21. }
  22. //printf("end Ori %f\n", endOri);

        对于每个点云点计算对应的扫描线,主要掌握其计算方法,实际现在的3d激光雷达驱动中都已经集成了每个点云点的线号、时间戳和角度等信息,不需要再单独计算。

  1. bool halfPassed = false;
  2. int count = cloudSize;
  3. PointType point;
  4. std::vector<pcl::PointCloud<PointType>> laserCloudScans(N_SCANS);
  5. // 遍历每一个点
  6. for (int i = 0; i < cloudSize; i++)
  7. {
  8. point.x = laserCloudIn.points[i].x;
  9. point.y = laserCloudIn.points[i].y;
  10. point.z = laserCloudIn.points[i].z;
  11. // 计算他的俯仰角
  12. // 计算垂直视场角,决定这个激光点所在的scanID
  13. // 通过计算垂直视场角确定激光点在哪个扫描线上(N_SCANS线激光雷达)
  14. float angle = atan(point.z / sqrt(point.x * point.x + point.y * point.y)) * 180 / M_PI;
  15. int scanID = 0;
  16. // 计算是第几根scan
  17. if (N_SCANS == 16)
  18. {
  19. // +-15°的垂直视场,垂直角度分辨率2°,-15°时的scanID = 0
  20. /*
  21. * 垂直视场角,可以算作每个点的
  22. * 如果是16线激光雷达,结算出的angle应该在-15~15之间
  23. */
  24. scanID = int((angle + 15) / 2 + 0.5);
  25. // scanID(0~15), 这些是无效的点,cloudSize--
  26. if (scanID > (N_SCANS - 1) || scanID < 0)
  27. {
  28. count--;
  29. continue;
  30. }
  31. }
  32. else if (N_SCANS == 32)
  33. {
  34. scanID = int((angle + 92.0/3.0) * 3.0 / 4.0);
  35. if (scanID > (N_SCANS - 1) || scanID < 0)
  36. {
  37. count--;
  38. continue;
  39. }
  40. }
  41. else if (N_SCANS == 64)
  42. {
  43. if (angle >= -8.83)
  44. scanID = int((2 - angle) * 3.0 + 0.5);
  45. else
  46. scanID = N_SCANS / 2 + int((-8.83 - angle) * 2.0 + 0.5);
  47. // use [0 50] > 50 remove outlies
  48. if (angle > 2 || angle < -24.33 || scanID > 50 || scanID < 0)
  49. {
  50. count--;
  51. continue;
  52. }
  53. }
  54. else
  55. {
  56. printf("wrong scan number\n");
  57. ROS_BREAK();
  58. }
  59. //printf("angle %f scanID %d \n", angle, scanID);
  60. // 计算水平角
  61. float ori = -atan2(point.y, point.x);
  62. // 根据扫描线是否旋转过半选择与起始位置还是终止位置进行差值计算,从而进行补偿
  63. /*
  64. * 如果此时扫描没有过半,则halfPassed为false
  65. */
  66. if (!halfPassed)
  67. {
  68. // 确保-PI / 2 < ori - startOri < 3 / 2 * PI
  69. //如果ori-startOri小于-0.5pi或大于1.5pi,则调整ori的角度
  70. if (ori < startOri - M_PI / 2)
  71. {
  72. // 在-pi与pi的断点处容易出这种问题
  73. ori += 2 * M_PI;
  74. }
  75. else if (ori > startOri + M_PI * 3 / 2)
  76. {
  77. ori -= 2 * M_PI;
  78. }
  79. // 如果超过180度,就说明过了一半了
  80. if (ori - startOri > M_PI)
  81. {
  82. halfPassed = true;
  83. }
  84. }
  85. else
  86. {
  87. // 确保-PI * 3 / 2 < ori - endOri < PI / 2
  88. ori += 2 * M_PI; // 先补偿2PI
  89. if (ori < endOri - M_PI * 3 / 2)
  90. {
  91. ori += 2 * M_PI;
  92. }
  93. else if (ori > endOri + M_PI / 2)
  94. {
  95. ori -= 2 * M_PI;
  96. }
  97. }
  98. // 角度的计算是为了计算相对的起始时刻的时间
  99. /*
  100. * relTime 是一个0~1之间的小数,代表占用扫描时间的比例,乘以扫描时间得到真实扫描时刻,
  101. * scanPeriod扫描时间默认为0.1s 100hz
  102. */
  103. float relTime = (ori - startOri) / (endOri - startOri);
  104. // 整数部分是scan的索引,小数部分是相对起始时刻的时间
  105. point.intensity = scanID + scanPeriod * relTime;
  106. // 根据scan的idx送入各自数组
  107. laserCloudScans[scanID].push_back(point);
  108. }
  109. // cloudSize是有效的点云的数目
  110. cloudSize = count;
  111. printf("points size %d \n", cloudSize);

接下来就是对雷达数据的特征提取,和论文中一致,分别提取角点和面点。主要思想是利用点云点的曲率来提取特征点。曲率是指一定范围内拟合出的圆的半径的倒数所以曲率大的为角点,曲率小的为面点。

        代码中的方法是,同一条扫描线上取目标点左右则各5个点,求均值。并与之作差。

  1. // 将每条扫描线上的点输入到laserCloud指向的点云,
  2. // 并记录好每条线上可以计算曲率的初始点和结束点的索引(在laserCloud中的索引)
  3. pcl::PointCloud<PointType>::Ptr laserCloud(new pcl::PointCloud<PointType>());
  4. // 全部集合到一个点云里面去,但是使用两个数组标记起始和结束,这里分别+5和-6是为了计算曲率方便
  5. for (int i = 0; i < N_SCANS; i++)
  6. {
  7. //5个点和后5个点都无法计算曲率,因为他们不满足左右两侧各有5个点
  8. scanStartInd[i] = laserCloud->size() + 5;
  9. *laserCloud += laserCloudScans[i];
  10. scanEndInd[i] = laserCloud->size() - 6;
  11. }
  12. // 将一帧无序点云转换成有序点云消耗的时间
  13. printf("prepare time %f \n", t_prepare.toc());
  14. // 计算每一个点的曲率,这里的laserCloud是有序的点云,故可以直接这样计算(论文中说对每条线扫scan计算曲率)
  15. // 但是在 每条scan的交界处 计算得到的曲率是不准确的,这可通过scanStartInd[i]、scanEndInd[i]来选取
  16. /*
  17. * 表面上除了前后五个点都应该有曲率,但是由于临近点都在扫描上选取,实际上每条扫描线上的前后五个点也不太准确,
  18. * 应该由scanStartInd[i]、scanEndInd[i]来确定范围
  19. */
  20. for (int i = 5; i < cloudSize - 5; i++)
  21. {
  22. float diffX = laserCloud->points[i - 5].x + laserCloud->points[i - 4].x + laserCloud->points[i - 3].x + laserCloud->points[i - 2].x + laserCloud->points[i - 1].x - 10 * laserCloud->points[i].x + laserCloud->points[i + 1].x + laserCloud->points[i + 2].x + laserCloud->points[i + 3].x + laserCloud->points[i + 4].x + laserCloud->points[i + 5].x;
  23. float diffY = laserCloud->points[i - 5].y + laserCloud->points[i - 4].y + laserCloud->points[i - 3].y + laserCloud->points[i - 2].y + laserCloud->points[i - 1].y - 10 * laserCloud->points[i].y + laserCloud->points[i + 1].y + laserCloud->points[i + 2].y + laserCloud->points[i + 3].y + laserCloud->points[i + 4].y + laserCloud->points[i + 5].y;
  24. float diffZ = laserCloud->points[i - 5].z + laserCloud->points[i - 4].z + laserCloud->points[i - 3].z + laserCloud->points[i - 2].z + laserCloud->points[i - 1].z - 10 * laserCloud->points[i].z + laserCloud->points[i + 1].z + laserCloud->points[i + 2].z + laserCloud->points[i + 3].z + laserCloud->points[i + 4].z + laserCloud->points[i + 5].z;
  25. // 存储曲率,索引
  26. // 对应论文中的公式(1),但是没有进行除法
  27. cloudCurvature[i] = diffX * diffX + diffY * diffY + diffZ * diffZ;
  28. /*
  29. * cloudSortInd[i] = i相当于所有点的初始自然序列,从此以后,每个点就有了它自己的序号(索引)
  30. * 对于每个点,我们已经选择了它附近的特征点数量初始化为0
  31. * 每个点的点类型初始设置为0(次极小平面点)
  32. */
  33. cloudSortInd[i] = i;
  34. cloudNeighborPicked[i] = 0;
  35. cloudLabel[i] = 0;
  36. }

提取特征需要注意几条原则:

1、为了提高效率,论文中对每条扫描线分成了4个扇形,而代码中实际是分成了6份,在每份中寻找曲率最大的20个点最为极大角点,对提取数据做了约束,最大点不大于2个,极小面点不大于4个,剩下的编辑未次极小面点;

2、为防止特征点过于集中,每提取一个特征点,就对该点和它附近的点的标志位设置未“已选中”,在循环提取时会跳过已提取的特征点,对于次极小面点采取下采样方式避免特征点扎堆。

  1. pcl::PointCloud<PointType> cornerPointsSharp; // 极大边线点
  2. pcl::PointCloud<PointType> cornerPointsLessSharp; // 次极大边线点
  3. pcl::PointCloud<PointType> surfPointsFlat; // 极小平面点
  4. pcl::PointCloud<PointType> surfPointsLessFlat; // 次极小平面点(经过降采样)
  5. // 对每条线扫scan进行操作(曲率排序,选取对应特征点)
  6. float t_q_sort = 0; // 用来记录排序花费的总时间
  7. // 遍历每个scan
  8. for (int i = 0; i < N_SCANS; i++)
  9. {
  10. /// 如果最后一个可算曲率的点与第一个的差小于6,说明无法分成6个扇区,跳过
  11. if( scanEndInd[i] - scanStartInd[i] < 6)
  12. continue;
  13. // 用来存储不太平整的点
  14. pcl::PointCloud<PointType>::Ptr surfPointsLessFlatScan(new pcl::PointCloud<PointType>);
  15. // 将每个scan等分成6等分
  16. for (int j = 0; j < 6; j++)
  17. {
  18. // 每个等分的起始和结束点
  19. int sp = scanStartInd[i] + (scanEndInd[i] - scanStartInd[i]) * j / 6;
  20. int ep = scanStartInd[i] + (scanEndInd[i] - scanStartInd[i]) * (j + 1) / 6 - 1;
  21. TicToc t_tmp;
  22. // 对点云按照曲率进行排序,小的在前,大的在后
  23. std::sort (cloudSortInd + sp, cloudSortInd + ep + 1, comp);
  24. // t_q_sort累计每个扇区曲率排序时间总和
  25. t_q_sort += t_tmp.toc();
  26. // 选取极大边线点(2个)和次极大边线点(20个)
  27. int largestPickedNum = 0;
  28. // 从最大曲率往最小曲率遍历,寻找边线点,并要求大于0.1
  29. for (int k = ep; k >= sp; k--)
  30. {
  31. // 排序后顺序就乱了,这个时候索引的作用就体现出来了
  32. // 取出点的索引
  33. int ind = cloudSortInd[k];
  34. // 看看这个点是否是有效点,同时曲率是否大于阈值
  35. // 没被选过 && 曲率 > 0.1
  36. if (cloudNeighborPicked[ind] == 0 &&
  37. cloudCurvature[ind] > 0.1)
  38. {
  39. largestPickedNum++;
  40. // 每段选2个曲率大的点
  41. if (largestPickedNum <= 2)
  42. {
  43. // label为2是曲率大的标记
  44. cloudLabel[ind] = 2;
  45. // cornerPointsSharp存放大曲率的点
  46. // 既放入极大边线点容器,也放入次极大边线点容器
  47. cornerPointsSharp.push_back(laserCloud->points[ind]);
  48. cornerPointsLessSharp.push_back(laserCloud->points[ind]);
  49. }
  50. // 以及20个曲率稍微大一些的点
  51. else if (largestPickedNum <= 20)
  52. {
  53. // label置1表示曲率稍微大
  54. // 超过2个选择点以后,设置为次极大边线点,仅放入次极大边线点容器
  55. cloudLabel[ind] = 1;
  56. cornerPointsLessSharp.push_back(laserCloud->points[ind]);
  57. }
  58. // 超过20个就算了
  59. else
  60. {
  61. break;
  62. }
  63. // 这个点被选中后 pick标志位置1
  64. cloudNeighborPicked[ind] = 1;
  65. // 为了保证特征点不过度集中,将选中的点周围5个点都置1,避免后续会选到
  66. // ID为ind的特征点的相邻scan点距离的平方 <= 0.05的点标记为选择过,避免特征点密集分布
  67. // 右侧
  68. for (int l = 1; l <= 5; l++)
  69. {
  70. // 查看相邻点距离是否差异过大,如果差异过大说明点云在此不连续,是特征边缘,就会是新的特征,因此就不置位了
  71. float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l - 1].x;
  72. float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l - 1].y;
  73. float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l - 1].z;
  74. if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05)
  75. {
  76. break;
  77. }
  78. cloudNeighborPicked[ind + l] = 1;
  79. }
  80. //左侧 同理
  81. for (int l = -1; l >= -5; l--)
  82. {
  83. float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l + 1].x;
  84. float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l + 1].y;
  85. float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l + 1].z;
  86. if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05)
  87. {
  88. break;
  89. }
  90. cloudNeighborPicked[ind + l] = 1;
  91. }
  92. }
  93. }
  94. // 下面开始挑选面点(4个)
  95. int smallestPickedNum = 0;
  96. for (int k = sp; k <= ep; k++)
  97. {
  98. int ind = cloudSortInd[k];
  99. // 确保这个点没有被pick且曲率小于阈值
  100. if (cloudNeighborPicked[ind] == 0 &&
  101. cloudCurvature[ind] < 0.1)
  102. {
  103. // -1认为是平坦的点
  104. cloudLabel[ind] = -1;
  105. surfPointsFlat.push_back(laserCloud->points[ind]);
  106. smallestPickedNum++;
  107. // 这里不区分平坦和比较平坦,因为剩下的点label默认是0,就是比较平坦
  108. if (smallestPickedNum >= 4)
  109. {
  110. break;
  111. }
  112. // 同样距离 < 0.05的点全设为已经选择过
  113. cloudNeighborPicked[ind] = 1;
  114. for (int l = 1; l <= 5; l++)
  115. {
  116. float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l - 1].x;
  117. float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l - 1].y;
  118. float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l - 1].z;
  119. if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05)
  120. {
  121. break;
  122. }
  123. cloudNeighborPicked[ind + l] = 1;
  124. }
  125. for (int l = -1; l >= -5; l--)
  126. {
  127. float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l + 1].x;
  128. float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l + 1].y;
  129. float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l + 1].z;
  130. if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05)
  131. {
  132. break;
  133. }
  134. cloudNeighborPicked[ind + l] = 1;
  135. }
  136. }
  137. }
  138. // 选取次极小平面点,除了极大平面点、次极大平面点,剩下的都是次极小平面点
  139. for (int k = sp; k <= ep; k++)
  140. {
  141. // 这里可以看到,剩下来的点都是一般平坦,这个也符合实际
  142. if (cloudLabel[k] <= 0)
  143. {
  144. surfPointsLessFlatScan->push_back(laserCloud->points[k]);
  145. }
  146. }
  147. }
  148. // 对每一条scan线上的次极小平面点进行一次降采样
  149. pcl::PointCloud<PointType> surfPointsLessFlatScanDS;
  150. pcl::VoxelGrid<PointType> downSizeFilter;
  151. // 一般平坦的点比较多,所以这里做一个体素滤波
  152. downSizeFilter.setInputCloud(surfPointsLessFlatScan);
  153. downSizeFilter.setLeafSize(0.2, 0.2, 0.2);
  154. downSizeFilter.filter(surfPointsLessFlatScanDS);
  155. surfPointsLessFlat += surfPointsLessFlatScanDS;
  156. }
  157. printf("sort q time %f \n", t_q_sort);
  158. printf("seperate points time %f \n", t_pts.toc());

接下来就是对当前点云、四种特征点云进行 打包发布,不再赘述,目的是给laserodometry 通信,将预处理的数据传递给里程计节点。

2.2、总结概括

该部分代码主要工作就是处理无效点云,计算点云线束和对齐时间戳,计算曲率、并提取特征点。

总体处理流程,下面博主流程图总结的很好,不再单独整理了,借鉴于此

SLAM前端入门框架-A_LOAM源码解析 - 知乎

        上述流程图应该已经很清楚的表明这个scanRegistration文件的执行流程。可能会存在几个关键问题,在下面具体展开一下。
关于步骤2和步骤3中去除无效点云和自身点云应该是很正常的流程
步骤4计算这一帧起始角度和终止角度是为了构建一个“整体”,下面就可以通过这个点和初始角度的偏差来计算,这个点到底在这一帧内部进行了多久的运动,并且将这个时间存储起来,从而进行雷达去畸变。(具体什么是雷达去畸变可以参考LOAM中的论文)
步骤5,计算出每一个点对应的线束,并且重新组织,是为了下面计算曲率使用。
计算方式是通过同一条线上的角度相同。利用atan(z/(sqr(x*x+y*x))来计算。(具体的线束分布需要按照不同的激光雷达给出的说明手册)
步骤6,利用论文中给出的公式来计算(只能说是大体上是),代码中做了一些改变。
步骤7,人为给定一个阈值(0.1),将每一条扫描线分为六段,目的是不能让特征过于集中,每一段计算曲率大于阈值的点(少量 2个),大于阈值的点(多量 20个),小于阈值的点(4个),其他所有没有被选中的点。在这个过程中,如果一个个点被选中了,就立刻标记周围五个距离小于0.05的点,目的也是防止特征过于集中。

3、LaserOdometry.cpp

        laserOdometry.cpp主要是通过读取scanRegistration.cpp中的信息来计算帧与帧之间的变化,最终得到里程计坐标系下的激光雷达的位姿。也就是前端激光里程计和位姿粗估计,帧间匹配应用scan-scan 思想

3.1、代码注释

主函数 定义订阅点云数据的话题与发布里程计的角点面点,以及里程计等

  1. int main(int argc, char **argv)
  2. {
  3. ros::init(argc, argv, "laserOdometry");
  4. ros::NodeHandle nh;
  5. nh.param<int>("mapping_skip_frame", skipFrameNum, 2);
  6. printf("Mapping %d Hz \n", 10 / skipFrameNum);
  7. // 订阅提取出来的点云
  8. // 极大边线点 次极大边线点 极小平面点 次极小平面点
  9. ros::Subscriber subCornerPointsSharp = nh.subscribe<sensor_msgs::PointCloud2>("/laser_cloud_sharp", 100, laserCloudSharpHandler);
  10. ros::Subscriber subCornerPointsLessSharp = nh.subscribe<sensor_msgs::PointCloud2>("/laser_cloud_less_sharp", 100, laserCloudLessSharpHandler);
  11. ros::Subscriber subSurfPointsFlat = nh.subscribe<sensor_msgs::PointCloud2>("/laser_cloud_flat", 100, laserCloudFlatHandler);
  12. ros::Subscriber subSurfPointsLessFlat = nh.subscribe<sensor_msgs::PointCloud2>("/laser_cloud_less_flat", 100, laserCloudLessFlatHandler);
  13. //全部点点云
  14. ros::Subscriber subLaserCloudFullRes = nh.subscribe<sensor_msgs::PointCloud2>("/velodyne_cloud_2", 100, laserCloudFullResHandler);
  15. // 发布上一帧的边线点
  16. ros::Publisher pubLaserCloudCornerLast = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_corner_last", 100);
  17. // 发布上一帧的平面点
  18. ros::Publisher pubLaserCloudSurfLast = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_surf_last", 100);
  19. // 发布全部有序点云,就是从scanRegistration订阅来的点云,未经其他处理
  20. ros::Publisher pubLaserCloudFullRes = nh.advertise<sensor_msgs::PointCloud2>("/velodyne_cloud_3", 100);
  21. // 发布帧间的位姿变换
  22. ros::Publisher pubLaserOdometry = nh.advertise<nav_msgs::Odometry>("/laser_odom_to_init", 100);
  23. // 发布帧间的平移运动
  24. ros::Publisher pubLaserPath = nh.advertise<nav_msgs::Path>("/laser_odom_path", 100);
  25. nav_msgs::Path laserPath;
  26. int frameCount = 0;
  27. ros::Rate rate(100);
  28. while (ros::ok())
  29. {
  30. ros::spinOnce();
  31. //........
  32. rate.sleep();
  33. }
  34. return 0;
  35. }

主函数中的主循环未10HZ的高频周期,主要是帧间匹配。

预处理 取出需要的点云数据转化为pcl格式

  1. while (ros::ok())
  2. {
  3. ros::spinOnce(); // 触发一次回调,参考https://www.cnblogs.com/liu-fa/p/5925381.html
  4. // 首先确保订阅的五个消息都有,有一个队列为空都不行
  5. if (!cornerSharpBuf.empty() && !cornerLessSharpBuf.empty() &&
  6. !surfFlatBuf.empty() && !surfLessFlatBuf.empty() &&
  7. !fullPointsBuf.empty())
  8. {
  9. // 分别求出队列第一个时间
  10. timeCornerPointsSharp = cornerSharpBuf.front()->header.stamp.toSec();
  11. timeCornerPointsLessSharp = cornerLessSharpBuf.front()->header.stamp.toSec();
  12. timeSurfPointsFlat = surfFlatBuf.front()->header.stamp.toSec();
  13. timeSurfPointsLessFlat = surfLessFlatBuf.front()->header.stamp.toSec();
  14. timeLaserCloudFullRes = fullPointsBuf.front()->header.stamp.toSec();
  15. // 因为同一帧的时间戳都是相同的,因此这里比较是否是同一帧
  16. //比较时间是否同步
  17. if (timeCornerPointsSharp != timeLaserCloudFullRes ||
  18. timeCornerPointsLessSharp != timeLaserCloudFullRes ||
  19. timeSurfPointsFlat != timeLaserCloudFullRes ||
  20. timeSurfPointsLessFlat != timeLaserCloudFullRes)
  21. {
  22. printf("unsync messeage!");
  23. ROS_BREAK();
  24. }
  25. // 分别将五个点云消息取出来,同时转成pcl的点云格式
  26. mBuf.lock();
  27. cornerPointsSharp->clear();
  28. pcl::fromROSMsg(*cornerSharpBuf.front(), *cornerPointsSharp);
  29. cornerSharpBuf.pop();
  30. cornerPointsLessSharp->clear();
  31. pcl::fromROSMsg(*cornerLessSharpBuf.front(), *cornerPointsLessSharp);
  32. cornerLessSharpBuf.pop();
  33. surfPointsFlat->clear();
  34. pcl::fromROSMsg(*surfFlatBuf.front(), *surfPointsFlat);
  35. surfFlatBuf.pop();
  36. surfPointsLessFlat->clear();
  37. pcl::fromROSMsg(*surfLessFlatBuf.front(), *surfPointsLessFlat);
  38. surfLessFlatBuf.pop();
  39. laserCloudFullRes->clear();
  40. pcl::fromROSMsg(*fullPointsBuf.front(), *laserCloudFullRes);
  41. fullPointsBuf.pop();
  42. mBuf.unlock();
  43. TicToc t_whole;
  44. // initializing
  45. // 一个什么也不干的初始化
  46. if (!systemInited)
  47. {
  48. // 主要用来跳过第一帧数据
  49. // 仅仅将cornerPointsLessSharp保存至laserCloudCornerLast
  50. // 将surfPointsLessFlat保存至laserCloudSurfLast,以及更新对应的kdtree
  51. systemInited = true;
  52. std::cout << "Initialization finished \n";
  53. }
  54. else
  55. {
  56. // 极大边线点的数量
  57. int cornerPointsSharpNum = cornerPointsSharp->points.size();
  58. // 极小平面点的数量
  59. int surfPointsFlatNum = surfPointsFlat->points.size();
  60. TicToc t_opt;
  61. // 点到线以及点到面的非线性优化,迭代2次(选择当前优化的位姿的特征点匹配,并优化位姿(4次迭代),
  62. //然后重新选择特征点匹配并优化)
  63. for (size_t opti_counter = 0; opti_counter < 2; ++opti_counter)
  64. {
  65. corner_correspondence = 0;
  66. plane_correspondence = 0;
  67. //ceres::LossFunction *loss_function = NULL;
  68. // 使用Huber核函数来减少外点的影响,Algorithm 1: Lidar Odometry中有
  69. // 定义一下ceres的核函数
  70. ceres::LossFunction *loss_function = new ceres::HuberLoss(0.1);
  71. // 由于旋转不满足一般意义的加法,因此这里使用ceres自带的local param
  72. ceres::LocalParameterization *q_parameterization =
  73. new ceres::EigenQuaternionParameterization();
  74. ceres::Problem::Options problem_options;
  75. ceres::Problem problem(problem_options);
  76. // 待优化的变量是帧间位姿,平移和旋转,这里旋转使用四元数来表示
  77. problem.AddParameterBlock(para_q, 4, q_parameterization);
  78. problem.AddParameterBlock(para_t, 3);
  79. pcl::PointXYZI pointSel;
  80. std::vector<int> pointSearchInd;
  81. std::vector<float> pointSearchSqDis;
  82. TicToc t_data;

        分别通过两次迭代计算点线和面线之间的关系,并创建KD-tree。其中点线基于最近邻原理建立corner特征点(边线点)之间的关联,每一个极大边线点去上一帧的次极大边线点中找匹配;采用边线点匹配方法:假如在第k+1帧中发现了边线点i,通过KD-tree查询在第k帧中的最近邻点j,查询j的附近扫描线上的最近邻点l,j与l相连形成一条直线l-j,让点i与这条直线的距离最短。

构建一个非线性优化问题:以点i与直线lj的距离为代价函数,以位姿变换T(四元数表示旋转+位移t)为优化变量。下面是优化的程序。

  1. // find correspondence for corner features
  2. // 寻找角点的约束
  3. // 基于最近邻原理建立corner特征点之间关联,每一个极大边线点去上一帧的次极大边线点集中找匹配
  4. for (int i = 0; i < cornerPointsSharpNum; ++i)
  5. {
  6. // 运动补偿
  7. // 这个函数类似论文中公式(5)的功能
  8. // 将当前帧的极大边线点(记为点O_cur),变换到上一帧Lidar坐标系(记为点O),以利于寻找极大边线点的correspondence
  9. TransformToStart(&(cornerPointsSharp->points[i]), &pointSel);
  10. // 在上一帧所有角点构成的kdtree中寻找距离当前帧最近的一个点
  11. kdtreeCornerLast->nearestKSearch(pointSel, 1, pointSearchInd, pointSearchSqDis);
  12. int closestPointInd = -1, minPointInd2 = -1;
  13. // 只有小于给定门限才认为是有效约束
  14. if (pointSearchSqDis[0] < DISTANCE_SQ_THRESHOLD)
  15. {
  16. closestPointInd = pointSearchInd[0]; // 对应的最近距离的索引取出来
  17. // 找到其所在线束id,线束信息藏在intensity的整数部分
  18. int closestPointScanID = int(laserCloudCornerLast->points[closestPointInd].intensity);
  19. double minPointSqDis2 = DISTANCE_SQ_THRESHOLD;
  20. // search in the direction of increasing scan line
  21. // 寻找角点,在刚刚角点id上下分别继续寻找,目的是找到最近的角点,由于其按照线束进行排序,所以就是向上找
  22. for (int j = closestPointInd + 1; j < (int)laserCloudCornerLast->points.size(); ++j)
  23. {
  24. // if in the same scan line, continue
  25. // 不找同一根线束的
  26. if (int(laserCloudCornerLast->points[j].intensity) <= closestPointScanID)
  27. continue;
  28. // if not in nearby scans, end the loop
  29. // 要求找到的线束距离当前线束不能太远
  30. if (int(laserCloudCornerLast->points[j].intensity) > (closestPointScanID + NEARBY_SCAN))
  31. break;
  32. // 计算和当前找到的角点之间的距离
  33. double pointSqDis = (laserCloudCornerLast->points[j].x - pointSel.x) *
  34. (laserCloudCornerLast->points[j].x - pointSel.x) +
  35. (laserCloudCornerLast->points[j].y - pointSel.y) *
  36. (laserCloudCornerLast->points[j].y - pointSel.y) +
  37. (laserCloudCornerLast->points[j].z - pointSel.z) *
  38. (laserCloudCornerLast->points[j].z - pointSel.z);
  39. // 寻找距离最小的角点及其索引
  40. if (pointSqDis < minPointSqDis2)
  41. {
  42. // find nearer point
  43. // 记录其索引
  44. minPointSqDis2 = pointSqDis;
  45. minPointInd2 = j;
  46. }
  47. }
  48. // search in the direction of decreasing scan line
  49. // 同样另一个方向寻找对应角点
  50. for (int j = closestPointInd - 1; j >= 0; --j)
  51. {
  52. // if in the same scan line, continue
  53. if (int(laserCloudCornerLast->points[j].intensity) >= closestPointScanID)
  54. continue;
  55. // if not in nearby scans, end the loop
  56. if (int(laserCloudCornerLast->points[j].intensity) < (closestPointScanID - NEARBY_SCAN))
  57. break;
  58. double pointSqDis = (laserCloudCornerLast->points[j].x - pointSel.x) *
  59. (laserCloudCornerLast->points[j].x - pointSel.x) +
  60. (laserCloudCornerLast->points[j].y - pointSel.y) *
  61. (laserCloudCornerLast->points[j].y - pointSel.y) +
  62. (laserCloudCornerLast->points[j].z - pointSel.z) *
  63. (laserCloudCornerLast->points[j].z - pointSel.z);
  64. if (pointSqDis < minPointSqDis2)
  65. {
  66. // find nearer point
  67. minPointSqDis2 = pointSqDis;
  68. minPointInd2 = j;
  69. }
  70. }
  71. }
  72. // 如果这个角点是有效的角点
  73. // 即特征点i的两个最近邻点j和m都有效,构建非线性优化问题
  74. if (minPointInd2 >= 0) // both closestPointInd and minPointInd2 is valid
  75. {
  76. // 取出当前点和上一帧的两个角点
  77. Eigen::Vector3d curr_point(cornerPointsSharp->points[i].x,
  78. cornerPointsSharp->points[i].y,
  79. cornerPointsSharp->points[i].z);
  80. Eigen::Vector3d last_point_a(laserCloudCornerLast->points[closestPointInd].x,
  81. laserCloudCornerLast->points[closestPointInd].y,
  82. laserCloudCornerLast->points[closestPointInd].z);
  83. Eigen::Vector3d last_point_b(laserCloudCornerLast->points[minPointInd2].x,
  84. laserCloudCornerLast->points[minPointInd2].y,
  85. laserCloudCornerLast->points[minPointInd2].z);
  86. double s;
  87. if (DISTORTION)
  88. s = (cornerPointsSharp->points[i].intensity - int(cornerPointsSharp->points[i].intensity)) / SCAN_PERIOD;
  89. else
  90. s = 1.0;
  91. ceres::CostFunction *cost_function = LidarEdgeFactor::Create(curr_point, last_point_a, last_point_b, s);
  92. problem.AddResidualBlock(cost_function, loss_function, para_q, para_t);
  93. corner_correspondence++;
  94. }
  95. }

        下面采用平面点匹配方法:假如在第k+1帧中发现了平面点i,通过KD-tree查询在第k帧(上一帧)中的最近邻点j,查询j的附近扫描线上的最近邻点l和同一条扫描线的最近邻点m,这三点确定一个平面,让点i与这个平面的距离最短;

构建一个非线性优化问题:以点i与平面lmj的距离为代价函数,以位姿变换T(四元数表示旋转+t)为优化变量。

  1. // find correspondence for plane features
  2. // 与上述类似,寻找平面点的最近邻点j,l,m
  3. for (int i = 0; i < surfPointsFlatNum; ++i)
  4. {
  5. // 这个函数类似论文中公式(5)的功能
  6. // 将当前帧的极大边线点(记为点O_cur),变换到上一帧Lidar坐标系(记为点O),以利于寻找极大边线点的correspondence
  7. TransformToStart(&(surfPointsFlat->points[i]), &pointSel);
  8. // 先寻找上一帧距离这个面点最近的面点
  9. kdtreeSurfLast->nearestKSearch(pointSel, 1, pointSearchInd, pointSearchSqDis);
  10. int closestPointInd = -1, minPointInd2 = -1, minPointInd3 = -1;
  11. // 距离必须小于给定阈值
  12. if (pointSearchSqDis[0] < DISTANCE_SQ_THRESHOLD)
  13. {
  14. // 取出找到的上一帧面点的索引
  15. closestPointInd = pointSearchInd[0];
  16. // get closest point's scan ID
  17. // 取出最近的面点在上一帧的第几根scan上面
  18. int closestPointScanID = int(laserCloudSurfLast->points[closestPointInd].intensity);
  19. double minPointSqDis2 = DISTANCE_SQ_THRESHOLD, minPointSqDis3 = DISTANCE_SQ_THRESHOLD;
  20. // 额外在寻找两个点,要求,一个点和最近点同一个scan,另一个是不同scan
  21. // search in the direction of increasing scan line
  22. // 按照增量方向寻找其他面点
  23. for (int j = closestPointInd + 1; j < (int)laserCloudSurfLast->points.size(); ++j)
  24. {
  25. // if not in nearby scans, end the loop
  26. // 不能和当前找到的上一帧面点线束距离太远
  27. if (int(laserCloudSurfLast->points[j].intensity) > (closestPointScanID + NEARBY_SCAN))
  28. break;
  29. // 计算和当前帧该点距离
  30. double pointSqDis = (laserCloudSurfLast->points[j].x - pointSel.x) *
  31. (laserCloudSurfLast->points[j].x - pointSel.x) +
  32. (laserCloudSurfLast->points[j].y - pointSel.y) *
  33. (laserCloudSurfLast->points[j].y - pointSel.y) +
  34. (laserCloudSurfLast->points[j].z - pointSel.z) *
  35. (laserCloudSurfLast->points[j].z - pointSel.z);
  36. // if in the same or lower scan line
  37. // 如果是同一根scan且距离最近
  38. if (int(laserCloudSurfLast->points[j].intensity) <= closestPointScanID && pointSqDis < minPointSqDis2)
  39. {
  40. minPointSqDis2 = pointSqDis;
  41. minPointInd2 = j;
  42. }
  43. // if in the higher scan line
  44. // 如果是其他线束点
  45. else if (int(laserCloudSurfLast->points[j].intensity) > closestPointScanID && pointSqDis < minPointSqDis3)
  46. {
  47. minPointSqDis3 = pointSqDis;
  48. minPointInd3 = j;
  49. }
  50. }
  51. // search in the direction of decreasing scan line
  52. // 同样的方式,去按照降序方向寻找这两个点
  53. for (int j = closestPointInd - 1; j >= 0; --j)
  54. {
  55. // if not in nearby scans, end the loop
  56. if (int(laserCloudSurfLast->points[j].intensity) < (closestPointScanID - NEARBY_SCAN))
  57. break;
  58. double pointSqDis = (laserCloudSurfLast->points[j].x - pointSel.x) *
  59. (laserCloudSurfLast->points[j].x - pointSel.x) +
  60. (laserCloudSurfLast->points[j].y - pointSel.y) *
  61. (laserCloudSurfLast->points[j].y - pointSel.y) +
  62. (laserCloudSurfLast->points[j].z - pointSel.z) *
  63. (laserCloudSurfLast->points[j].z - pointSel.z);
  64. // if in the same or higher scan line
  65. if (int(laserCloudSurfLast->points[j].intensity) >= closestPointScanID && pointSqDis < minPointSqDis2)
  66. {
  67. minPointSqDis2 = pointSqDis;
  68. minPointInd2 = j;
  69. }
  70. else if (int(laserCloudSurfLast->points[j].intensity) < closestPointScanID && pointSqDis < minPointSqDis3)
  71. {
  72. // find nearer point
  73. minPointSqDis3 = pointSqDis;
  74. minPointInd3 = j;
  75. }
  76. }
  77. // 如果另外找到的两个点是有效点,就取出他们的3d坐标
  78. if (minPointInd2 >= 0 && minPointInd3 >= 0)
  79. {
  80. Eigen::Vector3d curr_point(surfPointsFlat->points[i].x,
  81. surfPointsFlat->points[i].y,
  82. surfPointsFlat->points[i].z);
  83. Eigen::Vector3d last_point_a(laserCloudSurfLast->points[closestPointInd].x,
  84. laserCloudSurfLast->points[closestPointInd].y,
  85. laserCloudSurfLast->points[closestPointInd].z);
  86. Eigen::Vector3d last_point_b(laserCloudSurfLast->points[minPointInd2].x,
  87. laserCloudSurfLast->points[minPointInd2].y,
  88. laserCloudSurfLast->points[minPointInd2].z);
  89. Eigen::Vector3d last_point_c(laserCloudSurfLast->points[minPointInd3].x,
  90. laserCloudSurfLast->points[minPointInd3].y,
  91. laserCloudSurfLast->points[minPointInd3].z);
  92. double s;
  93. if (DISTORTION)
  94. s = (surfPointsFlat->points[i].intensity - int(surfPointsFlat->points[i].intensity)) / SCAN_PERIOD;
  95. else
  96. s = 1.0;
  97. // 构建点到面的约束
  98. ceres::CostFunction *cost_function = LidarPlaneFactor::Create(curr_point, last_point_a, last_point_b, last_point_c, s);
  99. problem.AddResidualBlock(cost_function, loss_function, para_q, para_t);
  100. plane_correspondence++;
  101. }
  102. }
  103. }

应用ceres 构建求解器:

  1. printf("data association time %f ms \n", t_data.toc());
  2. // 如果总的约束太少,就打印一下
  3. if ((corner_correspondence + plane_correspondence) < 10)
  4. {
  5. printf("less correspondence! *************************************************\n");
  6. }
  7. // 调用ceres求解器求解
  8. TicToc t_solver;
  9. ceres::Solver::Options options;
  10. options.linear_solver_type = ceres::DENSE_QR;
  11. options.max_num_iterations = 4;
  12. options.minimizer_progress_to_stdout = false;
  13. ceres::Solver::Summary summary;
  14. ceres::Solve(options, &problem, &summary);
  15. printf("solver time %f ms \n", t_solver.toc());
  16. }
  17. printf("optimization twice time %f \n", t_opt.toc());
  18. // 这里的w_curr 实际上是 w_last
  19. t_w_curr = t_w_curr + q_w_curr * t_last_curr;
  20. q_w_curr = q_w_curr * q_last_curr;
  21. }

里程计数据打包与发布比较简单不再赘述,其中值得注意的是需要降频发给后端。

在求点到线和点到面函数中需要对点云数据就行运动补偿以去除运动畸变带来的估计误差,

运动补偿畸变函数LOAM假设激光雷达的运动为匀速模型,虽然实际中并不完全匹配,但是实际使用效果也基本没有问题。

常用的做法是补偿到起始时刻,如果有IMU,我们通过IMU得到的雷达高频位姿,可以求出每个点相对起始点的位姿,就可以补偿回去。

如果没有IMU,我们可以使用匀速模型假设,使⽤上⼀个帧间⾥程记的结果作为当前两帧之间的运动,假设当前帧也是匀速运动,可以估计出每个点相对起始时刻的位姿。

最后,当前点云中的点相对第一个点去除因运动产生的畸变,效果相当于静止扫描得到的点云。下面是去除运动畸变的函数。

  1. / undistort lidar point
  2. void TransformToStart(PointType const *const pi, PointType *const po)
  3. {
  4. //interpolation ratio
  5. double s;
  6. // 由于kitti数据集上的lidar已经做过了运动补偿,因此这里就不做具体补偿了
  7. if (DISTORTION)
  8. s = (pi->intensity - int(pi->intensity)) / SCAN_PERIOD;
  9. else
  10. s = 1.0; // s = 1s说明全部补偿到点云结束的时刻
  11. //s = 1;
  12. // 所有点的操作方式都是一致的,相当于从结束时刻补偿到起始时刻
  13. // 这里相当于是一个匀速模型的假设
  14. Eigen::Quaterniond q_point_last = Eigen::Quaterniond::Identity().slerp(s, q_last_curr);
  15. Eigen::Vector3d t_point_last = s * t_last_curr;
  16. Eigen::Vector3d point(pi->x, pi->y, pi->z);
  17. Eigen::Vector3d un_point = q_point_last * point + t_point_last;
  18. po->x = un_point.x();
  19. po->y = un_point.y();
  20. po->z = un_point.z();
  21. po->intensity = pi->intensity;
  22. }
  23. // transform all lidar points to the start of the next frame
  24. void TransformToEnd(PointType const *const pi, PointType *const po)
  25. {
  26. // undistort point first
  27. pcl::PointXYZI un_point_tmp;
  28. TransformToStart(pi, &un_point_tmp);
  29. Eigen::Vector3d un_point(un_point_tmp.x, un_point_tmp.y, un_point_tmp.z);
  30. Eigen::Vector3d point_end = q_last_curr.inverse() * (un_point - t_last_curr);
  31. po->x = point_end.x();
  32. po->y = point_end.y();
  33. po->z = point_end.z();
  34. //Remove distortion time info
  35. po->intensity = int(pi->intensity);
  36. }

3.2、总结概括

该部分主要实现前端高频低精度的激光里程计。首先搞清楚几个坐标系之间的转换,然后对点云匹配前先去畸变。采用两部LM的方法分别求解点到线的距离,点到面的距离,应用ceres 构建求解器。构建损失函数,构建优化项代入ceres 求解器。该部分在LOAM 中,求解是相当麻烦

流程如下图

 代码流程图,同样参考知乎大佬

SLAM前端入门框架-A_LOAM源码解析 - 知乎

上图已经将laserOdometry的流程描述的比较清楚了。下面就具体的说明一下可能会存在的实现上或者原理上的问题。
步骤1,主要就是配置订阅和发布节点,以及一些提前使用的变量的初始化。
步骤2,步骤3主要判断是否存在数据异常。
步骤4,用来判断是否有第一帧数据,如果没有第一帧数据,没有办法进行后续的匹配。所以需要进行一个初始化判断。
步骤5,是最关键的一个步骤,内部流程是将获取的每一个角点和面点(小集合)利用估计的映射,映射到上一时刻(这一帧雷达的启始时刻)(代码中有实现关于畸变去除的部分),通过利用历史帧构建的面KDTree和线KDTree(大集合)来匹配相似的点来构建点线和点面残差,利用ceres来求解较为精准的里程计。
线残差的计算方式,面残差的计算方式具体看下文,在lidarFactor中有具体的原理和涉及
步骤6,将这一帧的角点和面点(大集合)信息加入面KDTree和线KDTree中,以供下一帧匹配使用。
步骤7,发布激光里程计,点云以及角点和面点(大集合)。

4、laserMapping.cpp

        laserMapping.cpp主要是通过已经获得的激光里程计信息来消除激光里程计和地图之间的误差(也就是累计的误差),使得最终的姿态都是关于世界坐标的。

前端里程计会周期向后端发送位姿T_odom,但是Mapping模块中,我们需要得到位姿是T_map_cur,因此mapping就需要估计出odom坐标系与map坐标系之间的相对位姿变换T_map_odm,这部分需要仔细推导一下。 T_map_cur = T_map_odom × T_odom_cur

4.1、代码注释

主函数

  1. int main(int argc, char **argv)
  2. {
  3. ros::init(argc, argv, "laserMapping");
  4. ros::NodeHandle nh;
  5. float lineRes = 0; // 次极大边线点集体素滤波分辨率
  6. float planeRes = 0; // 次极小平面点集体素滤波分辨率
  7. nh.param<float>("mapping_line_resolution", lineRes, 0.4);
  8. nh.param<float>("mapping_plane_resolution", planeRes, 0.8);
  9. printf("line resolution %f plane resolution %f \n", lineRes, planeRes);
  10. downSizeFilterCorner.setLeafSize(lineRes, lineRes,lineRes);
  11. downSizeFilterSurf.setLeafSize(planeRes, planeRes, planeRes);
  12. // 从laserOdometry节点接收次极大边线点
  13. ros::Subscriber subLaserCloudCornerLast = nh.subscribe<sensor_msgs::PointCloud2>("/laser_cloud_corner_last", 100, laserCloudCornerLastHandler);
  14. // 从laserOdometry节点接收次极小平面点
  15. ros::Subscriber subLaserCloudSurfLast = nh.subscribe<sensor_msgs::PointCloud2>("/laser_cloud_surf_last", 100, laserCloudSurfLastHandler);
  16. // 从laserOdometry节点接收到的最新帧的位姿T_cur^w
  17. ros::Subscriber subLaserOdometry = nh.subscribe<nav_msgs::Odometry>("/laser_odom_to_init", 100, laserOdometryHandler);
  18. // 从laserOdometry节点接收到的原始点云(只经过一次降采样)
  19. ros::Subscriber subLaserCloudFullRes = nh.subscribe<sensor_msgs::PointCloud2>("/velodyne_cloud_3", 100, laserCloudFullResHandler);
  20. // submap所在cube中的点云 / 发布周围5帧的点云集合(降采样以后的)
  21. pubLaserCloudSurround = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_surround", 100);
  22. // 所欲cube中的点云
  23. pubLaserCloudMap = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_map", 100);
  24. // 原始点云
  25. pubLaserCloudFullRes = nh.advertise<sensor_msgs::PointCloud2>("/velodyne_cloud_registered", 100);
  26. // 经过Scan to Map精估计优化后的当前帧位姿
  27. pubOdomAftMapped = nh.advertise<nav_msgs::Odometry>("/aft_mapped_to_init", 100);
  28. // 将里程计坐标系位姿转化到世界坐标系位姿(地图坐标系),相当于位姿优化初值
  29. pubOdomAftMappedHighFrec = nh.advertise<nav_msgs::Odometry>("/aft_mapped_to_init_high_frec", 100);
  30. // 经过Scan to Map精估计优化后的当前帧平移
  31. pubLaserAfterMappedPath = nh.advertise<nav_msgs::Path>("/aft_mapped_path", 100);
  32. /*
  33. * 重置这两个数组,这两数组用于存储所有边线点cube和平面点cube
  34. */
  35. for (int i = 0; i < laserCloudNum; i++)
  36. {
  37. laserCloudCornerArray[i].reset(new pcl::PointCloud<PointType>());
  38. laserCloudSurfArray[i].reset(new pcl::PointCloud<PointType>());
  39. }
  40. std::thread mapping_process{process};
  41. ros::spin();
  42. return 0;
  43. }

关于坐标转换的几个函数:

这里涉及到几个坐标系的相互转换,需要理清关系:雷达坐标系(每帧扫描到的点云点的坐标point_curr都在雷达坐标系中),里程计坐标系(由laseOdometry节点粗估计得到的LiDAR位姿wodom_curr对应的坐标系),地图坐标系(真实的世界坐标系)

  1. // set initial guess,里程计位姿转化为地图位姿,作为后端初始估计
  2. void transformAssociateToMap()
  3. {
  4. // T_w_curr = T_w_last * T_last_curr(from lidar odom)
  5. q_w_curr = q_wmap_wodom * q_wodom_curr;
  6. t_w_curr = q_wmap_wodom * t_wodom_curr + t_wmap_wodom;
  7. }
  8. // 更新odom到map之间的位姿变换
  9. void transformUpdate()
  10. {
  11. q_wmap_wodom = q_w_curr * q_wodom_curr.inverse();
  12. t_wmap_wodom = t_w_curr - q_wmap_wodom * t_wodom_curr;
  13. }
  14. //雷达坐标系点转化为地图点
  15. void pointAssociateToMap(PointType const *const pi, PointType *const po)
  16. {
  17. Eigen::Vector3d point_curr(pi->x, pi->y, pi->z);
  18. Eigen::Vector3d point_w = q_w_curr * point_curr + t_w_curr;
  19. po->x = point_w.x();
  20. po->y = point_w.y();
  21. po->z = point_w.z();
  22. po->intensity = pi->intensity;
  23. //po->intensity = 1.0;
  24. }
  25. //地图点转化到雷达坐标系点
  26. void pointAssociateTobeMapped(PointType const *const pi, PointType *const po)
  27. {
  28. Eigen::Vector3d point_w(pi->x, pi->y, pi->z);
  29. Eigen::Vector3d point_curr = q_w_curr.inverse() * (point_w - t_w_curr);
  30. po->x = point_curr.x();
  31. po->y = point_curr.y();
  32. po->z = point_curr.z();
  33. po->intensity = pi->intensity;
  34. }

回调函数处理

  1. // 回调函数中将消息都是送入各自队列,进行线程加锁和解锁
  2. void laserCloudCornerLastHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloudCornerLast2)
  3. {
  4. mBuf.lock();
  5. cornerLastBuf.push(laserCloudCornerLast2);
  6. mBuf.unlock();
  7. }
  8. void laserCloudSurfLastHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloudSurfLast2)
  9. {
  10. mBuf.lock();
  11. surfLastBuf.push(laserCloudSurfLast2);
  12. mBuf.unlock();
  13. }
  14. void laserCloudFullResHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloudFullRes2)
  15. {
  16. mBuf.lock();
  17. fullResBuf.push(laserCloudFullRes2);
  18. mBuf.unlock();
  19. }
  20. //receive odomtry
  21. //里程计坐标系位姿转化为地图坐标系位姿
  22. void laserOdometryHandler(const nav_msgs::Odometry::ConstPtr &laserOdometry)
  23. {
  24. mBuf.lock();
  25. odometryBuf.push(laserOdometry);
  26. mBuf.unlock();
  27. // high frequence publish
  28. Eigen::Quaterniond q_wodom_curr;
  29. Eigen::Vector3d t_wodom_curr;
  30. q_wodom_curr.x() = laserOdometry->pose.pose.orientation.x;
  31. q_wodom_curr.y() = laserOdometry->pose.pose.orientation.y;
  32. q_wodom_curr.z() = laserOdometry->pose.pose.orientation.z;
  33. q_wodom_curr.w() = laserOdometry->pose.pose.orientation.w;
  34. t_wodom_curr.x() = laserOdometry->pose.pose.position.x;
  35. t_wodom_curr.y() = laserOdometry->pose.pose.position.y;
  36. t_wodom_curr.z() = laserOdometry->pose.pose.position.z;
  37. //里程计坐标系位姿转换为地图坐标系位姿
  38. Eigen::Quaterniond q_w_curr = q_wmap_wodom * q_wodom_curr;
  39. Eigen::Vector3d t_w_curr = q_wmap_wodom * t_wodom_curr + t_wmap_wodom;
  40. nav_msgs::Odometry odomAftMapped;
  41. odomAftMapped.header.frame_id = "/camera_init";
  42. odomAftMapped.child_frame_id = "/aft_mapped";
  43. odomAftMapped.header.stamp = laserOdometry->header.stamp;
  44. odomAftMapped.pose.pose.orientation.x = q_w_curr.x();
  45. odomAftMapped.pose.pose.orientation.y = q_w_curr.y();
  46. odomAftMapped.pose.pose.orientation.z = q_w_curr.z();
  47. odomAftMapped.pose.pose.orientation.w = q_w_curr.w();
  48. odomAftMapped.pose.pose.position.x = t_w_curr.x();
  49. odomAftMapped.pose.pose.position.y = t_w_curr.y();
  50. odomAftMapped.pose.pose.position.z = t_w_curr.z();
  51. pubOdomAftMappedHighFrec.publish(odomAftMapped);
  52. }

接下来就是核心函数,scan to map 位姿精匹配的实现。但是,如果完全使用所有区域的点云进行匹配,这样的效率会很低,而且内存空间可能会爆掉。LOAM论文中提到采用的是栅格(cube)地图的方法,将整个地图分成21×21×11个珊格,每个珊格是⼀个边⻓50m的正⽅体,当地图逐渐累加时,珊格之外的部分就被舍弃,这样可以保证内存空间不会随着程序的运⾏⽽爆掉,同时保证效率。

process 主线程中,首先对数据就行预处理,同步时间戳,转换为pcl格式,点云数据坐标转换,建立cube,并通过六个循环处理当前栅格,使其始终保持单钱栅格在中间位置,目的是为了保证当前帧不在局部地图的边缘,方便从地图中获取足够的特征点

  1. // 主处理线程
  2. void process()
  3. {
  4. while(1)
  5. {
  6. // 假如四个队列非空,四个队列分别存放边线点、平面点、全部点、和里程计位姿
  7. while (!cornerLastBuf.empty() && !surfLastBuf.empty() &&
  8. !fullResBuf.empty() && !odometryBuf.empty())
  9. {
  10. // laserOdometry模块对本节点的执行频率进行了控制,laserOdometry模块publish的位姿是10Hz,点云的publish频率则可以没这么高
  11. // 保证其他容器的最新消息与cornerLastBuf.front()最新消息时间戳同步
  12. mBuf.lock();
  13. // 以cornerLastBuf为基准,把时间戳小于其的全部pop出去
  14. while (!odometryBuf.empty() && odometryBuf.front()->header.stamp.toSec() < cornerLastBuf.front()->header.stamp.toSec())
  15. odometryBuf.pop();
  16. if (odometryBuf.empty())
  17. {
  18. mBuf.unlock();
  19. break;
  20. }
  21. while (!surfLastBuf.empty() && surfLastBuf.front()->header.stamp.toSec() < cornerLastBuf.front()->header.stamp.toSec())
  22. surfLastBuf.pop();
  23. if (surfLastBuf.empty())
  24. {
  25. mBuf.unlock();
  26. break;
  27. }
  28. while (!fullResBuf.empty() && fullResBuf.front()->header.stamp.toSec() < cornerLastBuf.front()->header.stamp.toSec())
  29. fullResBuf.pop();
  30. if (fullResBuf.empty())
  31. {
  32. mBuf.unlock();
  33. break;
  34. }
  35. timeLaserCloudCornerLast = cornerLastBuf.front()->header.stamp.toSec();
  36. timeLaserCloudSurfLast = surfLastBuf.front()->header.stamp.toSec();
  37. timeLaserCloudFullRes = fullResBuf.front()->header.stamp.toSec();
  38. timeLaserOdometry = odometryBuf.front()->header.stamp.toSec();
  39. // 原则上取出来的时间戳都是一样的,如果不一定说明有问题了
  40. if (timeLaserCloudCornerLast != timeLaserOdometry ||
  41. timeLaserCloudSurfLast != timeLaserOdometry ||
  42. timeLaserCloudFullRes != timeLaserOdometry)
  43. {
  44. printf("time corner %f surf %f full %f odom %f \n", timeLaserCloudCornerLast, timeLaserCloudSurfLast, timeLaserCloudFullRes, timeLaserOdometry);
  45. printf("unsync messeage!");
  46. mBuf.unlock();
  47. break;
  48. }
  49. // 点云全部转成pcl的数据格式
  50. laserCloudCornerLast->clear();
  51. pcl::fromROSMsg(*cornerLastBuf.front(), *laserCloudCornerLast);
  52. cornerLastBuf.pop();
  53. laserCloudSurfLast->clear();
  54. pcl::fromROSMsg(*surfLastBuf.front(), *laserCloudSurfLast);
  55. surfLastBuf.pop();
  56. laserCloudFullRes->clear();
  57. pcl::fromROSMsg(*fullResBuf.front(), *laserCloudFullRes);
  58. fullResBuf.pop();
  59. // lidar odom的结果转成eigen数据格式
  60. q_wodom_curr.x() = odometryBuf.front()->pose.pose.orientation.x;
  61. q_wodom_curr.y() = odometryBuf.front()->pose.pose.orientation.y;
  62. q_wodom_curr.z() = odometryBuf.front()->pose.pose.orientation.z;
  63. q_wodom_curr.w() = odometryBuf.front()->pose.pose.orientation.w;
  64. t_wodom_curr.x() = odometryBuf.front()->pose.pose.position.x;
  65. t_wodom_curr.y() = odometryBuf.front()->pose.pose.position.y;
  66. t_wodom_curr.z() = odometryBuf.front()->pose.pose.position.z;
  67. odometryBuf.pop();
  68. // 考虑到实时性,就把队列里其他的都pop出去,不然可能出现处理延时的情况
  69. // 其余的边线点清空
  70. // 为了保证LOAM算法整体的实时性,因Mapping线程耗时>100ms导致的历史缓存都会被清空
  71. while(!cornerLastBuf.empty())
  72. {
  73. cornerLastBuf.pop();
  74. printf("drop lidar frame in mapping for real time performance \n");
  75. }
  76. mBuf.unlock();
  77. TicToc t_whole;
  78. // 根据前端结果,得到后端的一个初始估计值
  79. transformAssociateToMap();
  80. TicToc t_shift;
  81. // 根据初始估计值计算寻找当前位姿在地图中的索引,一个各自边长是50m
  82. // 后端的地图本质上是一个以当前点为中心,一个珊格地图
  83. int centerCubeI = int((t_w_curr.x() + 25.0) / 50.0) + laserCloudCenWidth;
  84. int centerCubeJ = int((t_w_curr.y() + 25.0) / 50.0) + laserCloudCenHeight;
  85. int centerCubeK = int((t_w_curr.z() + 25.0) / 50.0) + laserCloudCenDepth;
  86. // 如果小于25就向下取整,相当于四舍五入的一个过程
  87. // 由于int(-2.1)=-2是向0取整,当被求余数为负数时求余结果统一向左偏移一个单位
  88. if (t_w_curr.x() + 25.0 < 0)
  89. centerCubeI--;
  90. if (t_w_curr.y() + 25.0 < 0)
  91. centerCubeJ--;
  92. if (t_w_curr.z() + 25.0 < 0)
  93. centerCubeK--;
  94. // 如果当前珊格索引小于3,就说明当前点快接近地图边界了,需要进行调整,相当于地图整体往x正方向移动
  95. // 调整取值范围:3 < centerCubeI < 183 < centerCubeJ < 18, 3 < centerCubeK < 8
  96. // 如果cube处于边界,则将cube向中心靠拢一些,方便后续拓展cube
  97. while (centerCubeI < 3)
  98. {
  99. for (int j = 0; j < laserCloudHeight; j++)
  100. {
  101. for (int k = 0; k < laserCloudDepth; k++)
  102. {
  103. int i = laserCloudWidth - 1;
  104. // 从x最大值开始
  105. pcl::PointCloud<PointType>::Ptr laserCloudCubeCornerPointer =
  106. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  107. pcl::PointCloud<PointType>::Ptr laserCloudCubeSurfPointer =
  108. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  109. // 整体右移
  110. for (; i >= 1; i--)
  111. {
  112. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  113. laserCloudCornerArray[i - 1 + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  114. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  115. laserCloudSurfArray[i - 1 + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  116. }
  117. // 此时i = 0,也就是最左边的格子赋值了之前最右边的格子
  118. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  119. laserCloudCubeCornerPointer;
  120. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  121. laserCloudCubeSurfPointer;
  122. // 该点云清零,由于是指针操作,相当于最左边的格子清空了
  123. laserCloudCubeCornerPointer->clear();
  124. laserCloudCubeSurfPointer->clear();
  125. }
  126. }
  127. // 索引右移
  128. centerCubeI++;
  129. laserCloudCenWidth++;
  130. }
  131. // 同理x如果抵达右边界,就整体左移
  132. while (centerCubeI >= laserCloudWidth - 3)
  133. {
  134. for (int j = 0; j < laserCloudHeight; j++)
  135. {
  136. for (int k = 0; k < laserCloudDepth; k++)
  137. {
  138. int i = 0;
  139. pcl::PointCloud<PointType>::Ptr laserCloudCubeCornerPointer =
  140. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  141. pcl::PointCloud<PointType>::Ptr laserCloudCubeSurfPointer =
  142. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  143. // 整体左移
  144. for (; i < laserCloudWidth - 1; i++)
  145. {
  146. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  147. laserCloudCornerArray[i + 1 + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  148. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  149. laserCloudSurfArray[i + 1 + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  150. }
  151. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  152. laserCloudCubeCornerPointer;
  153. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  154. laserCloudCubeSurfPointer;
  155. laserCloudCubeCornerPointer->clear();
  156. laserCloudCubeSurfPointer->clear();
  157. }
  158. }
  159. centerCubeI--;
  160. laserCloudCenWidth--;
  161. }
  162. // y和z的操作同理
  163. while (centerCubeJ < 3)
  164. {
  165. for (int i = 0; i < laserCloudWidth; i++)
  166. {
  167. for (int k = 0; k < laserCloudDepth; k++)
  168. {
  169. int j = laserCloudHeight - 1;
  170. pcl::PointCloud<PointType>::Ptr laserCloudCubeCornerPointer =
  171. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  172. pcl::PointCloud<PointType>::Ptr laserCloudCubeSurfPointer =
  173. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  174. for (; j >= 1; j--)
  175. {
  176. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  177. laserCloudCornerArray[i + laserCloudWidth * (j - 1) + laserCloudWidth * laserCloudHeight * k];
  178. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  179. laserCloudSurfArray[i + laserCloudWidth * (j - 1) + laserCloudWidth * laserCloudHeight * k];
  180. }
  181. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  182. laserCloudCubeCornerPointer;
  183. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  184. laserCloudCubeSurfPointer;
  185. laserCloudCubeCornerPointer->clear();
  186. laserCloudCubeSurfPointer->clear();
  187. }
  188. }
  189. centerCubeJ++;
  190. laserCloudCenHeight++;
  191. }
  192. while (centerCubeJ >= laserCloudHeight - 3)
  193. {
  194. for (int i = 0; i < laserCloudWidth; i++)
  195. {
  196. for (int k = 0; k < laserCloudDepth; k++)
  197. {
  198. int j = 0;
  199. pcl::PointCloud<PointType>::Ptr laserCloudCubeCornerPointer =
  200. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  201. pcl::PointCloud<PointType>::Ptr laserCloudCubeSurfPointer =
  202. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  203. for (; j < laserCloudHeight - 1; j++)
  204. {
  205. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  206. laserCloudCornerArray[i + laserCloudWidth * (j + 1) + laserCloudWidth * laserCloudHeight * k];
  207. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  208. laserCloudSurfArray[i + laserCloudWidth * (j + 1) + laserCloudWidth * laserCloudHeight * k];
  209. }
  210. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  211. laserCloudCubeCornerPointer;
  212. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  213. laserCloudCubeSurfPointer;
  214. laserCloudCubeCornerPointer->clear();
  215. laserCloudCubeSurfPointer->clear();
  216. }
  217. }
  218. centerCubeJ--;
  219. laserCloudCenHeight--;
  220. }
  221. while (centerCubeK < 3)
  222. {
  223. for (int i = 0; i < laserCloudWidth; i++)
  224. {
  225. for (int j = 0; j < laserCloudHeight; j++)
  226. {
  227. int k = laserCloudDepth - 1;
  228. pcl::PointCloud<PointType>::Ptr laserCloudCubeCornerPointer =
  229. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  230. pcl::PointCloud<PointType>::Ptr laserCloudCubeSurfPointer =
  231. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  232. for (; k >= 1; k--)
  233. {
  234. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  235. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * (k - 1)];
  236. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  237. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * (k - 1)];
  238. }
  239. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  240. laserCloudCubeCornerPointer;
  241. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  242. laserCloudCubeSurfPointer;
  243. laserCloudCubeCornerPointer->clear();
  244. laserCloudCubeSurfPointer->clear();
  245. }
  246. }
  247. centerCubeK++;
  248. laserCloudCenDepth++;
  249. }
  250. while (centerCubeK >= laserCloudDepth - 3)
  251. {
  252. for (int i = 0; i < laserCloudWidth; i++)
  253. {
  254. for (int j = 0; j < laserCloudHeight; j++)
  255. {
  256. int k = 0;
  257. pcl::PointCloud<PointType>::Ptr laserCloudCubeCornerPointer =
  258. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  259. pcl::PointCloud<PointType>::Ptr laserCloudCubeSurfPointer =
  260. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k];
  261. for (; k < laserCloudDepth - 1; k++)
  262. {
  263. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  264. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * (k + 1)];
  265. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  266. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * (k + 1)];
  267. }
  268. laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  269. laserCloudCubeCornerPointer;
  270. laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] =
  271. laserCloudCubeSurfPointer;
  272. laserCloudCubeCornerPointer->clear();
  273. laserCloudCubeSurfPointer->clear();
  274. }
  275. }
  276. centerCubeK--;
  277. laserCloudCenDepth--;
  278. }
  279. // 以上操作相当于维护了一个局部地图,保证当前帧不在这个局部地图的边缘,这样才可以从地图中获取足够的约束
  280. int laserCloudValidNum = 0;
  281. int laserCloudSurroundNum = 0;
  282. // 从当前格子为中心,选出地图中一定范围的点云
  283. // 向IJ坐标轴的正负方向各拓展2个cube,K坐标轴的正负方向各拓展1个cube
  284. // 在每一维附近5个cube(前2个,后2个,中间1个)里进行查找(前后250米范围内,总共500米范围),三个维度总共125个cube
  285. // 在这125个cube里面进一步筛选在视域范围内的cube
  286. for (int i = centerCubeI - 2; i <= centerCubeI + 2; i++)
  287. {
  288. for (int j = centerCubeJ - 2; j <= centerCubeJ + 2; j++)
  289. {
  290. for (int k = centerCubeK - 1; k <= centerCubeK + 1; k++)
  291. {
  292. if (i >= 0 && i < laserCloudWidth &&
  293. j >= 0 && j < laserCloudHeight &&
  294. k >= 0 && k < laserCloudDepth)
  295. {
  296. // 把各自的索引记录下来
  297. laserCloudValidInd[laserCloudValidNum] = i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k;
  298. laserCloudValidNum++;
  299. laserCloudSurroundInd[laserCloudSurroundNum] = i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k;
  300. laserCloudSurroundNum++;
  301. }
  302. }
  303. }
  304. }
  305. // 将有效index的cube中的点云叠加到一起组成submap的特征点云
  306. laserCloudCornerFromMap->clear();
  307. laserCloudSurfFromMap->clear();
  308. // 开始构建用来这一帧优化的小的局部地图
  309. for (int i = 0; i < laserCloudValidNum; i++)
  310. {
  311. *laserCloudCornerFromMap += *laserCloudCornerArray[laserCloudValidInd[i]];
  312. *laserCloudSurfFromMap += *laserCloudSurfArray[laserCloudValidInd[i]];
  313. }
  314. int laserCloudCornerFromMapNum = laserCloudCornerFromMap->points.size();
  315. int laserCloudSurfFromMapNum = laserCloudSurfFromMap->points.size();
  316. // 为了减少运算量,对点云进行下采样
  317. pcl::PointCloud<PointType>::Ptr laserCloudCornerStack(new pcl::PointCloud<PointType>());
  318. downSizeFilterCorner.setInputCloud(laserCloudCornerLast);
  319. downSizeFilterCorner.filter(*laserCloudCornerStack);
  320. int laserCloudCornerStackNum = laserCloudCornerStack->points.size();
  321. pcl::PointCloud<PointType>::Ptr laserCloudSurfStack(new pcl::PointCloud<PointType>());
  322. downSizeFilterSurf.setInputCloud(laserCloudSurfLast);
  323. downSizeFilterSurf.filter(*laserCloudSurfStack);
  324. int laserCloudSurfStackNum = laserCloudSurfStack->points.size();
  325. printf("map prepare time %f ms\n", t_shift.toc());
  326. printf("map corner num %d surf num %d \n", laserCloudCornerFromMapNum, laserCloudSurfFromMapNum);

scan to map 在submap的cube 与全部地图的cube匹配时,帧间匹配的方法不再适用,cube上的方法如下:

1. 取当前帧的角点与面点

2. 找到全部地图特征点中,当前特征点的5个最近邻点。

3. 如果是角点,则以这五个点的均值点为中心,以5个点的主方向向量(类似于PCA方法)为方向,作一条直线,令该边线点与直线距离最短,构建非线性优化问题。

4. 如果是平面点,则寻找五个点的法方向(反向的PCA方法),令这个平面点在法方向上与五个近邻点的距离最小,构建非线性优化问题。

5. 优化变量是雷达位姿,求解能够让以上非线性问题代价函数最小的雷达位姿。

  1. // 最终的有效点云数目进行判断
  2. if (laserCloudCornerFromMapNum > 10 && laserCloudSurfFromMapNum > 50)
  3. {
  4. TicToc t_opt;
  5. TicToc t_tree;
  6. // 送入kdtree便于最近邻搜索
  7. kdtreeCornerFromMap->setInputCloud(laserCloudCornerFromMap);
  8. kdtreeSurfFromMap->setInputCloud(laserCloudSurfFromMap);
  9. printf("build tree time %f ms \n", t_tree.toc());
  10. // 建立对应关系的迭代次数不超2次 两次非线性优化
  11. for (int iterCount = 0; iterCount < 2; iterCount++)
  12. {
  13. //ceres::LossFunction *loss_function = NULL;
  14. // 建立ceres问题
  15. ceres::LossFunction *loss_function = new ceres::HuberLoss(0.1);
  16. ceres::LocalParameterization *q_parameterization =
  17. new ceres::EigenQuaternionParameterization();
  18. ceres::Problem::Options problem_options;
  19. ceres::Problem problem(problem_options);
  20. problem.AddParameterBlock(parameters, 4, q_parameterization);
  21. problem.AddParameterBlock(parameters + 4, 3);
  22. TicToc t_data;
  23. int corner_num = 0;
  24. // 构建角点相关的约束
  25. for (int i = 0; i < laserCloudCornerStackNum; i++)
  26. {
  27. pointOri = laserCloudCornerStack->points[i];
  28. //double sqrtDis = pointOri.x * pointOri.x + pointOri.y * pointOri.y + pointOri.z * pointOri.z;
  29. // 把当前点根据初值投到地图坐标系下去
  30. // submap中的点云都是在(map)world坐标系下,而接收到的当前帧点云都是Lidar坐标系下
  31. // 所以在搜寻最近邻点时,先用预测的Mapping位姿w_curr,将Lidar坐标系下的特征点变换到(map)world坐标系下
  32. pointAssociateToMap(&pointOri, &pointSel);
  33. // 地图中寻找和该点最近的5个点
  34. // 特征点中,寻找距离当前帧corner特征点最近的5个点
  35. kdtreeCornerFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);
  36. // 判断最远的点距离不能超过1m,否则就是无效约束
  37. if (pointSearchSqDis[4] < 1.0)
  38. {
  39. // 计算这个5个最近邻点的中心
  40. std::vector<Eigen::Vector3d> nearCorners;
  41. Eigen::Vector3d center(0, 0, 0);
  42. for (int j = 0; j < 5; j++)
  43. {
  44. Eigen::Vector3d tmp(laserCloudCornerFromMap->points[pointSearchInd[j]].x,
  45. laserCloudCornerFromMap->points[pointSearchInd[j]].y,
  46. laserCloudCornerFromMap->points[pointSearchInd[j]].z);
  47. center = center + tmp;
  48. nearCorners.push_back(tmp);
  49. }
  50. // 计算这五个点的均值
  51. center = center / 5.0;
  52. Eigen::Matrix3d covMat = Eigen::Matrix3d::Zero();
  53. // 构建5个最近邻点的协方差矩阵
  54. for (int j = 0; j < 5; j++)
  55. {
  56. Eigen::Matrix<double, 3, 1> tmpZeroMean = nearCorners[j] - center;
  57. covMat = covMat + tmpZeroMean * tmpZeroMean.transpose();
  58. }
  59. // 进行特征值分解
  60. Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> saes(covMat);
  61. // if is indeed line feature
  62. // note Eigen library sort eigenvalues in increasing order
  63. // 根据特征值分解情况看看是不是真正的线特征
  64. // 特征向量就是线特征的方向
  65. // 计算协方差矩阵的特征值和特征向量,用于判断这5个点是不是呈线状分布,此为PCA的原理
  66. // 如果5个点呈线状分布,最大的特征值对应的特征向量就是该线的方向矢量
  67. Eigen::Vector3d unit_direction = saes.eigenvectors().col(2);
  68. Eigen::Vector3d curr_point(pointOri.x, pointOri.y, pointOri.z);
  69. // 最大特征值大于次大特征值的3倍认为是线特征
  70. // 如果最大的特征值 >> 其他特征值,则5个点确实呈线状分布,否则认为直线“不够直”
  71. if (saes.eigenvalues()[2] > 3 * saes.eigenvalues()[1])
  72. {
  73. Eigen::Vector3d point_on_line = center;
  74. Eigen::Vector3d point_a, point_b;
  75. // 根据拟合出来的线特征方向,以平均点为中心构建两个虚拟点
  76. // 从中心点沿着方向向量向两端移动0.1m,使用两个点代替一条直线,这样计算点到直线的距离的形式就跟laserOdometry相似
  77. point_a = 0.1 * unit_direction + point_on_line;
  78. point_b = -0.1 * unit_direction + point_on_line;
  79. // 构建约束,和lidar odom约束一致
  80. ceres::CostFunction *cost_function = LidarEdgeFactor::Create(curr_point, point_a, point_b, 1.0);
  81. problem.AddResidualBlock(cost_function, loss_function, parameters, parameters + 4);
  82. corner_num++;
  83. }
  84. }
  85. /*
  86. else if(pointSearchSqDis[4] < 0.01 * sqrtDis)
  87. {
  88. Eigen::Vector3d center(0, 0, 0);
  89. for (int j = 0; j < 5; j++)
  90. {
  91. Eigen::Vector3d tmp(laserCloudCornerFromMap->points[pointSearchInd[j]].x,
  92. laserCloudCornerFromMap->points[pointSearchInd[j]].y,
  93. laserCloudCornerFromMap->points[pointSearchInd[j]].z);
  94. center = center + tmp;
  95. }
  96. center = center / 5.0;
  97. Eigen::Vector3d curr_point(pointOri.x, pointOri.y, pointOri.z);
  98. ceres::CostFunction *cost_function = LidarDistanceFactor::Create(curr_point, center);
  99. problem.AddResidualBlock(cost_function, loss_function, parameters, parameters + 4);
  100. }
  101. */
  102. }
  103. int surf_num = 0;
  104. // 构建面点约束
  105. for (int i = 0; i < laserCloudSurfStackNum; i++)
  106. {
  107. pointOri = laserCloudSurfStack->points[i];
  108. //double sqrtDis = pointOri.x * pointOri.x + pointOri.y * pointOri.y + pointOri.z * pointOri.z;
  109. pointAssociateToMap(&pointOri, &pointSel);
  110. kdtreeSurfFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);
  111. Eigen::Matrix<double, 5, 3> matA0;
  112. Eigen::Matrix<double, 5, 1> matB0 = -1 * Eigen::Matrix<double, 5, 1>::Ones();
  113. // 构建平面方程Ax + By +Cz + 1 = 0
  114. // 通过构建一个超定方程来求解这个平面方程
  115. if (pointSearchSqDis[4] < 1.0)
  116. {
  117. for (int j = 0; j < 5; j++)
  118. {
  119. matA0(j, 0) = laserCloudSurfFromMap->points[pointSearchInd[j]].x;
  120. matA0(j, 1) = laserCloudSurfFromMap->points[pointSearchInd[j]].y;
  121. matA0(j, 2) = laserCloudSurfFromMap->points[pointSearchInd[j]].z;
  122. //printf(" pts %f %f %f ", matA0(j, 0), matA0(j, 1), matA0(j, 2));
  123. }
  124. // find the norm of plane
  125. // 调用eigen接口求解该方程,解就是这个平面的法向量
  126. Eigen::Vector3d norm = matA0.colPivHouseholderQr().solve(matB0);
  127. double negative_OA_dot_norm = 1 / norm.norm(); // 法向量长度的倒数
  128. // 法向量归一化
  129. norm.normalize(); // 法向量归一化,相当于直线Ax + By + Cz + 1 = 0两边都乘negative_OA_dot_norm
  130. // Here n(pa, pb, pc) is unit norm of plane
  131. bool planeValid = true;
  132. // 根据求出来的平面方程进行校验,看看是不是符合平面约束
  133. for (int j = 0; j < 5; j++)
  134. {
  135. // if OX * n > 0.2, then plane is not fit well
  136. // 这里相当于求解点到平面的距离
  137. // 点(x0, y0, z0)到平面Ax + By + Cz + D = 0 的距离公式 = fabs(Ax0 + By0 + Cz0 + D) / sqrt(A^2 + B^2 + C^2)
  138. if (fabs(norm(0) * laserCloudSurfFromMap->points[pointSearchInd[j]].x +
  139. norm(1) * laserCloudSurfFromMap->points[pointSearchInd[j]].y +
  140. norm(2) * laserCloudSurfFromMap->points[pointSearchInd[j]].z + negative_OA_dot_norm) > 0.2)
  141. {
  142. planeValid = false; // 点如果距离平面太远,就认为这是一个拟合的不好的平面
  143. break;
  144. }
  145. }
  146. Eigen::Vector3d curr_point(pointOri.x, pointOri.y, pointOri.z);
  147. // 如果平面有效就构建平面约束
  148. if (planeValid)
  149. {
  150. // 利用平面方程构建约束,和前端构建形式稍有不同
  151. ceres::CostFunction *cost_function = LidarPlaneNormFactor::Create(curr_point, norm, negative_OA_dot_norm);
  152. problem.AddResidualBlock(cost_function, loss_function, parameters, parameters + 4);
  153. surf_num++;
  154. }
  155. }
  156. /*
  157. else if(pointSearchSqDis[4] < 0.01 * sqrtDis)
  158. {
  159. Eigen::Vector3d center(0, 0, 0);
  160. for (int j = 0; j < 5; j++)
  161. {
  162. Eigen::Vector3d tmp(laserCloudSurfFromMap->points[pointSearchInd[j]].x,
  163. laserCloudSurfFromMap->points[pointSearchInd[j]].y,
  164. laserCloudSurfFromMap->points[pointSearchInd[j]].z);
  165. center = center + tmp;
  166. }
  167. center = center / 5.0;
  168. Eigen::Vector3d curr_point(pointOri.x, pointOri.y, pointOri.z);
  169. ceres::CostFunction *cost_function = LidarDistanceFactor::Create(curr_point, center);
  170. problem.AddResidualBlock(cost_function, loss_function, parameters, parameters + 4);
  171. }
  172. */
  173. }
  174. //printf("corner num %d used corner num %d \n", laserCloudCornerStackNum, corner_num);
  175. //printf("surf num %d used surf num %d \n", laserCloudSurfStackNum, surf_num);
  176. printf("mapping data assosiation time %f ms \n", t_data.toc());
  177. // 调用ceres求解
  178. TicToc t_solver;
  179. ceres::Solver::Options options;
  180. options.linear_solver_type = ceres::DENSE_QR;
  181. options.max_num_iterations = 4;
  182. options.minimizer_progress_to_stdout = false;
  183. options.check_gradients = false;
  184. options.gradient_check_relative_precision = 1e-4;
  185. ceres::Solver::Summary summary;
  186. ceres::Solve(options, &problem, &summary);
  187. printf("mapping solver time %f ms \n", t_solver.toc());
  188. //printf("time %f \n", timeLaserOdometry);
  189. //printf("corner factor num %d surf factor num %d\n", corner_num, surf_num);
  190. //printf("result q %f %f %f %f result t %f %f %f\n", parameters[3], parameters[0], parameters[1], parameters[2],
  191. // parameters[4], parameters[5], parameters[6]);
  192. }
  193. printf("mapping optimization time %f \n", t_opt.toc());
  194. }
  195. else
  196. {
  197. ROS_WARN("time Map corner and surf num are not enough");
  198. }
  199. // 完成(迭代2次)特征匹配后,用最后匹配计算出的优化变量w_curr,更新增量wmap_wodom,让下一次的Mapping初值更准确
  200. transformUpdate();

接下来就是一些后处理,即将当前帧的特征点加入到全部地图栅格中,对全部地图栅格中的点进行降采样,刷新附近点云地图,刷新全部点云地图,发布当前帧的精确位姿和平移估计。

  1. TicToc t_add;
  2. // 将优化后的当前帧角点加到局部地图中去
  3. for (int i = 0; i < laserCloudCornerStackNum; i++)
  4. {
  5. // 该点根据位姿投到地图坐标系
  6. pointAssociateToMap(&laserCloudCornerStack->points[i], &pointSel);
  7. // 算出这个点所在的格子的索引
  8. int cubeI = int((pointSel.x + 25.0) / 50.0) + laserCloudCenWidth;
  9. int cubeJ = int((pointSel.y + 25.0) / 50.0) + laserCloudCenHeight;
  10. int cubeK = int((pointSel.z + 25.0) / 50.0) + laserCloudCenDepth;
  11. // 同样四舍五入一下
  12. if (pointSel.x + 25.0 < 0)
  13. cubeI--;
  14. if (pointSel.y + 25.0 < 0)
  15. cubeJ--;
  16. if (pointSel.z + 25.0 < 0)
  17. cubeK--;
  18. // 如果超过边界的话就算了
  19. if (cubeI >= 0 && cubeI < laserCloudWidth &&
  20. cubeJ >= 0 && cubeJ < laserCloudHeight &&
  21. cubeK >= 0 && cubeK < laserCloudDepth)
  22. {
  23. // 根据xyz的索引计算在一位数组中的索引
  24. int cubeInd = cubeI + laserCloudWidth * cubeJ + laserCloudWidth * laserCloudHeight * cubeK;
  25. laserCloudCornerArray[cubeInd]->push_back(pointSel);
  26. }
  27. }
  28. // 面点也做同样的处理
  29. for (int i = 0; i < laserCloudSurfStackNum; i++)
  30. {
  31. pointAssociateToMap(&laserCloudSurfStack->points[i], &pointSel);
  32. int cubeI = int((pointSel.x + 25.0) / 50.0) + laserCloudCenWidth;
  33. int cubeJ = int((pointSel.y + 25.0) / 50.0) + laserCloudCenHeight;
  34. int cubeK = int((pointSel.z + 25.0) / 50.0) + laserCloudCenDepth;
  35. if (pointSel.x + 25.0 < 0)
  36. cubeI--;
  37. if (pointSel.y + 25.0 < 0)
  38. cubeJ--;
  39. if (pointSel.z + 25.0 < 0)
  40. cubeK--;
  41. if (cubeI >= 0 && cubeI < laserCloudWidth &&
  42. cubeJ >= 0 && cubeJ < laserCloudHeight &&
  43. cubeK >= 0 && cubeK < laserCloudDepth)
  44. {
  45. int cubeInd = cubeI + laserCloudWidth * cubeJ + laserCloudWidth * laserCloudHeight * cubeK;
  46. laserCloudSurfArray[cubeInd]->push_back(pointSel);
  47. }
  48. }
  49. printf("add points time %f ms\n", t_add.toc());
  50. TicToc t_filter;
  51. // 把当前帧涉及到的局部地图的珊格做一个下采样
  52. for (int i = 0; i < laserCloudValidNum; i++)
  53. {
  54. int ind = laserCloudValidInd[i];
  55. pcl::PointCloud<PointType>::Ptr tmpCorner(new pcl::PointCloud<PointType>());
  56. downSizeFilterCorner.setInputCloud(laserCloudCornerArray[ind]);
  57. downSizeFilterCorner.filter(*tmpCorner);
  58. laserCloudCornerArray[ind] = tmpCorner;
  59. pcl::PointCloud<PointType>::Ptr tmpSurf(new pcl::PointCloud<PointType>());
  60. downSizeFilterSurf.setInputCloud(laserCloudSurfArray[ind]);
  61. downSizeFilterSurf.filter(*tmpSurf);
  62. laserCloudSurfArray[ind] = tmpSurf;
  63. }
  64. printf("filter time %f ms \n", t_filter.toc());
  65. TicToc t_pub;
  66. //publish surround map for every 5 frame
  67. // 每隔5帧对外发布一下
  68. if (frameCount % 5 == 0)
  69. {
  70. laserCloudSurround->clear();
  71. // 把该当前帧相关的局部地图发布出去
  72. for (int i = 0; i < laserCloudSurroundNum; i++)
  73. {
  74. int ind = laserCloudSurroundInd[i];
  75. *laserCloudSurround += *laserCloudCornerArray[ind];
  76. *laserCloudSurround += *laserCloudSurfArray[ind];
  77. }
  78. sensor_msgs::PointCloud2 laserCloudSurround3;
  79. pcl::toROSMsg(*laserCloudSurround, laserCloudSurround3);
  80. laserCloudSurround3.header.stamp = ros::Time().fromSec(timeLaserOdometry);
  81. laserCloudSurround3.header.frame_id = "/camera_init";
  82. pubLaserCloudSurround.publish(laserCloudSurround3);
  83. }
  84. // 每隔20帧发布全量的局部地图
  85. if (frameCount % 20 == 0)
  86. {
  87. pcl::PointCloud<PointType> laserCloudMap;
  88. // 21 × 21 × 11 = 4851
  89. for (int i = 0; i < 4851; i++)
  90. {
  91. laserCloudMap += *laserCloudCornerArray[i];
  92. laserCloudMap += *laserCloudSurfArray[i];
  93. }
  94. sensor_msgs::PointCloud2 laserCloudMsg;
  95. pcl::toROSMsg(laserCloudMap, laserCloudMsg);
  96. laserCloudMsg.header.stamp = ros::Time().fromSec(timeLaserOdometry);
  97. laserCloudMsg.header.frame_id = "/camera_init";
  98. pubLaserCloudMap.publish(laserCloudMsg);
  99. }
  100. int laserCloudFullResNum = laserCloudFullRes->points.size();
  101. // 把当前帧发布出去
  102. for (int i = 0; i < laserCloudFullResNum; i++)
  103. {
  104. pointAssociateToMap(&laserCloudFullRes->points[i], &laserCloudFullRes->points[i]);
  105. }
  106. sensor_msgs::PointCloud2 laserCloudFullRes3;
  107. pcl::toROSMsg(*laserCloudFullRes, laserCloudFullRes3);
  108. laserCloudFullRes3.header.stamp = ros::Time().fromSec(timeLaserOdometry);
  109. laserCloudFullRes3.header.frame_id = "/camera_init";
  110. pubLaserCloudFullRes.publish(laserCloudFullRes3);
  111. printf("mapping pub time %f ms \n", t_pub.toc());
  112. printf("whole mapping time %f ms +++++\n", t_whole.toc());
  113. // 发布当前位姿
  114. nav_msgs::Odometry odomAftMapped;
  115. odomAftMapped.header.frame_id = "/camera_init";
  116. odomAftMapped.child_frame_id = "/aft_mapped";
  117. odomAftMapped.header.stamp = ros::Time().fromSec(timeLaserOdometry);
  118. odomAftMapped.pose.pose.orientation.x = q_w_curr.x();
  119. odomAftMapped.pose.pose.orientation.y = q_w_curr.y();
  120. odomAftMapped.pose.pose.orientation.z = q_w_curr.z();
  121. odomAftMapped.pose.pose.orientation.w = q_w_curr.w();
  122. odomAftMapped.pose.pose.position.x = t_w_curr.x();
  123. odomAftMapped.pose.pose.position.y = t_w_curr.y();
  124. odomAftMapped.pose.pose.position.z = t_w_curr.z();
  125. pubOdomAftMapped.publish(odomAftMapped);
  126. // 发布当前轨迹
  127. geometry_msgs::PoseStamped laserAfterMappedPose;
  128. laserAfterMappedPose.header = odomAftMapped.header;
  129. laserAfterMappedPose.pose = odomAftMapped.pose.pose;
  130. laserAfterMappedPath.header.stamp = odomAftMapped.header.stamp;
  131. laserAfterMappedPath.header.frame_id = "/camera_init";
  132. laserAfterMappedPath.poses.push_back(laserAfterMappedPose);
  133. pubLaserAfterMappedPath.publish(laserAfterMappedPath);
  134. // 发布tf
  135. static tf::TransformBroadcaster br;
  136. tf::Transform transform;
  137. tf::Quaternion q;
  138. transform.setOrigin(tf::Vector3(t_w_curr(0),
  139. t_w_curr(1),
  140. t_w_curr(2)));
  141. q.setW(q_w_curr.w());
  142. q.setX(q_w_curr.x());
  143. q.setY(q_w_curr.y());
  144. q.setZ(q_w_curr.z());
  145. transform.setRotation(q);
  146. br.sendTransform(tf::StampedTransform(transform, odomAftMapped.header.stamp, "/camera_init", "/aft_mapped"));
  147. frameCount++;
  148. }
  149. std::chrono::milliseconds dura(2);
  150. std::this_thread::sleep_for(dura);
  151. }

4.2、总结概括

该部分主要实现低频率高精度的地图构建。该部分的算法流程如论文中可参考下图理解

关于坐标之间的转换是理解代码的关键,关于三个坐标系之间的转换关系,可以参考知乎大佬的图

 SLAM前端入门框架-A_LOAM源码解析 - 知乎

下面皆引自上述链接

我们再来描述一下这个过程,首先每一帧的里程计坐标从上一个节点不断传来,起初里程计坐标和世界坐标下是没有偏差的,利用里程计坐标和两者之间的变化来求解世界坐标。优化后得到准确的世界坐标。利用这个准确的坐标和这一点的里程计坐标来求解,里程计坐标和世界坐标之间的变化,来给下一帧的激光里程计作为估计参考。
接下来是代码流程部分:
具体看下图:

上述图已经描绘的很清楚了,我是按照代码片段和个人的一些判断分成了15个步骤,每一步骤都有具体解释。比较复杂的可能也就是两部分,一部分是关于大cube的构建和移动,另一部分就是利用特征值和特征向量来计算线和面了

首先是cube的构建:

A_LOAM在实现的过程中构建了一个21*21*11的大立方体。
在流程图的第1步初始化时给其分配了对应的空间。
在流程图第5步中计算当前世界坐标系下的位置,就是计算上图中红色五角星的位置。对应的蓝色cube也就是此刻世界坐标下的点云。
其次是调整cube和此刻的相对位置:
流程图第6步所做的事情就是将这个这个大cube(21*21*11)的相对中间的位置为红色五角星(此刻点云在世界坐标系的位置),也就是通过6个while循环,移动到(3-18,3-18,3-11)的位置。具体移动一小格的示意图见下图

5、lidarFactor.cpp

        在laserOdometry和laserMapping中利用特征来计算位姿变化时,需要计算残差,这里就是来计算残差的。

下面介绍下ceres优化问题如何求解:定义一个模板类,重写优化问题,在这个类中定义残差,重载()运算符,()运算符函数前⼏个参数是参数块的起始指针,最后⼀个参数是残差块的指针,()运算符负责计算残差。下面是优化边线点的模板类程序。

线残差计算方式(引自 SLAM前端入门框架-A_LOAM源码解析 - 知乎

点线特征模板程序

  1. struct LidarEdgeFactor
  2. {
  3. LidarEdgeFactor(Eigen::Vector3d curr_point_, Eigen::Vector3d last_point_a_,
  4. Eigen::Vector3d last_point_b_, double s_)
  5. : curr_point(curr_point_), last_point_a(last_point_a_), last_point_b(last_point_b_), s(s_) {}
  6. template <typename T>
  7. bool operator()(const T *q, const T *t, T *residual) const
  8. {
  9. // 将double数组转成eigen的数据结构,注意这里必须都写成模板
  10. Eigen::Matrix<T, 3, 1> cp{T(curr_point.x()), T(curr_point.y()), T(curr_point.z())};
  11. Eigen::Matrix<T, 3, 1> lpa{T(last_point_a.x()), T(last_point_a.y()), T(last_point_a.z())};
  12. Eigen::Matrix<T, 3, 1> lpb{T(last_point_b.x()), T(last_point_b.y()), T(last_point_b.z())};
  13. //Eigen::Quaternion<T> q_last_curr{q[3], T(s) * q[0], T(s) * q[1], T(s) * q[2]};
  14. Eigen::Quaternion<T> q_last_curr{q[3], q[0], q[1], q[2]};
  15. Eigen::Quaternion<T> q_identity{T(1), T(0), T(0), T(0)};
  16. // 计算的是上一帧到当前帧的位姿变换,因此根据匀速模型,计算该点对应的位姿
  17. // 这里暂时不考虑畸变,因此这里不做任何变换
  18. q_last_curr = q_identity.slerp(T(s), q_last_curr);
  19. Eigen::Matrix<T, 3, 1> t_last_curr{T(s) * t[0], T(s) * t[1], T(s) * t[2]};
  20. Eigen::Matrix<T, 3, 1> lp;
  21. // 把当前点根据当前计算的帧间位姿变换到上一帧
  22. lp = q_last_curr * cp + t_last_curr;
  23. Eigen::Matrix<T, 3, 1> nu = (lp - lpa).cross(lp - lpb); // 模是三角形的面积
  24. Eigen::Matrix<T, 3, 1> de = lpa - lpb;
  25. // 残差的模是该点到底边的垂线长度
  26. // 这里感觉不需要定义三维
  27. residual[0] = nu.x() / de.norm();
  28. residual[1] = nu.y() / de.norm();
  29. residual[2] = nu.z() / de.norm();
  30. return true;
  31. }
  32. static ceres::CostFunction *Create(const Eigen::Vector3d curr_point_, const Eigen::Vector3d last_point_a_,
  33. const Eigen::Vector3d last_point_b_, const double s_)
  34. {
  35. return (new ceres::AutoDiffCostFunction<
  36. LidarEdgeFactor, 3, 4, 3>(
  37. new LidarEdgeFactor(curr_point_, last_point_a_, last_point_b_, s_)));
  38. }
  39. Eigen::Vector3d curr_point, last_point_a, last_point_b;
  40. double s;
  41. };

面参数计算方法:

面点残差模板

  1. struct LidarPlaneFactor
  2. {
  3. LidarPlaneFactor(Eigen::Vector3d curr_point_, Eigen::Vector3d last_point_j_,
  4. Eigen::Vector3d last_point_l_, Eigen::Vector3d last_point_m_, double s_)
  5. : curr_point(curr_point_), last_point_j(last_point_j_), last_point_l(last_point_l_),
  6. last_point_m(last_point_m_), s(s_)
  7. {
  8. // 求出平面单位法向量
  9. ljm_norm = (last_point_j - last_point_l).cross(last_point_j - last_point_m);
  10. ljm_norm.normalize();
  11. }
  12. template <typename T>
  13. bool operator()(const T *q, const T *t, T *residual) const
  14. {
  15. Eigen::Matrix<T, 3, 1> cp{T(curr_point.x()), T(curr_point.y()), T(curr_point.z())};
  16. Eigen::Matrix<T, 3, 1> lpj{T(last_point_j.x()), T(last_point_j.y()), T(last_point_j.z())};
  17. //Eigen::Matrix<T, 3, 1> lpl{T(last_point_l.x()), T(last_point_l.y()), T(last_point_l.z())};
  18. //Eigen::Matrix<T, 3, 1> lpm{T(last_point_m.x()), T(last_point_m.y()), T(last_point_m.z())};
  19. Eigen::Matrix<T, 3, 1> ljm{T(ljm_norm.x()), T(ljm_norm.y()), T(ljm_norm.z())};
  20. //Eigen::Quaternion<T> q_last_curr{q[3], T(s) * q[0], T(s) * q[1], T(s) * q[2]};
  21. Eigen::Quaternion<T> q_last_curr{q[3], q[0], q[1], q[2]};
  22. Eigen::Quaternion<T> q_identity{T(1), T(0), T(0), T(0)};
  23. // 根据时间戳进行插值
  24. q_last_curr = q_identity.slerp(T(s), q_last_curr);
  25. Eigen::Matrix<T, 3, 1> t_last_curr{T(s) * t[0], T(s) * t[1], T(s) * t[2]};
  26. Eigen::Matrix<T, 3, 1> lp;
  27. lp = q_last_curr * cp + t_last_curr;
  28. // 点到平面的距离
  29. residual[0] = (lp - lpj).dot(ljm);
  30. return true;
  31. }
  32. static ceres::CostFunction *Create(const Eigen::Vector3d curr_point_, const Eigen::Vector3d last_point_j_,
  33. const Eigen::Vector3d last_point_l_, const Eigen::Vector3d last_point_m_,
  34. const double s_)
  35. {
  36. return (new ceres::AutoDiffCostFunction<
  37. LidarPlaneFactor, 1, 4, 3>(
  38. new LidarPlaneFactor(curr_point_, last_point_j_, last_point_l_, last_point_m_, s_)));
  39. }
  40. Eigen::Vector3d curr_point, last_point_j, last_point_l, last_point_m;
  41. Eigen::Vector3d ljm_norm;
  42. double s;
  43. };

关于ceres 优化器的使用,可参考 高博的《视觉slam十四讲》熟悉熟悉。推荐ceres官网(http://www.ceres-solver.org/

6、参考连接

SLAM前端入门框架-A_LOAM源码解析 - 知乎

从A_LOAM开始入门3D激光SLAM - 知乎

二十七-VIO-SLAM开源框架Vin-mono跑EuRoC数据集 - 知乎

LOAM细节分析 - 知乎

loam代码解析 - 知乎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/90412?site
推荐阅读
相关标签
  

闽ICP备14008679号