• LIO-SAM源码解析(五):mapOptmization.cpp


    1. 代码流程

    1.1. extractSurroundingKeyFrames()

    1.2. scan2MapOptimization()

    这个函数主要就是进行帧到地图的匹配,通过点到面、点到线的距离距离最小作为优化目标。LOAM中雅阁比矩阵推导其实还是过于复杂了,可以使用进行误差扰动来计算雅阁比矩阵,姿态使用失准角(李代数)模型推导更为简单

     

    1.3. saveKeyFramesAndFactor()

    在这个函数一直维持着一个关键帧节点构建的图,将GPS位置、关键帧间相对位姿、闭环关键帧间相对位姿(两帧的点云匹配得到)作为观测值,对关键帧位姿进行优化,在没有GPS情况下,精度主要靠回环。

    利用当前关键帧scan2map匹配位姿和上个关键帧优化后的位姿(这一次优化的初值)来计算关键帧间相对位姿观测量,实际上这个观测量对位姿起不到优化的作用。

    2. 功能说明

    2.1. 第一个巨大的回调函数:lasercloudinfoHandle

    这个函数监听的是/feature/cloud_info,关于这个话题里面包含的内容,我已经在featureExtraction.cpp的总结部分说过了。这里回忆一下,cloud_info是作者自定义的一个特殊的msg类型,包含了当前激光帧的角点集合,平面点集合,一维数组,每根线开始的点和结束点在一维数组中的索引……

    那么收到数据,先保存时间戳,然后提取已经在featureExtraction.cpp中被提取的角点和平面点信息,保存到*laserCloudCornerLast和*laserCloudSurfLast中。请记住这两个命名。

    频率控制:当前时刻-上一时刻>=0.15s时,才开始下列循环:

    2.1.1.  UpdateInitGuess:当前帧初始化

    当关键帧集合为空时,用激光帧的imu原始数据角度数据初始化,并且把数据用lastImuTransformation保存(记住这个命名),返回。

    此时推荐回顾一下imageProjection.cpp部分的总结3.2

    假如cloudInfo.odomAvailable=true时,那么就用一个transBack来记录cloudInfo.initialGuessX等信息,(这个信息其实来自于imupreintegration.cpp中发布的imu里程计数据),然后记录增量,在之前系统状态transformTobeMapped的基础上,加上这个增量,再次存入transformTobeMapped。 注意这个transformTobeMapped,这个数据结构,在这个cpp里,我们可以理解为就是它在存储着激光里程计部分的系统状态,包括位置与姿态。

    注意,这里有一个lastImuPreTransformation,这个用来保存上一时刻imu里程计的数据,根据它和当前的imu里程计来算增量。不要和lastImuTransformation变量混起来,虽然这俩变量名字长的很像。

    然后覆盖lastImuTransformation(在这个case里没用到),返回;

    假如cloudInfo.imuAvailable=true,那么进入这个case:

    注意,lastImuTransformation在1.1.1和1.1.2中并未用到,只是不断的在替换成最新数据。当cloudInfo.odomAvailable一直是true的时候,程序压根也不会进入到这个case。

    但是,凡事总有例外,万一哪里没有衔接好,imu里程计没有及时算出来,那么就导致此时激光帧的位姿没有一个初始化的数据(我们之后是要在初始化的基础上进行优化的),那么之后的优化就无从进行。因此,就要用到这个case。

    这里主要思路是用imuRollInit数据来初始化,如果你回顾过imageProjection.cpp部分的总结3.2 那么你应该就会懂,这里的数据来源是原始imu数据的角度信息。那么如果这里有数据,就用lastImuTransformation当成最新的上一时刻数据,当前数据transBack和它算一个增量,然后累积到系统值transformTobeMapped上面去。最后更新覆盖lastImuTransformation,返回。

    2.1.2. extractSurroundingKeyFrames

    这个是比较复杂的一个函数,以下的内容希望读者可以心平气和的,每个字都依次念一遍。

    如果没有关键帧,那就算了,返回;

    如果有,就调用extractNearby函数。

    关键帧是啥?cloudKeyPoses3D,我们要记住这个变量,虽然到现在为止,我们还不知道它是怎么来的,但是这个东西是怎么获取的,我们在后续必须弄明白。

    在这里我先剧透一下:它里面装的是历史的“关键帧”的位置,即x,y,z三个值。需要明确:这里装的绝不是历史的关键帧位置处的点云。而是历史关键帧记录时刻机器人所在的位置。

    同理还有一个cloudKeyPoses6D,它比这个3D还多了三个角度信息。之所以要用一个6D一个3D分别来装关键帧,我现在直接揭晓答案:用3D装,是因为我们要根据这个来构建KD树,搜索历史上最近的节点。“最近”指的是距离上最近,即xyz空间坐标最近,和角度无关。而cloudKeyPoses6D,是用来投影点云的,把当前帧点云投影到世界坐标系下,那么投影就必须要用角度信息了,所以作者分别用了一个3D和一个6D来装数据。

    Kd树的原理我这里不写,随便放一个链接:机器学习——详解KD-Tree原理 - 知乎 ,实际上代码里也只是调库,所以这里我不写。

    2.1.3. extractNearby函数

    使用kd树,搜索当前最近的关键帧,在给定半径内(默认是50m)所有关键帧最近的位置,并把结果返回到pointSearchInd,把距离返回到pointSearchSqDis中。

    根据索引pointSearchInd,把相邻关键帧存入到surroundingKeyPoses中。

    下采样,装进surroundingKeyPosesDS中,并在原始的surroundingKeyPoses其中找到最近的一个点,替换掉索引。(关于这个,我的理解是,下采样后不太准确了,好几个不同的关键帧可能因为下采样的原因混成了一个,所以要用原始数据对索引进行一个修正,这样以后才方便根据索引投影点云)

    顺手把10s内的关键帧cloudKeyPoses3D中的位置也加入到surroundingKeyPosesDS中。

    extractCloud:提取边缘和平面点对应的localmap,把surroundingKeyPosesDS传入到函数中:

    对输入的surroundingKeyPosesDS进行遍历,找到50m之内的位置,然后用transformPointCloud把对应位置的点云,进行变换到世界坐标系下。

    如何变换呢?根据上面提到的cloudKeyPoses6D的位姿,然后把cornerCloudKeyFrame和surfCloudKeyFrame中根据索引找到点云,投影到世界坐标系下。

     那么在这里,cornerCloudKeyFrame和surfCloudKeyFrame是什么?之前从来没有出现过。我这里同样进行剧透,它里面存放的是下采样的点云。注意总结1中的*laserCloudCornerLast和*laserCloudSurfLast这两个东西,这是瞬时点云,这个东西会在之后被下采样,然后装入cornerCloudKeyFrame中。

    在角点点云和平面点点云被投影到世界坐标系下后,会被加入到laserCloudCornerFromMap和laserCloudSurfFromMap等数据结构中,然后再合出一个pair类型的Container<关键帧号,<角点集合,平面点集合>>。

    2.1.4. downsampleCurrentScan

    这部分比较简单,就是对最外层的回调函数中的laserCloudCornerLast之类的东西,进行一个下采样,保存到laserCloudCornerLastDS这些以DS结尾的数据结构中,并且把数目存到laserCloudCornerLastDSNum这种以DSNUM结尾的数据结构中。其实就是代表了当前帧点云的角点/平面点的下采样集合,和数目值。

    2.1.5. Scan2MapOptimization

    这个函数是本cpp中第二复杂的函数。我们现在把它展开。

    首先,没有关键帧保存,那就返回,不处理;

    如果DSNUM这种记录角点和平面点的数据结构中,发现数目不够多,也不处理;只有在数目足够多的时候才进行处理,默认最少要10个角点,100个平面点。

    迭代30次:

    边缘点匹配优化:CornerOptimization

    平面点匹配优化:SurfOptimization

    组合优化多项式系数:combineOptimizationCoeffs

    LMOptimization判断迭代误差是否足够小,如果是true则认为迭代完成,返回;

    transformUpdate:原始的imu的rpy,在这里和优化后的激光里程计位姿进行一个加权融合。 接下来,我们依次展开这些函数:

    边缘点匹配优化:CornerOptimization

    把系统状态transformTobeMapped做一个数据格式转换,变成transPointAssociateToMap形式
    从当前角点下采样集合laserCloudCornerLastDS进行遍历,找到世界坐标系下最近的5个点,要求小于1m。
    求5个样本的均值,协方差矩阵。对协方差矩阵进行特征值分解,如果最大特征值大于次大特征值的3倍,那么就认为构成线。
    一旦发现构成线,那么就在均值沿着最大特征向量方向(把它看成线的方向)前后各取一个点(+-0.1 x 方向)。
    X0为当前点,X1和X2为“X0附近的5个点一起算出的均值沿方向前后各取的一点”,叉乘计算三点面积a012,x1x2底边长度l12。然后再做一次叉乘,得到X0距离x1,x2连线的垂线段的单位方向向量(la,lb,lc)。并计算点到直线的距离ld2=a012/l12。
    用一个鲁棒和函数,使得距离ld2越大,s越小。然后用coeff来保存“鲁棒后”的距离,和“鲁棒后”的点到线的垂线的方向向量。
    如果点到直线的距离小于1m,那么存入数据结构,laserCloudOriCornerVec为原始点云,coeffSelCornerVec为鲁棒距离和鲁棒向量,laserCloudOriCornerFlag代表当前点X0 已经找到对应的线。

    思考:为什么要加入方向向量呢?是因为这个在优化的偏导数中会被用到。

    平面点匹配优化:SurfOptimization

    和上面的同理,对系统状态量transformTobeMapped进行数据格式转换;
    从当前角点下采样集合laserCloudSurfLastDS进行遍历,找到世界坐标系下最近的5个点,要求小于1m。
    直接用matA0存储这个5个点,求解Ax+By+Cz+1=0的ABC系数(用QR分解)
    然后对ABCD,代码中为pa,pb,pc,pd=1进行单位化。
    根据点x0到平面的距离d=d=\frac{|Ax_0+By_0+Cz_0+D|}{\sqrt{A^2+B^2+C^2}} (分母为1)判断是否构成平面。如果有一个大于0.2m则不构成。
    pd2为点到平面的距离,也用鲁棒和函数处理,并且比上两次开方(这点我不理解,我猜就是用来鲁棒的,换成1次开方可能也差不多,意义或许不大),然后和角点部分类似,得到s,存入数据结构。

    组合优化多项式系数:combineOptimizationCoeffs

    这个比较简单,就是把CornerOptimization和SurfOptimization中已经确定匹配关系的点提取出来,laserCloudOri统一把角点和平面点装在一起,coeffSel统一装之前计算得到的“鲁棒优化向量”(角点就是点到直线的“鲁棒垂线”,平面点就是点到平面的“鲁棒法线”)。

    优化向量会在LMOptimization中进行优化。

    LMOptimization判断迭代误差是否足够小,如果是true则认为迭代完成,返回。

        这一部分大内容,主要麻烦在原理上面。

        这里推荐一个阅读:LIO-SAM-scan2MapOptimization()优化原理及代码解析

        这个文章中公式写的非常好。我就不照搬了。

        另外在推导部分,可以仔细研究一下这篇文章:

        LeGO-LOAM中的数学公式推导

        虽然是Lego-loam的推导,但是Lego-loam和lio-sam在这部分的原理是一样的,因此可以通用。看完这篇文章,就能理解1.4.2.3中我提到的“优化向量”是干啥用的。

            总之,照着原理,构建JtJ*delt_x=-JTf,然后构建MatAtA,matAtB,利用cv:solve提供的QR分解,得到matX,即delta_x。
            当特征点缺乏时,状态估计方法会发生退化。特征值小于阈值,则视为退化方向向量。这块的理论,可以参考LOAM SLAM原理之防止非线性优化解退化
            更新位姿,判断收敛与否。那么真正的雷达里程计系统状态transformTobeMapped,就是在这里被更新。

        1.4.3 transformUpdate:原始的imu的rpy,在这里和优化后的激光里程计位姿进行一个加权融合。

        当imuAvailable=True的时候,并且俯仰角<1.4,那么对位姿和原始imu的rpy做一个加权平均,(权重在配置文件中可以被设置为0.01)。主要是对roll,pitch仅加权平均,并且对z进行一个高度约束(也就是clip,不得超过配置文件中的z_tollerance,这个主要是一个小trick,应对不能飞起来的无人小车用的),更新transformTobeMapped。

    好了,那么 现在回到回调函数的主流程:

    1.5 saveKeyFramesAndFactor:之前函数二话不说就用了一些并没有出现过的数据结构,例如什么cloudKeyPoses3D,cornerCloudKeyFrame之类的东西,看完这个函数将明白这些变量是怎么来的。

        1.5.1 saveFrame:计算当前帧和前一帧位姿变换,如果太小不设关键帧。默认是角度<0.2,距离<1m,两者不满足其一就不保存;

        1.5.2 addOdomFactor:

        这个是要加入激光里程计因子,给图优化的模型gtSAMgraph。在1.5之前别的函数里,如果没有关键帧,直接就跳过了。但是这里不能跳过。

        如果暂时还没有关键帧,就把当前激光系统状态transformTobeMapped,打包成一个PriorFactor加入到gtSAMgraph里。如果目前已经有关键帧了,就把最后一个关键帧,和当前状态transformTobeMapped计算一个增量,把这个增量打包成一个BetweenFactor,加入到gtSAMgraph里头去。

        initialEstimate代表变量初值,用transformTobeMapped赋值。

        1.5.3 addGpsFactor:

        GPS的筛选规则为:如果没有GPS信息,没有关键帧信息,首尾关键帧小于5m,或者位姿的协方差很小(x,y的协方差阈值小于25),就不添加GPS。

        否则,遍历GPS列表,当前帧0.2s以前的不要,或者GPS的协方差太大了也不要,无效数据也不要…… 找到正常数据,打包成一个gps_factor,加入gtSAMgraph里面。

        1.5.4 addLoopFactor:

        这个其实和当前的回调函数无关,因为当前回调函数监听的是/feature/cloud_info信息,回环是由其他线程监控和检测的。那么在这里,它查询回环队列,加入回环因子,就是一个顺手的事情,反正现在要更新优化,那么查一下,如果有候选的等在那里,就顺手加入优化。如果用做饭来比喻这件事,那么另外的回环检测的线程就是相当于另一个人在备菜,这里addLoopFactor相当于是在炒菜,备好了就先炒,没有备好就算了。

        1.5.5 gtsam正常更新。如果有回环那就多更新几次。

        1.5.6 把cloudKeyPoses3D,cloudKeyPoses6D,分别装上信息,cloudKeyPoses3D代表关键帧的位置,cloudKeyPoses6D代表关键帧的位置+姿态,为什么要有一个3D一个6D呢?6D里不已经包含了3D信息吗?这个问题我在1.2处已经解释过了。

        1.5.7 用优化结果更新transformTobeMapped。

        1.5.8 cornerCloudKeyFrames,surfCloudKeyFrames装入信息,回顾一下,回调函数开头收到的点云数据为laserCloudCornerLast,laserCloudSurfLast,然后在downsampleCurrentScan处这俩信息被下采样,加上了DS后缀。在这里把它装到cornerCloudKeyFrames和surfCloudKeyFrames中。

        (回顾:cornerCloudKeyFrames代表关键帧位置处的角点点云,surfCloudKeyFrames代表关键帧位置处的平面点点云。这俩东西就是上面1.2处extractSurroundingKeyFrames用到的内容,cornerCloudKeyFrames通过cloudKeyPoses6D变换到世界系下,被存到laserCloudCornerFromMap里面,这个FromMap又在scan2MapOptimization函数中被设置到kdtreeCornerFromMap这个Kd树里,在cornerOptimization函数里,就是把当前帧的激光点云依据1.1的初值transformTobeMapped,变换到世界坐标系下,再用kdtreeCornerFromMap进行kd搜索,建立匹配关系,优化transformTobeMapped。)

        1.5.9 updatePath,更新里程计轨迹。把cloudKeyPoses6D传入,保存在globalPath中。不过暂时还没有进行发布。

     1.6 correctPoses:

    如果发现回环的话,就把历史关键帧通通更新一遍。我们刚刚在1.5.5里面虽然更新过了,但是结果都是保存在gtsam里面的,cloudKeyPoses3D和cloudKeyPoses6D,这俩保存位置和位姿的变量仍然保留着更新前的关键帧位姿。所以就根据更新结果,把他俩更新一遍。

    为什么不更新cornerCloudKeyFrames和surfCloudKeyFrames呢?因为没有必要更新,这俩存的是机器人坐标系下的点云,和机器人在世界系下的位姿是无关的。

    1.7 publishOdometry:

    到此为止,激光里程计部分的transformTobeMapped就不再更新了。回顾一下transformTobeMapped经历了哪些变换:在1.1部分用imu角度初值或是imu里程计初值赋值,然后在scan2mapOptimization里面根据点到线、点到面的方程进行更新,再在transformUpdate里和原始imu的rpy信息进行一个很小的加权融合(不过这一步我觉得没啥大用),最后在saveKeyFrameAndFactor里面再加入GPS因子和回环因子进行一轮优化。

    最后把transformTobeMapped发布出去,其他cpp文件里,接收的“激光里程计”就是这么个东西。也就是lio_sam/mapping/odometry_incremental.

    1.8 publishFrames:

        这个纯粹就是把乱七八糟东西都发布出去,不管有没有用。如果用户需要就可以监听它。

        1.8.1发布关键帧位姿集合,把cloudKeyPoses3D发布成lio_sam/mapping/trajectory

        1.8.2发布局部降采样平面点,把laserCloudSurfFromMapDS(历史默认50m内的点,在extractCloud中被设置),发布为lio_sam/mapping/map_local

        1.8.3发布当前帧的下采样角点和平面点,用优化后的激光里程计位姿transformTobeMapped投影到世界系下发布,/lio_sam/mapping/cloud_registered

        1.8.4发布原始点云经过配准的点云:输入的/feature/cloud_info的cloud_deskewed字段是由featureExtraction.cpp发布的,其cloud_deskewed是源于imageProjection.cpp发布的原始去畸变点云。把它发布到世界坐标系下,然后以/lio_sam/mapping/cloud_registered_raw的形式发布。

        1.8.5发布轨迹,把1.5.9里装好在globalPath里面但是还没有发布的轨迹发布出去,名为/lio_sam/mapping/path。

    那么到现在,基本上mapOptimization.cpp的内容就结束了,但是还有一些尾巴:

    2.gpshandle:监听GPS数据,保存到GPS队列里。

    3.loopinfohandle:监听"lio_loop/loop_closure_detection",订阅来自外部闭环检测程序提供的闭环数据,本程序没有提供,这里实际没用上。

    4.loopClosureThread:这个线程在主函数里单独开了一个线程,简要说一下:

    4.1 读取配置文件中是否开启回环检测。

    4.2开始无限循环:

        4.2.1 performLoopClosure:

            在历史帧中搜索距离关键帧最近,时间间各较远的关键帧(默认是30s以外,15m以内)没找到就返回,如果找到了,结果就放在loopKeyPre当中,loopKeyCur保存最近一个关键帧。
            把最近一个关键帧的特征点提出来,放入cureKeyframeCloud里;回环候选帧前后各25帧也提取出来,放入prevKeyframeCloud里。
            把prevKeyframeCloud发布出去,名为lio_sam/mapping/icp_loop_closure_history/cloud
            调用pcl库的icp轮子,设定阈值,参数,用setInputSource,setInputTarget传入两个点云,用align对齐。成功阈值设定为0.3,成功则存在icp.getFinalTransformation里面。把当前关键帧的点云,用这个结果icp.getFinalTransformation,转换以后,以lio_sam/mapping/icp_loop_closure_corrected_cloud发布出去。
            把当前帧的的位姿用icp.getFinalTransformation结果校正一下,把pair<当前,回环>,间隔位姿,噪声用队列存起来,等待addLoopFactor来调用,即上面的1.5.4部分。

        4.2.2 visualizeLoopClosure:

        这部分内容没啥好说的,就是用于rviz展示,把关键帧节点和二者的约束用点和线连起来,以lio_sam/mapping/loop_closure_constraints发布出去。

    5. 最后一个线程,visualizeGlobalMapThread:

    这个主要是两块内容:

    5.1 publishGlobalmap:把当前关键帧附近1000m(默认)的关键帧找出来(其实也就是全局的了),降采样,变换到世界系下,然后发布为lio_sam/mapping/map_global.

    5.2 saveMapService:这个用来保存pcd格式的点云地图。在配置文件中可以设置开启与否,和存储位置。注意,当程序结束时,ctrl+c以后,才会启动保存任务。这个部分的代码,和发布globalmap部分的核心内容基本一致,反正就是把cornerCloudKeyFrames,surfCloudKeyFrames用cloudKeyPoses6D变换到世界系下,分别保存角点pcd和平面点pcd,以及全局(合起来)的pcd文件。

    3. 代码

    1. #include "utility.h"
    2. #include "lio_sam/cloud_info.h"
    3. #include "lio_sam/save_map.h"
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include
    13. #include
    14. #include
    15. #include
    16. #include
    17. using namespace gtsam;
    18. using symbol_shorthand::X; // Pose3 (x,y,z,r,p,y)
    19. using symbol_shorthand::V; // Vel (xdot,ydot,zdot)
    20. using symbol_shorthand::B; // Bias (ax,ay,az,gx,gy,gz)
    21. using symbol_shorthand::G; // GPS pose
    22. /**
    23. * 6D位姿点云结构定义
    24. */
    25. struct PointXYZIRPYT
    26. {
    27. PCL_ADD_POINT4D
    28. PCL_ADD_INTENSITY;
    29. float roll;
    30. float pitch;
    31. float yaw;
    32. double time;
    33. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    34. } EIGEN_ALIGN16;
    35. POINT_CLOUD_REGISTER_POINT_STRUCT (PointXYZIRPYT,
    36. (float, x, x) (float, y, y)
    37. (float, z, z) (float, intensity, intensity)
    38. (float, roll, roll) (float, pitch, pitch) (float, yaw, yaw)
    39. (double, time, time))
    40. typedef PointXYZIRPYT PointTypePose;
    41. class mapOptimization : public ParamServer
    42. {
    43. public:
    44. // gtsam
    45. NonlinearFactorGraph gtSAMgraph;
    46. Values initialEstimate;
    47. Values optimizedEstimate;
    48. ISAM2 *isam;
    49. Values isamCurrentEstimate;
    50. Eigen::MatrixXd poseCovariance;
    51. ros::Publisher pubLaserCloudSurround;
    52. ros::Publisher pubLaserOdometryGlobal;
    53. ros::Publisher pubLaserOdometryIncremental;
    54. ros::Publisher pubKeyPoses;
    55. ros::Publisher pubPath;
    56. ros::Publisher pubHistoryKeyFrames;
    57. ros::Publisher pubIcpKeyFrames;
    58. ros::Publisher pubRecentKeyFrames;
    59. ros::Publisher pubRecentKeyFrame;
    60. ros::Publisher pubCloudRegisteredRaw;
    61. ros::Publisher pubLoopConstraintEdge;
    62. ros::Subscriber subCloud;
    63. ros::Subscriber subGPS;
    64. ros::Subscriber subLoop;
    65. ros::ServiceServer srvSaveMap;
    66. std::deque gpsQueue;
    67. lio_sam::cloud_info cloudInfo;
    68. // 历史所有关键帧的角点集合(降采样)
    69. vector::Ptr> cornerCloudKeyFrames;
    70. // 历史所有关键帧的平面点集合(降采样)
    71. vector::Ptr> surfCloudKeyFrames;
    72. // 历史关键帧位姿(位置)
    73. pcl::PointCloud::Ptr cloudKeyPoses3D;
    74. // 历史关键帧位姿
    75. pcl::PointCloud::Ptr cloudKeyPoses6D;
    76. pcl::PointCloud::Ptr copy_cloudKeyPoses3D;
    77. pcl::PointCloud::Ptr copy_cloudKeyPoses6D;
    78. // 当前激光帧角点集合
    79. pcl::PointCloud::Ptr laserCloudCornerLast;
    80. // 当前激光帧平面点集合
    81. pcl::PointCloud::Ptr laserCloudSurfLast;
    82. // 当前激光帧角点集合,降采样,DS: DownSize
    83. pcl::PointCloud::Ptr laserCloudCornerLastDS;
    84. // 当前激光帧平面点集合,降采样
    85. pcl::PointCloud::Ptr laserCloudSurfLastDS;
    86. // 当前帧与局部map匹配上了的角点、平面点,加入同一集合;后面是对应点的参数
    87. pcl::PointCloud::Ptr laserCloudOri;
    88. pcl::PointCloud::Ptr coeffSel;
    89. // 当前帧与局部map匹配上了的角点、参数、标记
    90. std::vector laserCloudOriCornerVec;
    91. std::vector coeffSelCornerVec;
    92. std::vector<bool> laserCloudOriCornerFlag;
    93. // 当前帧与局部map匹配上了的平面点、参数、标记
    94. std::vector laserCloudOriSurfVec;
    95. std::vector coeffSelSurfVec;
    96. std::vector<bool> laserCloudOriSurfFlag;
    97. map<int, pair, pcl::PointCloud>> laserCloudMapContainer;
    98. // 局部map的角点集合
    99. pcl::PointCloud::Ptr laserCloudCornerFromMap;
    100. // 局部map的平面点集合
    101. pcl::PointCloud::Ptr laserCloudSurfFromMap;
    102. // 局部map的角点集合,降采样
    103. pcl::PointCloud::Ptr laserCloudCornerFromMapDS;
    104. // 局部map的平面点集合,降采样
    105. pcl::PointCloud::Ptr laserCloudSurfFromMapDS;
    106. // 局部关键帧构建的map点云,对应kdtree,用于scan-to-map找相邻点
    107. pcl::KdTreeFLANN::Ptr kdtreeCornerFromMap;
    108. pcl::KdTreeFLANN::Ptr kdtreeSurfFromMap;
    109. pcl::KdTreeFLANN::Ptr kdtreeSurroundingKeyPoses;
    110. pcl::KdTreeFLANN::Ptr kdtreeHistoryKeyPoses;
    111. // 降采样
    112. pcl::VoxelGrid downSizeFilterCorner;
    113. pcl::VoxelGrid downSizeFilterSurf;
    114. pcl::VoxelGrid downSizeFilterICP;
    115. pcl::VoxelGrid downSizeFilterSurroundingKeyPoses; // for surrounding key poses of scan-to-map optimization
    116. ros::Time timeLaserInfoStamp;
    117. double timeLaserInfoCur;
    118. float transformTobeMapped[6];
    119. std::mutex mtx;
    120. std::mutex mtxLoopInfo;
    121. bool isDegenerate = false;
    122. cv::Mat matP;
    123. // 局部map角点数量
    124. int laserCloudCornerFromMapDSNum = 0;
    125. // 局部map平面点数量
    126. int laserCloudSurfFromMapDSNum = 0;
    127. // 当前激光帧角点数量
    128. int laserCloudCornerLastDSNum = 0;
    129. // 当前激光帧面点数量
    130. int laserCloudSurfLastDSNum = 0;
    131. bool aLoopIsClosed = false;
    132. map<int, int> loopIndexContainer; // from new to old
    133. vectorint, int>> loopIndexQueue;
    134. vector loopPoseQueue;
    135. vector loopNoiseQueue;
    136. deque loopInfoVec;
    137. nav_msgs::Path globalPath;
    138. // 当前帧位姿
    139. Eigen::Affine3f transPointAssociateToMap;
    140. // 前一帧位姿
    141. Eigen::Affine3f incrementalOdometryAffineFront;
    142. // 当前帧位姿
    143. Eigen::Affine3f incrementalOdometryAffineBack;
    144. /**
    145. * 构造函数
    146. */
    147. mapOptimization()
    148. {
    149. // ISM2参数
    150. ISAM2Params parameters;
    151. parameters.relinearizeThreshold = 0.1;
    152. parameters.relinearizeSkip = 1;
    153. isam = new ISAM2(parameters);
    154. // 发布历史关键帧里程计
    155. pubKeyPoses = nh.advertise("lio_sam/mapping/trajectory", 1);
    156. // 发布局部关键帧map的特征点云
    157. pubLaserCloudSurround = nh.advertise("lio_sam/mapping/map_global", 1);
    158. // 发布激光里程计,rviz中表现为坐标轴
    159. pubLaserOdometryGlobal = nh.advertise ("lio_sam/mapping/odometry", 1);
    160. // 发布激光里程计,它与上面的激光里程计基本一样,只是roll、pitch用imu数据加权平均了一下,z做了限制
    161. pubLaserOdometryIncremental = nh.advertise ("lio_sam/mapping/odometry_incremental", 1);
    162. // 发布激光里程计路径,rviz中表现为载体的运行轨迹
    163. pubPath = nh.advertise("lio_sam/mapping/path", 1);
    164. // 订阅当前激光帧点云信息,来自featureExtraction
    165. subCloud = nh.subscribe("lio_sam/feature/cloud_info", 1, &mapOptimization::laserCloudInfoHandler, this, ros::TransportHints().tcpNoDelay());
    166. // 订阅GPS里程计
    167. subGPS = nh.subscribe (gpsTopic, 200, &mapOptimization::gpsHandler, this, ros::TransportHints().tcpNoDelay());
    168. // 订阅来自外部闭环检测程序提供的闭环数据,本程序没有提供,这里实际没用上
    169. subLoop = nh.subscribe("lio_loop/loop_closure_detection", 1, &mapOptimization::loopInfoHandler, this, ros::TransportHints().tcpNoDelay());
    170. // 发布地图保存服务
    171. srvSaveMap = nh.advertiseService("lio_sam/save_map", &mapOptimization::saveMapService, this);
    172. // 发布闭环匹配关键帧局部map
    173. pubHistoryKeyFrames = nh.advertise("lio_sam/mapping/icp_loop_closure_history_cloud", 1);
    174. // 发布当前关键帧经过闭环优化后的位姿变换之后的特征点云
    175. pubIcpKeyFrames = nh.advertise("lio_sam/mapping/icp_loop_closure_corrected_cloud", 1);
    176. // 发布闭环边,rviz中表现为闭环帧之间的连线
    177. pubLoopConstraintEdge = nh.advertise("/lio_sam/mapping/loop_closure_constraints", 1);
    178. // 发布局部map的降采样平面点集合
    179. pubRecentKeyFrames = nh.advertise("lio_sam/mapping/map_local", 1);
    180. // 发布历史帧(累加的)的角点、平面点降采样集合
    181. pubRecentKeyFrame = nh.advertise("lio_sam/mapping/cloud_registered", 1);
    182. // 发布当前帧原始点云配准之后的点云
    183. pubCloudRegisteredRaw = nh.advertise("lio_sam/mapping/cloud_registered_raw", 1);
    184. downSizeFilterCorner.setLeafSize(mappingCornerLeafSize, mappingCornerLeafSize, mappingCornerLeafSize);
    185. downSizeFilterSurf.setLeafSize(mappingSurfLeafSize, mappingSurfLeafSize, mappingSurfLeafSize);
    186. downSizeFilterICP.setLeafSize(mappingSurfLeafSize, mappingSurfLeafSize, mappingSurfLeafSize);
    187. downSizeFilterSurroundingKeyPoses.setLeafSize(surroundingKeyframeDensity, surroundingKeyframeDensity, surroundingKeyframeDensity); // for surrounding key poses of scan-to-map optimization
    188. allocateMemory();
    189. }
    190. /**
    191. * 初始化
    192. */
    193. void allocateMemory()
    194. {
    195. cloudKeyPoses3D.reset(new pcl::PointCloud());
    196. cloudKeyPoses6D.reset(new pcl::PointCloud());
    197. copy_cloudKeyPoses3D.reset(new pcl::PointCloud());
    198. copy_cloudKeyPoses6D.reset(new pcl::PointCloud());
    199. kdtreeSurroundingKeyPoses.reset(new pcl::KdTreeFLANN());
    200. kdtreeHistoryKeyPoses.reset(new pcl::KdTreeFLANN());
    201. laserCloudCornerLast.reset(new pcl::PointCloud()); // corner feature set from odoOptimization
    202. laserCloudSurfLast.reset(new pcl::PointCloud()); // surf feature set from odoOptimization
    203. laserCloudCornerLastDS.reset(new pcl::PointCloud()); // downsampled corner featuer set from odoOptimization
    204. laserCloudSurfLastDS.reset(new pcl::PointCloud()); // downsampled surf featuer set from odoOptimization
    205. laserCloudOri.reset(new pcl::PointCloud());
    206. coeffSel.reset(new pcl::PointCloud());
    207. laserCloudOriCornerVec.resize(N_SCAN * Horizon_SCAN);
    208. coeffSelCornerVec.resize(N_SCAN * Horizon_SCAN);
    209. laserCloudOriCornerFlag.resize(N_SCAN * Horizon_SCAN);
    210. laserCloudOriSurfVec.resize(N_SCAN * Horizon_SCAN);
    211. coeffSelSurfVec.resize(N_SCAN * Horizon_SCAN);
    212. laserCloudOriSurfFlag.resize(N_SCAN * Horizon_SCAN);
    213. std::fill(laserCloudOriCornerFlag.begin(), laserCloudOriCornerFlag.end(), false);
    214. std::fill(laserCloudOriSurfFlag.begin(), laserCloudOriSurfFlag.end(), false);
    215. laserCloudCornerFromMap.reset(new pcl::PointCloud());
    216. laserCloudSurfFromMap.reset(new pcl::PointCloud());
    217. laserCloudCornerFromMapDS.reset(new pcl::PointCloud());
    218. laserCloudSurfFromMapDS.reset(new pcl::PointCloud());
    219. kdtreeCornerFromMap.reset(new pcl::KdTreeFLANN());
    220. kdtreeSurfFromMap.reset(new pcl::KdTreeFLANN());
    221. for (int i = 0; i < 6; ++i){
    222. transformTobeMapped[i] = 0;
    223. }
    224. matP = cv::Mat(6, 6, CV_32F, cv::Scalar::all(0));
    225. }
    226. /**
    227. * 订阅当前激光帧点云信息,来自featureExtraction
    228. * 1、当前帧位姿初始化
    229. * 1) 如果是第一帧,用原始imu数据的RPY初始化当前帧位姿(旋转部分)
    230. * 2) 后续帧,用imu里程计计算两帧之间的增量位姿变换,作用于前一帧的激光位姿,得到当前帧激光位姿
    231. * 2、提取局部角点、平面点云集合,加入局部map
    232. * 1) 对最近的一帧关键帧,搜索时空维度上相邻的关键帧集合,降采样一下
    233. * 2) 对关键帧集合中的每一帧,提取对应的角点、平面点,加入局部map中
    234. * 3、当前激光帧角点、平面点集合降采样
    235. * 4、scan-to-map优化当前帧位姿
    236. * (1) 要求当前帧特征点数量足够多,且匹配的点数够多,才执行优化
    237. * (2) 迭代30次(上限)优化
    238. * 1) 当前激光帧角点寻找局部map匹配点
    239. * a.更新当前帧位姿,将当前帧角点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成直线(用距离中心点的协方差矩阵,特征值进行判断),则认为匹配上了
    240. * b.计算当前帧角点到直线的距离、垂线的单位向量,存储为角点参数
    241. * 2) 当前激光帧平面点寻找局部map匹配点
    242. * a.更新当前帧位姿,将当前帧平面点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成平面(最小二乘拟合平面),则认为匹配上了
    243. * b.计算当前帧平面点到平面的距离、垂线的单位向量,存储为平面点参数
    244. * 3) 提取当前帧中与局部map匹配上了的角点、平面点,加入同一集合
    245. * 4) 对匹配特征点计算Jacobian矩阵,观测值为特征点到直线、平面的距离,构建高斯牛顿方程,迭代优化当前位姿,存transformTobeMapped
    246. * (3)用imu原始RPY数据与scan-to-map优化后的位姿进行加权融合,更新当前帧位姿的roll、pitch,约束z坐标
    247. * 5、设置当前帧为关键帧并执行因子图优化
    248. * 1) 计算当前帧与前一帧位姿变换,如果变化太小,不设为关键帧,反之设为关键帧
    249. * 2) 添加激光里程计因子、GPS因子、闭环因子
    250. * 3) 执行因子图优化
    251. * 4) 得到当前帧优化后位姿,位姿协方差
    252. * 5) 添加cloudKeyPoses3D,cloudKeyPoses6D,更新transformTobeMapped,添加当前关键帧的角点、平面点集合
    253. * 6、更新因子图中所有变量节点的位姿,也就是所有历史关键帧的位姿,更新里程计轨迹
    254. * 7、发布激光里程计
    255. * 8、发布里程计、点云、轨迹
    256. */
    257. void laserCloudInfoHandler(const lio_sam::cloud_infoConstPtr& msgIn)
    258. {
    259. // 当前激光帧时间戳
    260. timeLaserInfoStamp = msgIn->header.stamp;
    261. timeLaserInfoCur = msgIn->header.stamp.toSec();
    262. // 提取当前激光帧角点、平面点集合
    263. cloudInfo = *msgIn;
    264. pcl::fromROSMsg(msgIn->cloud_corner, *laserCloudCornerLast);
    265. pcl::fromROSMsg(msgIn->cloud_surface, *laserCloudSurfLast);
    266. std::lock_guard lock(mtx);
    267. // mapping执行频率控制
    268. static double timeLastProcessing = -1;
    269. if (timeLaserInfoCur - timeLastProcessing >= mappingProcessInterval)
    270. {
    271. timeLastProcessing = timeLaserInfoCur;
    272. // 当前帧位姿初始化
    273. // 1、如果是第一帧,用原始imu数据的RPY初始化当前帧位姿(旋转部分)
    274. // 2、后续帧,用imu里程计计算两帧之间的增量位姿变换,作用于前一帧的激光位姿,得到当前帧激光位姿
    275. updateInitialGuess();
    276. // 提取局部角点、平面点云集合,加入局部map
    277. // 1、对最近的一帧关键帧,搜索时空维度上相邻的关键帧集合,降采样一下
    278. // 2、对关键帧集合中的每一帧,提取对应的角点、平面点,加入局部map中
    279. extractSurroundingKeyFrames();
    280. // 当前激光帧角点、平面点集合降采样
    281. downsampleCurrentScan();
    282. // scan-to-map优化当前帧位姿
    283. // 1、要求当前帧特征点数量足够多,且匹配的点数够多,才执行优化
    284. // 2、迭代30次(上限)优化
    285. // 1) 当前激光帧角点寻找局部map匹配点
    286. // a.更新当前帧位姿,将当前帧角点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成直线(用距离中心点的协方差矩阵,特征值进行判断),则认为匹配上了
    287. // b.计算当前帧角点到直线的距离、垂线的单位向量,存储为角点参数
    288. // 2) 当前激光帧平面点寻找局部map匹配点
    289. // a.更新当前帧位姿,将当前帧平面点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成平面(最小二乘拟合平面),则认为匹配上了
    290. // b.计算当前帧平面点到平面的距离、垂线的单位向量,存储为平面点参数
    291. // 3) 提取当前帧中与局部map匹配上了的角点、平面点,加入同一集合
    292. // 4) 对匹配特征点计算Jacobian矩阵,观测值为特征点到直线、平面的距离,构建高斯牛顿方程,迭代优化当前位姿,存transformTobeMapped
    293. // 3、用imu原始RPY数据与scan-to-map优化后的位姿进行加权融合,更新当前帧位姿的roll、pitch,约束z坐标
    294. scan2MapOptimization();
    295. // 设置当前帧为关键帧并执行因子图优化
    296. // 1、计算当前帧与前一帧位姿变换,如果变化太小,不设为关键帧,反之设为关键帧
    297. // 2、添加激光里程计因子、GPS因子、闭环因子
    298. // 3、执行因子图优化
    299. // 4、得到当前帧优化后位姿,位姿协方差
    300. // 5、添加cloudKeyPoses3D,cloudKeyPoses6D,更新transformTobeMapped,添加当前关键帧的角点、平面点集合
    301. saveKeyFramesAndFactor();
    302. // 更新因子图中所有变量节点的位姿,也就是所有历史关键帧的位姿,更新里程计轨迹
    303. correctPoses();
    304. // 发布激光里程计
    305. publishOdometry();
    306. // 发布里程计、点云、轨迹
    307. // 1、发布历史关键帧位姿集合
    308. // 2、发布局部map的降采样平面点集合
    309. // 3、发布历史帧(累加的)的角点、平面点降采样集合
    310. // 4、发布里程计轨迹
    311. publishFrames();
    312. }
    313. }
    314. /**
    315. * 订阅GPS里程计,添加到GPS里程计队列
    316. */
    317. void gpsHandler(const nav_msgs::Odometry::ConstPtr& gpsMsg)
    318. {
    319. gpsQueue.push_back(*gpsMsg);
    320. }
    321. /**
    322. * 激光坐标系下的激光点,通过激光帧位姿,变换到世界坐标系下
    323. */
    324. void pointAssociateToMap(PointType const * const pi, PointType * const po)
    325. {
    326. po->x = transPointAssociateToMap(0,0) * pi->x + transPointAssociateToMap(0,1) * pi->y + transPointAssociateToMap(0,2) * pi->z + transPointAssociateToMap(0,3);
    327. po->y = transPointAssociateToMap(1,0) * pi->x + transPointAssociateToMap(1,1) * pi->y + transPointAssociateToMap(1,2) * pi->z + transPointAssociateToMap(1,3);
    328. po->z = transPointAssociateToMap(2,0) * pi->x + transPointAssociateToMap(2,1) * pi->y + transPointAssociateToMap(2,2) * pi->z + transPointAssociateToMap(2,3);
    329. po->intensity = pi->intensity;
    330. }
    331. /**
    332. * 对点云cloudIn进行变换transformIn,返回结果点云
    333. */
    334. pcl::PointCloud::Ptr transformPointCloud(pcl::PointCloud::Ptr cloudIn, PointTypePose* transformIn)
    335. {
    336. pcl::PointCloud::Ptr cloudOut(new pcl::PointCloud());
    337. int cloudSize = cloudIn->size();
    338. cloudOut->resize(cloudSize);
    339. Eigen::Affine3f transCur = pcl::getTransformation(transformIn->x, transformIn->y, transformIn->z, transformIn->roll, transformIn->pitch, transformIn->yaw);
    340. #pragma omp parallel for num_threads(numberOfCores)
    341. for (int i = 0; i < cloudSize; ++i)
    342. {
    343. const auto &pointFrom = cloudIn->points[i];
    344. cloudOut->points[i].x = transCur(0,0) * pointFrom.x + transCur(0,1) * pointFrom.y + transCur(0,2) * pointFrom.z + transCur(0,3);
    345. cloudOut->points[i].y = transCur(1,0) * pointFrom.x + transCur(1,1) * pointFrom.y + transCur(1,2) * pointFrom.z + transCur(1,3);
    346. cloudOut->points[i].z = transCur(2,0) * pointFrom.x + transCur(2,1) * pointFrom.y + transCur(2,2) * pointFrom.z + transCur(2,3);
    347. cloudOut->points[i].intensity = pointFrom.intensity;
    348. }
    349. return cloudOut;
    350. }
    351. /**
    352. * 位姿格式变换
    353. */
    354. gtsam::Pose3 pclPointTogtsamPose3(PointTypePose thisPoint)
    355. {
    356. return gtsam::Pose3(gtsam::Rot3::RzRyRx(double(thisPoint.roll), double(thisPoint.pitch), double(thisPoint.yaw)),
    357. gtsam::Point3(double(thisPoint.x), double(thisPoint.y), double(thisPoint.z)));
    358. }
    359. /**
    360. * 位姿格式变换
    361. */
    362. gtsam::Pose3 trans2gtsamPose(float transformIn[])
    363. {
    364. return gtsam::Pose3(gtsam::Rot3::RzRyRx(transformIn[0], transformIn[1], transformIn[2]),
    365. gtsam::Point3(transformIn[3], transformIn[4], transformIn[5]));
    366. }
    367. /**
    368. * Eigen格式的位姿变换
    369. */
    370. Eigen::Affine3f pclPointToAffine3f(PointTypePose thisPoint)
    371. {
    372. return pcl::getTransformation(thisPoint.x, thisPoint.y, thisPoint.z, thisPoint.roll, thisPoint.pitch, thisPoint.yaw);
    373. }
    374. /**
    375. * Eigen格式的位姿变换
    376. */
    377. Eigen::Affine3f trans2Affine3f(float transformIn[])
    378. {
    379. return pcl::getTransformation(transformIn[3], transformIn[4], transformIn[5], transformIn[0], transformIn[1], transformIn[2]);
    380. }
    381. /**
    382. * 位姿格式变换
    383. */
    384. PointTypePose trans2PointTypePose(float transformIn[])
    385. {
    386. PointTypePose thisPose6D;
    387. thisPose6D.x = transformIn[3];
    388. thisPose6D.y = transformIn[4];
    389. thisPose6D.z = transformIn[5];
    390. thisPose6D.roll = transformIn[0];
    391. thisPose6D.pitch = transformIn[1];
    392. thisPose6D.yaw = transformIn[2];
    393. return thisPose6D;
    394. }
    395. /**
    396. * 保存全局关键帧特征点集合
    397. */
    398. bool saveMapService(lio_sam::save_mapRequest& req, lio_sam::save_mapResponse& res)
    399. {
    400. string saveMapDirectory;
    401. cout << "****************************************************" << endl;
    402. cout << "Saving map to pcd files ..." << endl;
    403. if(req.destination.empty()) saveMapDirectory = std::getenv("HOME") + savePCDDirectory;
    404. else saveMapDirectory = std::getenv("HOME") + req.destination;
    405. cout << "Save destination: " << saveMapDirectory << endl;
    406. // 这个代码太坑了!!注释掉
    407. // int unused = system((std::string("exec rm -r ") + saveMapDirectory).c_str());
    408. // unused = system((std::string("mkdir -p ") + saveMapDirectory).c_str());
    409. // 保存历史关键帧位姿
    410. pcl::io::savePCDFileBinary(saveMapDirectory + "/trajectory.pcd", *cloudKeyPoses3D);
    411. pcl::io::savePCDFileBinary(saveMapDirectory + "/transformations.pcd", *cloudKeyPoses6D);
    412. // 提取历史关键帧角点、平面点集合
    413. pcl::PointCloud::Ptr globalCornerCloud(new pcl::PointCloud());
    414. pcl::PointCloud::Ptr globalCornerCloudDS(new pcl::PointCloud());
    415. pcl::PointCloud::Ptr globalSurfCloud(new pcl::PointCloud());
    416. pcl::PointCloud::Ptr globalSurfCloudDS(new pcl::PointCloud());
    417. pcl::PointCloud::Ptr globalMapCloud(new pcl::PointCloud());
    418. for (int i = 0; i < (int)cloudKeyPoses3D->size(); i++) {
    419. *globalCornerCloud += *transformPointCloud(cornerCloudKeyFrames[i], &cloudKeyPoses6D->points[i]);
    420. *globalSurfCloud += *transformPointCloud(surfCloudKeyFrames[i], &cloudKeyPoses6D->points[i]);
    421. cout << "\r" << std::flush << "Processing feature cloud " << i << " of " << cloudKeyPoses6D->size() << " ...";
    422. }
    423. if(req.resolution != 0)
    424. {
    425. cout << "\n\nSave resolution: " << req.resolution << endl;
    426. // 降采样
    427. downSizeFilterCorner.setInputCloud(globalCornerCloud);
    428. downSizeFilterCorner.setLeafSize(req.resolution, req.resolution, req.resolution);
    429. downSizeFilterCorner.filter(*globalCornerCloudDS);
    430. pcl::io::savePCDFileBinary(saveMapDirectory + "/CornerMap.pcd", *globalCornerCloudDS);
    431. // 降采样
    432. downSizeFilterSurf.setInputCloud(globalSurfCloud);
    433. downSizeFilterSurf.setLeafSize(req.resolution, req.resolution, req.resolution);
    434. downSizeFilterSurf.filter(*globalSurfCloudDS);
    435. pcl::io::savePCDFileBinary(saveMapDirectory + "/SurfMap.pcd", *globalSurfCloudDS);
    436. }
    437. else
    438. {
    439. pcl::io::savePCDFileBinary(saveMapDirectory + "/CornerMap.pcd", *globalCornerCloud);
    440. pcl::io::savePCDFileBinary(saveMapDirectory + "/SurfMap.pcd", *globalSurfCloud);
    441. }
    442. // 保存到一起,全局关键帧特征点集合
    443. *globalMapCloud += *globalCornerCloud;
    444. *globalMapCloud += *globalSurfCloud;
    445. int ret = pcl::io::savePCDFileBinary(saveMapDirectory + "/GlobalMap.pcd", *globalMapCloud);
    446. res.success = ret == 0;
    447. downSizeFilterCorner.setLeafSize(mappingCornerLeafSize, mappingCornerLeafSize, mappingCornerLeafSize);
    448. downSizeFilterSurf.setLeafSize(mappingSurfLeafSize, mappingSurfLeafSize, mappingSurfLeafSize);
    449. cout << "****************************************************" << endl;
    450. cout << "Saving map to pcd files completed\n" << endl;
    451. return true;
    452. }
    453. /**
    454. * 展示线程
    455. * 1、发布局部关键帧map的特征点云
    456. * 2、保存全局关键帧特征点集合
    457. */
    458. void visualizeGlobalMapThread()
    459. {
    460. ros::Rate rate(0.2);
    461. while (ros::ok()){
    462. rate.sleep();
    463. // 发布局部关键帧map的特征点云
    464. publishGlobalMap();
    465. }
    466. if (savePCD == false)
    467. return;
    468. lio_sam::save_mapRequest req;
    469. lio_sam::save_mapResponse res;
    470. // 保存全局关键帧特征点集合
    471. if(!saveMapService(req, res)){
    472. cout << "Fail to save map" << endl;
    473. }
    474. }
    475. /**
    476. * 发布局部关键帧map的特征点云
    477. */
    478. void publishGlobalMap()
    479. {
    480. if (pubLaserCloudSurround.getNumSubscribers() == 0)
    481. return;
    482. if (cloudKeyPoses3D->points.empty() == true)
    483. return;
    484. pcl::KdTreeFLANN::Ptr kdtreeGlobalMap(new pcl::KdTreeFLANN());;
    485. pcl::PointCloud::Ptr globalMapKeyPoses(new pcl::PointCloud());
    486. pcl::PointCloud::Ptr globalMapKeyPosesDS(new pcl::PointCloud());
    487. pcl::PointCloud::Ptr globalMapKeyFrames(new pcl::PointCloud());
    488. pcl::PointCloud::Ptr globalMapKeyFramesDS(new pcl::PointCloud());
    489. // kdtree查找最近一帧关键帧相邻的关键帧集合
    490. std::vector<int> pointSearchIndGlobalMap;
    491. std::vector<float> pointSearchSqDisGlobalMap;
    492. mtx.lock();
    493. kdtreeGlobalMap->setInputCloud(cloudKeyPoses3D);
    494. kdtreeGlobalMap->radiusSearch(cloudKeyPoses3D->back(), globalMapVisualizationSearchRadius, pointSearchIndGlobalMap, pointSearchSqDisGlobalMap, 0);
    495. mtx.unlock();
    496. for (int i = 0; i < (int)pointSearchIndGlobalMap.size(); ++i)
    497. globalMapKeyPoses->push_back(cloudKeyPoses3D->points[pointSearchIndGlobalMap[i]]);
    498. // 降采样
    499. pcl::VoxelGrid downSizeFilterGlobalMapKeyPoses;
    500. downSizeFilterGlobalMapKeyPoses.setLeafSize(globalMapVisualizationPoseDensity, globalMapVisualizationPoseDensity, globalMapVisualizationPoseDensity); // for global map visualization
    501. downSizeFilterGlobalMapKeyPoses.setInputCloud(globalMapKeyPoses);
    502. downSizeFilterGlobalMapKeyPoses.filter(*globalMapKeyPosesDS);
    503. // 提取局部相邻关键帧对应的特征点云
    504. for (int i = 0; i < (int)globalMapKeyPosesDS->size(); ++i){
    505. // 距离过大
    506. if (pointDistance(globalMapKeyPosesDS->points[i], cloudKeyPoses3D->back()) > globalMapVisualizationSearchRadius)
    507. continue;
    508. int thisKeyInd = (int)globalMapKeyPosesDS->points[i].intensity;
    509. *globalMapKeyFrames += *transformPointCloud(cornerCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
    510. *globalMapKeyFrames += *transformPointCloud(surfCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
    511. }
    512. // 降采样,发布
    513. pcl::VoxelGrid downSizeFilterGlobalMapKeyFrames; // for global map visualization
    514. downSizeFilterGlobalMapKeyFrames.setLeafSize(globalMapVisualizationLeafSize, globalMapVisualizationLeafSize, globalMapVisualizationLeafSize); // for global map visualization
    515. downSizeFilterGlobalMapKeyFrames.setInputCloud(globalMapKeyFrames);
    516. downSizeFilterGlobalMapKeyFrames.filter(*globalMapKeyFramesDS);
    517. publishCloud(&pubLaserCloudSurround, globalMapKeyFramesDS, timeLaserInfoStamp, odometryFrame);
    518. }
    519. /**
    520. * 闭环线程
    521. * 1、闭环scan-to-map,icp优化位姿
    522. * 1) 在历史关键帧中查找与当前关键帧距离最近的关键帧集合,选择时间相隔较远的一帧作为候选闭环帧
    523. * 2) 提取当前关键帧特征点集合,降采样;提取闭环匹配关键帧前后相邻若干帧的关键帧特征点集合,降采样
    524. * 3) 执行scan-to-map优化,调用icp方法,得到优化后位姿,构造闭环因子需要的数据,在因子图优化中一并加入更新位姿
    525. * 2、rviz展示闭环边
    526. */
    527. void loopClosureThread()
    528. {
    529. if (loopClosureEnableFlag == false)
    530. return;
    531. ros::Rate rate(loopClosureFrequency);
    532. while (ros::ok())
    533. {
    534. rate.sleep();
    535. // 闭环scan-to-map,icp优化位姿
    536. // 1、在历史关键帧中查找与当前关键帧距离最近的关键帧集合,选择时间相隔较远的一帧作为候选闭环帧
    537. // 2、提取当前关键帧特征点集合,降采样;提取闭环匹配关键帧前后相邻若干帧的关键帧特征点集合,降采样
    538. // 3、执行scan-to-map优化,调用icp方法,得到优化后位姿,构造闭环因子需要的数据,在因子图优化中一并加入更新位姿
    539. // 注:闭环的时候没有立即更新当前帧的位姿,而是添加闭环因子,让图优化去更新位姿
    540. performLoopClosure();
    541. // rviz展示闭环边
    542. visualizeLoopClosure();
    543. }
    544. }
    545. /**
    546. * 订阅来自外部闭环检测程序提供的闭环数据,本程序没有提供,这里实际没用上
    547. */
    548. void loopInfoHandler(const std_msgs::Float64MultiArray::ConstPtr& loopMsg)
    549. {
    550. std::lock_guard lock(mtxLoopInfo);
    551. if (loopMsg->data.size() != 2)
    552. return;
    553. loopInfoVec.push_back(*loopMsg);
    554. while (loopInfoVec.size() > 5)
    555. loopInfoVec.pop_front();
    556. }
    557. /**
    558. * 闭环scan-to-map,icp优化位姿
    559. * 1、在历史关键帧中查找与当前关键帧距离最近的关键帧集合,选择时间相隔较远的一帧作为候选闭环帧
    560. * 2、提取当前关键帧特征点集合,降采样;提取闭环匹配关键帧前后相邻若干帧的关键帧特征点集合,降采样
    561. * 3、执行scan-to-map优化,调用icp方法,得到优化后位姿,构造闭环因子需要的数据,在因子图优化中一并加入更新位姿
    562. * 注:闭环的时候没有立即更新当前帧的位姿,而是添加闭环因子,让图优化去更新位姿
    563. */
    564. void performLoopClosure()
    565. {
    566. if (cloudKeyPoses3D->points.empty() == true)
    567. return;
    568. mtx.lock();
    569. *copy_cloudKeyPoses3D = *cloudKeyPoses3D;
    570. *copy_cloudKeyPoses6D = *cloudKeyPoses6D;
    571. mtx.unlock();
    572. // 当前关键帧索引,候选闭环匹配帧索引
    573. int loopKeyCur;
    574. int loopKeyPre;
    575. // not-used
    576. if (detectLoopClosureExternal(&loopKeyCur, &loopKeyPre) == false)
    577. // 在历史关键帧中查找与当前关键帧距离最近的关键帧集合,选择时间相隔较远的一帧作为候选闭环帧
    578. if (detectLoopClosureDistance(&loopKeyCur, &loopKeyPre) == false)
    579. return;
    580. // 提取
    581. pcl::PointCloud::Ptr cureKeyframeCloud(new pcl::PointCloud());
    582. pcl::PointCloud::Ptr prevKeyframeCloud(new pcl::PointCloud());
    583. {
    584. // 提取当前关键帧特征点集合,降采样
    585. loopFindNearKeyframes(cureKeyframeCloud, loopKeyCur, 0);
    586. // 提取闭环匹配关键帧前后相邻若干帧的关键帧特征点集合,降采样
    587. loopFindNearKeyframes(prevKeyframeCloud, loopKeyPre, historyKeyframeSearchNum);
    588. // 如果特征点较少,返回
    589. if (cureKeyframeCloud->size() < 300 || prevKeyframeCloud->size() < 1000)
    590. return;
    591. // 发布闭环匹配关键帧局部map
    592. if (pubHistoryKeyFrames.getNumSubscribers() != 0)
    593. publishCloud(&pubHistoryKeyFrames, prevKeyframeCloud, timeLaserInfoStamp, odometryFrame);
    594. }
    595. // ICP参数设置
    596. static pcl::IterativeClosestPoint icp;
    597. icp.setMaxCorrespondenceDistance(historyKeyframeSearchRadius*2);
    598. icp.setMaximumIterations(100);
    599. icp.setTransformationEpsilon(1e-6);
    600. icp.setEuclideanFitnessEpsilon(1e-6);
    601. icp.setRANSACIterations(0);
    602. // scan-to-map,调用icp匹配
    603. icp.setInputSource(cureKeyframeCloud);
    604. icp.setInputTarget(prevKeyframeCloud);
    605. pcl::PointCloud::Ptr unused_result(new pcl::PointCloud());
    606. icp.align(*unused_result);
    607. // 未收敛,或者匹配不够好
    608. if (icp.hasConverged() == false || icp.getFitnessScore() > historyKeyframeFitnessScore)
    609. return;
    610. // 发布当前关键帧经过闭环优化后的位姿变换之后的特征点云
    611. if (pubIcpKeyFrames.getNumSubscribers() != 0)
    612. {
    613. pcl::PointCloud::Ptr closed_cloud(new pcl::PointCloud());
    614. pcl::transformPointCloud(*cureKeyframeCloud, *closed_cloud, icp.getFinalTransformation());
    615. publishCloud(&pubIcpKeyFrames, closed_cloud, timeLaserInfoStamp, odometryFrame);
    616. }
    617. // 闭环优化得到的当前关键帧与闭环关键帧之间的位姿变换
    618. float x, y, z, roll, pitch, yaw;
    619. Eigen::Affine3f correctionLidarFrame;
    620. correctionLidarFrame = icp.getFinalTransformation();
    621. // 闭环优化前当前帧位姿
    622. Eigen::Affine3f tWrong = pclPointToAffine3f(copy_cloudKeyPoses6D->points[loopKeyCur]);
    623. // 闭环优化后当前帧位姿
    624. Eigen::Affine3f tCorrect = correctionLidarFrame * tWrong;
    625. pcl::getTranslationAndEulerAngles (tCorrect, x, y, z, roll, pitch, yaw);
    626. gtsam::Pose3 poseFrom = Pose3(Rot3::RzRyRx(roll, pitch, yaw), Point3(x, y, z));
    627. // 闭环匹配帧的位姿
    628. gtsam::Pose3 poseTo = pclPointTogtsamPose3(copy_cloudKeyPoses6D->points[loopKeyPre]);
    629. gtsam::Vector Vector6(6);
    630. float noiseScore = icp.getFitnessScore();
    631. Vector6 << noiseScore, noiseScore, noiseScore, noiseScore, noiseScore, noiseScore;
    632. noiseModel::Diagonal::shared_ptr constraintNoise = noiseModel::Diagonal::Variances(Vector6);
    633. // 添加闭环因子需要的数据
    634. mtx.lock();
    635. loopIndexQueue.push_back(make_pair(loopKeyCur, loopKeyPre));
    636. loopPoseQueue.push_back(poseFrom.between(poseTo));
    637. loopNoiseQueue.push_back(constraintNoise);
    638. mtx.unlock();
    639. loopIndexContainer[loopKeyCur] = loopKeyPre;
    640. }
    641. /**
    642. * 在历史关键帧中查找与当前关键帧距离最近的关键帧集合,选择时间相隔较远的一帧作为候选闭环帧
    643. */
    644. bool detectLoopClosureDistance(int *latestID, int *closestID)
    645. {
    646. // 当前关键帧帧
    647. int loopKeyCur = copy_cloudKeyPoses3D->size() - 1;
    648. int loopKeyPre = -1;
    649. // 当前帧已经添加过闭环对应关系,不再继续添加
    650. auto it = loopIndexContainer.find(loopKeyCur);
    651. if (it != loopIndexContainer.end())
    652. return false;
    653. // 在历史关键帧中查找与当前关键帧距离最近的关键帧集合
    654. std::vector<int> pointSearchIndLoop;
    655. std::vector<float> pointSearchSqDisLoop;
    656. kdtreeHistoryKeyPoses->setInputCloud(copy_cloudKeyPoses3D);
    657. kdtreeHistoryKeyPoses->radiusSearch(copy_cloudKeyPoses3D->back(), historyKeyframeSearchRadius, pointSearchIndLoop, pointSearchSqDisLoop, 0);
    658. // 在候选关键帧集合中,找到与当前帧时间相隔较远的帧,设为候选匹配帧
    659. for (int i = 0; i < (int)pointSearchIndLoop.size(); ++i)
    660. {
    661. int id = pointSearchIndLoop[i];
    662. if (abs(copy_cloudKeyPoses6D->points[id].time - timeLaserInfoCur) > historyKeyframeSearchTimeDiff)
    663. {
    664. loopKeyPre = id;
    665. break;
    666. }
    667. }
    668. if (loopKeyPre == -1 || loopKeyCur == loopKeyPre)
    669. return false;
    670. *latestID = loopKeyCur;
    671. *closestID = loopKeyPre;
    672. return true;
    673. }
    674. /**
    675. * not-used, 来自外部闭环检测程序提供的闭环匹配索引对
    676. */
    677. bool detectLoopClosureExternal(int *latestID, int *closestID)
    678. {
    679. // this function is not used yet, please ignore it
    680. int loopKeyCur = -1;
    681. int loopKeyPre = -1;
    682. std::lock_guard lock(mtxLoopInfo);
    683. if (loopInfoVec.empty())
    684. return false;
    685. double loopTimeCur = loopInfoVec.front().data[0];
    686. double loopTimePre = loopInfoVec.front().data[1];
    687. loopInfoVec.pop_front();
    688. if (abs(loopTimeCur - loopTimePre) < historyKeyframeSearchTimeDiff)
    689. return false;
    690. int cloudSize = copy_cloudKeyPoses6D->size();
    691. if (cloudSize < 2)
    692. return false;
    693. // latest key
    694. loopKeyCur = cloudSize - 1;
    695. for (int i = cloudSize - 1; i >= 0; --i)
    696. {
    697. if (copy_cloudKeyPoses6D->points[i].time >= loopTimeCur)
    698. loopKeyCur = round(copy_cloudKeyPoses6D->points[i].intensity);
    699. else
    700. break;
    701. }
    702. // previous key
    703. loopKeyPre = 0;
    704. for (int i = 0; i < cloudSize; ++i)
    705. {
    706. if (copy_cloudKeyPoses6D->points[i].time <= loopTimePre)
    707. loopKeyPre = round(copy_cloudKeyPoses6D->points[i].intensity);
    708. else
    709. break;
    710. }
    711. if (loopKeyCur == loopKeyPre)
    712. return false;
    713. auto it = loopIndexContainer.find(loopKeyCur);
    714. if (it != loopIndexContainer.end())
    715. return false;
    716. *latestID = loopKeyCur;
    717. *closestID = loopKeyPre;
    718. return true;
    719. }
    720. /**
    721. * 提取key索引的关键帧前后相邻若干帧的关键帧特征点集合,降采样
    722. */
    723. void loopFindNearKeyframes(pcl::PointCloud::Ptr& nearKeyframes, const int& key, const int& searchNum)
    724. {
    725. // 提取key索引的关键帧前后相邻若干帧的关键帧特征点集合
    726. nearKeyframes->clear();
    727. int cloudSize = copy_cloudKeyPoses6D->size();
    728. for (int i = -searchNum; i <= searchNum; ++i)
    729. {
    730. int keyNear = key + i;
    731. if (keyNear < 0 || keyNear >= cloudSize )
    732. continue;
    733. *nearKeyframes += *transformPointCloud(cornerCloudKeyFrames[keyNear], ©_cloudKeyPoses6D->points[keyNear]);
    734. *nearKeyframes += *transformPointCloud(surfCloudKeyFrames[keyNear], ©_cloudKeyPoses6D->points[keyNear]);
    735. }
    736. if (nearKeyframes->empty())
    737. return;
    738. // 降采样
    739. pcl::PointCloud::Ptr cloud_temp(new pcl::PointCloud());
    740. downSizeFilterICP.setInputCloud(nearKeyframes);
    741. downSizeFilterICP.filter(*cloud_temp);
    742. *nearKeyframes = *cloud_temp;
    743. }
    744. /**
    745. * rviz展示闭环边
    746. */
    747. void visualizeLoopClosure()
    748. {
    749. if (loopIndexContainer.empty())
    750. return;
    751. visualization_msgs::MarkerArray markerArray;
    752. // 闭环顶点
    753. visualization_msgs::Marker markerNode;
    754. markerNode.header.frame_id = odometryFrame;
    755. markerNode.header.stamp = timeLaserInfoStamp;
    756. markerNode.action = visualization_msgs::Marker::ADD;
    757. markerNode.type = visualization_msgs::Marker::SPHERE_LIST;
    758. markerNode.ns = "loop_nodes";
    759. markerNode.id = 0;
    760. markerNode.pose.orientation.w = 1;
    761. markerNode.scale.x = 0.3; markerNode.scale.y = 0.3; markerNode.scale.z = 0.3;
    762. markerNode.color.r = 0; markerNode.color.g = 0.8; markerNode.color.b = 1;
    763. markerNode.color.a = 1;
    764. // 闭环边
    765. visualization_msgs::Marker markerEdge;
    766. markerEdge.header.frame_id = odometryFrame;
    767. markerEdge.header.stamp = timeLaserInfoStamp;
    768. markerEdge.action = visualization_msgs::Marker::ADD;
    769. markerEdge.type = visualization_msgs::Marker::LINE_LIST;
    770. markerEdge.ns = "loop_edges";
    771. markerEdge.id = 1;
    772. markerEdge.pose.orientation.w = 1;
    773. markerEdge.scale.x = 0.1;
    774. markerEdge.color.r = 0.9; markerEdge.color.g = 0.9; markerEdge.color.b = 0;
    775. markerEdge.color.a = 1;
    776. // 遍历闭环
    777. for (auto it = loopIndexContainer.begin(); it != loopIndexContainer.end(); ++it)
    778. {
    779. int key_cur = it->first;
    780. int key_pre = it->second;
    781. geometry_msgs::Point p;
    782. p.x = copy_cloudKeyPoses6D->points[key_cur].x;
    783. p.y = copy_cloudKeyPoses6D->points[key_cur].y;
    784. p.z = copy_cloudKeyPoses6D->points[key_cur].z;
    785. markerNode.points.push_back(p);
    786. markerEdge.points.push_back(p);
    787. p.x = copy_cloudKeyPoses6D->points[key_pre].x;
    788. p.y = copy_cloudKeyPoses6D->points[key_pre].y;
    789. p.z = copy_cloudKeyPoses6D->points[key_pre].z;
    790. markerNode.points.push_back(p);
    791. markerEdge.points.push_back(p);
    792. }
    793. markerArray.markers.push_back(markerNode);
    794. markerArray.markers.push_back(markerEdge);
    795. pubLoopConstraintEdge.publish(markerArray);
    796. }
    797. /**
    798. * 当前帧位姿初始化
    799. * 1、如果是第一帧,用原始imu数据的RPY初始化当前帧位姿(旋转部分)
    800. * 2、后续帧,用imu里程计计算两帧之间的增量位姿变换,作用于前一帧的激光位姿,得到当前帧激光位姿
    801. */
    802. void updateInitialGuess()
    803. {
    804. // 前一帧的位姿,注:这里指lidar的位姿,后面都简写成位姿
    805. incrementalOdometryAffineFront = trans2Affine3f(transformTobeMapped);
    806. // 前一帧的初始化姿态角(来自原始imu数据),用于估计第一帧的位姿(旋转部分)
    807. static Eigen::Affine3f lastImuTransformation;
    808. // 如果关键帧集合为空,继续进行初始化
    809. if (cloudKeyPoses3D->points.empty())
    810. {
    811. // 当前帧位姿的旋转部分,用激光帧信息中的RPY(来自imu原始数据)初始化
    812. transformTobeMapped[0] = cloudInfo.imuRollInit;
    813. transformTobeMapped[1] = cloudInfo.imuPitchInit;
    814. transformTobeMapped[2] = cloudInfo.imuYawInit;
    815. if (!useImuHeadingInitialization)
    816. transformTobeMapped[2] = 0;
    817. lastImuTransformation = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit);
    818. return;
    819. }
    820. // 用当前帧和前一帧对应的imu里程计计算相对位姿变换,再用前一帧的位姿与相对变换,计算当前帧的位姿,存transformTobeMapped
    821. static bool lastImuPreTransAvailable = false;
    822. static Eigen::Affine3f lastImuPreTransformation;
    823. if (cloudInfo.odomAvailable == true)
    824. {
    825. // 当前帧的初始估计位姿(来自imu里程计),后面用来计算增量位姿变换
    826. Eigen::Affine3f transBack = pcl::getTransformation(cloudInfo.initialGuessX, cloudInfo.initialGuessY, cloudInfo.initialGuessZ,
    827. cloudInfo.initialGuessRoll, cloudInfo.initialGuessPitch, cloudInfo.initialGuessYaw);
    828. if (lastImuPreTransAvailable == false)
    829. {
    830. // 赋值给前一帧
    831. lastImuPreTransformation = transBack;
    832. lastImuPreTransAvailable = true;
    833. } else {
    834. // 当前帧相对于前一帧的位姿变换,imu里程计计算得到
    835. Eigen::Affine3f transIncre = lastImuPreTransformation.inverse() * transBack;
    836. // 前一帧的位姿
    837. Eigen::Affine3f transTobe = trans2Affine3f(transformTobeMapped);
    838. // 当前帧的位姿
    839. Eigen::Affine3f transFinal = transTobe * transIncre;
    840. // 更新当前帧位姿transformTobeMapped
    841. pcl::getTranslationAndEulerAngles(transFinal, transformTobeMapped[3], transformTobeMapped[4], transformTobeMapped[5],
    842. transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
    843. // 赋值给前一帧
    844. lastImuPreTransformation = transBack;
    845. lastImuTransformation = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit); // save imu before return;
    846. return;
    847. }
    848. }
    849. // 只在第一帧调用(注意上面的return),用imu数据初始化当前帧位姿,仅初始化旋转部分
    850. if (cloudInfo.imuAvailable == true)
    851. {
    852. // 当前帧的姿态角(来自原始imu数据)
    853. Eigen::Affine3f transBack = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit);
    854. // 当前帧相对于前一帧的姿态变换
    855. Eigen::Affine3f transIncre = lastImuTransformation.inverse() * transBack;
    856. // 前一帧的位姿
    857. Eigen::Affine3f transTobe = trans2Affine3f(transformTobeMapped);
    858. // 当前帧的位姿
    859. Eigen::Affine3f transFinal = transTobe * transIncre;
    860. // 更新当前帧位姿transformTobeMapped
    861. pcl::getTranslationAndEulerAngles(transFinal, transformTobeMapped[3], transformTobeMapped[4], transformTobeMapped[5],
    862. transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
    863. lastImuTransformation = pcl::getTransformation(0, 0, 0, cloudInfo.imuRollInit, cloudInfo.imuPitchInit, cloudInfo.imuYawInit); // save imu before return;
    864. return;
    865. }
    866. }
    867. /**
    868. * not-used
    869. */
    870. void extractForLoopClosure()
    871. {
    872. pcl::PointCloud::Ptr cloudToExtract(new pcl::PointCloud());
    873. //
    874. int numPoses = cloudKeyPoses3D->size();
    875. for (int i = numPoses-1; i >= 0; --i)
    876. {
    877. if ((int)cloudToExtract->size() <= surroundingKeyframeSize)
    878. cloudToExtract->push_back(cloudKeyPoses3D->points[i]);
    879. else
    880. break;
    881. }
    882. // 将相邻关键帧集合对应的角点、平面点,加入到局部map中,作为scan-to-map匹配的局部点云地图
    883. extractCloud(cloudToExtract);
    884. }
    885. /**
    886. * 提取局部角点、平面点云集合,加入局部map
    887. * 1、对最近的一帧关键帧,搜索时空维度上相邻的关键帧集合,降采样一下
    888. * 2、对关键帧集合中的每一帧,提取对应的角点、平面点,加入局部map中
    889. */
    890. void extractNearby()
    891. {
    892. pcl::PointCloud::Ptr surroundingKeyPoses(new pcl::PointCloud());
    893. pcl::PointCloud::Ptr surroundingKeyPosesDS(new pcl::PointCloud());
    894. std::vector<int> pointSearchInd;
    895. std::vector<float> pointSearchSqDis;
    896. // kdtree的输入,全局关键帧位姿集合(历史所有关键帧集合)
    897. kdtreeSurroundingKeyPoses->setInputCloud(cloudKeyPoses3D);
    898. // 对最近的一帧关键帧,在半径区域内搜索空间区域上相邻的关键帧集合
    899. kdtreeSurroundingKeyPoses->radiusSearch(cloudKeyPoses3D->back(), (double)surroundingKeyframeSearchRadius, pointSearchInd, pointSearchSqDis);
    900. // 遍历搜索结果,pointSearchInd存的是结果在cloudKeyPoses3D下面的索引
    901. for (int i = 0; i < (int)pointSearchInd.size(); ++i)
    902. {
    903. int id = pointSearchInd[i];
    904. // 加入相邻关键帧位姿集合中
    905. surroundingKeyPoses->push_back(cloudKeyPoses3D->points[id]);
    906. }
    907. // 降采样一下
    908. downSizeFilterSurroundingKeyPoses.setInputCloud(surroundingKeyPoses);
    909. downSizeFilterSurroundingKeyPoses.filter(*surroundingKeyPosesDS);
    910. // 加入时间上相邻的一些关键帧,比如当载体在原地转圈,这些帧加进来是合理的
    911. int numPoses = cloudKeyPoses3D->size();
    912. for (int i = numPoses-1; i >= 0; --i)
    913. {
    914. if (timeLaserInfoCur - cloudKeyPoses6D->points[i].time < 10.0)
    915. surroundingKeyPosesDS->push_back(cloudKeyPoses3D->points[i]);
    916. else
    917. break;
    918. }
    919. // 将相邻关键帧集合对应的角点、平面点,加入到局部map中,作为scan-to-map匹配的局部点云地图
    920. extractCloud(surroundingKeyPosesDS);
    921. }
    922. /**
    923. * 将相邻关键帧集合对应的角点、平面点,加入到局部map中,作为scan-to-map匹配的局部点云地图
    924. */
    925. void extractCloud(pcl::PointCloud::Ptr cloudToExtract)
    926. {
    927. // 相邻关键帧集合对应的角点、平面点,加入到局部map中;注:称之为局部map,后面进行scan-to-map匹配,所用到的map就是这里的相邻关键帧对应点云集合
    928. laserCloudCornerFromMap->clear();
    929. laserCloudSurfFromMap->clear();
    930. // 遍历当前帧(实际是取最近的一个关键帧来找它相邻的关键帧集合)时空维度上相邻的关键帧集合
    931. for (int i = 0; i < (int)cloudToExtract->size(); ++i)
    932. {
    933. // 距离超过阈值,丢弃
    934. if (pointDistance(cloudToExtract->points[i], cloudKeyPoses3D->back()) > surroundingKeyframeSearchRadius)
    935. continue;
    936. // 相邻关键帧索引
    937. int thisKeyInd = (int)cloudToExtract->points[i].intensity;
    938. if (laserCloudMapContainer.find(thisKeyInd) != laserCloudMapContainer.end())
    939. {
    940. *laserCloudCornerFromMap += laserCloudMapContainer[thisKeyInd].first;
    941. *laserCloudSurfFromMap += laserCloudMapContainer[thisKeyInd].second;
    942. } else {
    943. // 相邻关键帧对应的角点、平面点云,通过6D位姿变换到世界坐标系下
    944. pcl::PointCloud laserCloudCornerTemp = *transformPointCloud(cornerCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
    945. pcl::PointCloud laserCloudSurfTemp = *transformPointCloud(surfCloudKeyFrames[thisKeyInd], &cloudKeyPoses6D->points[thisKeyInd]);
    946. // 加入局部map
    947. *laserCloudCornerFromMap += laserCloudCornerTemp;
    948. *laserCloudSurfFromMap += laserCloudSurfTemp;
    949. laserCloudMapContainer[thisKeyInd] = make_pair(laserCloudCornerTemp, laserCloudSurfTemp);
    950. }
    951. }
    952. // 降采样局部角点map
    953. downSizeFilterCorner.setInputCloud(laserCloudCornerFromMap);
    954. downSizeFilterCorner.filter(*laserCloudCornerFromMapDS);
    955. laserCloudCornerFromMapDSNum = laserCloudCornerFromMapDS->size();
    956. // 降采样局部平面点map
    957. downSizeFilterSurf.setInputCloud(laserCloudSurfFromMap);
    958. downSizeFilterSurf.filter(*laserCloudSurfFromMapDS);
    959. laserCloudSurfFromMapDSNum = laserCloudSurfFromMapDS->size();
    960. // 太大了,清空一下内存
    961. if (laserCloudMapContainer.size() > 1000)
    962. laserCloudMapContainer.clear();
    963. }
    964. /**
    965. * 提取局部角点、平面点云集合,加入局部map
    966. * 1、对最近的一帧关键帧,搜索时空维度上相邻的关键帧集合,降采样一下
    967. * 2、对关键帧集合中的每一帧,提取对应的角点、平面点,加入局部map中
    968. */
    969. void extractSurroundingKeyFrames()
    970. {
    971. if (cloudKeyPoses3D->points.empty() == true)
    972. return;
    973. // if (loopClosureEnableFlag == true)
    974. // {
    975. // extractForLoopClosure();
    976. // } else {
    977. // extractNearby();
    978. // }
    979. // 提取局部角点、平面点云集合,加入局部map
    980. // 1、对最近的一帧关键帧,搜索时空维度上相邻的关键帧集合,降采样一下
    981. // 2、对关键帧集合中的每一帧,提取对应的角点、平面点,加入局部map中
    982. extractNearby();
    983. }
    984. /**
    985. * 当前激光帧角点、平面点集合降采样
    986. */
    987. void downsampleCurrentScan()
    988. {
    989. // 当前激光帧角点集合降采样
    990. laserCloudCornerLastDS->clear();
    991. downSizeFilterCorner.setInputCloud(laserCloudCornerLast);
    992. downSizeFilterCorner.filter(*laserCloudCornerLastDS);
    993. laserCloudCornerLastDSNum = laserCloudCornerLastDS->size();
    994. // 当前激光帧平面点集合降采样
    995. laserCloudSurfLastDS->clear();
    996. downSizeFilterSurf.setInputCloud(laserCloudSurfLast);
    997. downSizeFilterSurf.filter(*laserCloudSurfLastDS);
    998. laserCloudSurfLastDSNum = laserCloudSurfLastDS->size();
    999. }
    1000. /**
    1001. * 更新当前帧位姿
    1002. */
    1003. void updatePointAssociateToMap()
    1004. {
    1005. transPointAssociateToMap = trans2Affine3f(transformTobeMapped);
    1006. }
    1007. /**
    1008. * 当前激光帧角点寻找局部map匹配点
    1009. * 1、更新当前帧位姿,将当前帧角点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成直线(用距离中心点的协方差矩阵,特征值进行判断),则认为匹配上了
    1010. * 2、计算当前帧角点到直线的距离、垂线的单位向量,存储为角点参数
    1011. */
    1012. void cornerOptimization()
    1013. {
    1014. // 更新当前帧位姿
    1015. updatePointAssociateToMap();
    1016. // 遍历当前帧角点集合
    1017. #pragma omp parallel for num_threads(numberOfCores)
    1018. for (int i = 0; i < laserCloudCornerLastDSNum; i++)
    1019. {
    1020. PointType pointOri, pointSel, coeff;
    1021. std::vector<int> pointSearchInd;
    1022. std::vector<float> pointSearchSqDis;
    1023. // 角点(坐标还是lidar系)
    1024. pointOri = laserCloudCornerLastDS->points[i];
    1025. // 根据当前帧位姿,变换到世界坐标系(map系)下
    1026. pointAssociateToMap(&pointOri, &pointSel);
    1027. // 在局部角点map中查找当前角点相邻的5个角点
    1028. kdtreeCornerFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);
    1029. cv::Mat matA1(3, 3, CV_32F, cv::Scalar::all(0));
    1030. cv::Mat matD1(1, 3, CV_32F, cv::Scalar::all(0));
    1031. cv::Mat matV1(3, 3, CV_32F, cv::Scalar::all(0));
    1032. // 要求距离都小于1m
    1033. if (pointSearchSqDis[4] < 1.0) {
    1034. // 计算5个点的均值坐标,记为中心点
    1035. float cx = 0, cy = 0, cz = 0;
    1036. for (int j = 0; j < 5; j++) {
    1037. cx += laserCloudCornerFromMapDS->points[pointSearchInd[j]].x;
    1038. cy += laserCloudCornerFromMapDS->points[pointSearchInd[j]].y;
    1039. cz += laserCloudCornerFromMapDS->points[pointSearchInd[j]].z;
    1040. }
    1041. cx /= 5; cy /= 5; cz /= 5;
    1042. // 计算协方差
    1043. float a11 = 0, a12 = 0, a13 = 0, a22 = 0, a23 = 0, a33 = 0;
    1044. for (int j = 0; j < 5; j++) {
    1045. // 计算点与中心点之间的距离
    1046. float ax = laserCloudCornerFromMapDS->points[pointSearchInd[j]].x - cx;
    1047. float ay = laserCloudCornerFromMapDS->points[pointSearchInd[j]].y - cy;
    1048. float az = laserCloudCornerFromMapDS->points[pointSearchInd[j]].z - cz;
    1049. a11 += ax * ax; a12 += ax * ay; a13 += ax * az;
    1050. a22 += ay * ay; a23 += ay * az;
    1051. a33 += az * az;
    1052. }
    1053. a11 /= 5; a12 /= 5; a13 /= 5; a22 /= 5; a23 /= 5; a33 /= 5;
    1054. // 构建协方差矩阵
    1055. matA1.at<float>(0, 0) = a11; matA1.at<float>(0, 1) = a12; matA1.at<float>(0, 2) = a13;
    1056. matA1.at<float>(1, 0) = a12; matA1.at<float>(1, 1) = a22; matA1.at<float>(1, 2) = a23;
    1057. matA1.at<float>(2, 0) = a13; matA1.at<float>(2, 1) = a23; matA1.at<float>(2, 2) = a33;
    1058. // 特征值分解
    1059. cv::eigen(matA1, matD1, matV1);
    1060. // 如果最大的特征值相比次大特征值,大很多,认为构成了线,角点是合格的
    1061. if (matD1.at<float>(0, 0) > 3 * matD1.at<float>(0, 1)) {
    1062. // 当前帧角点坐标(map系下)
    1063. float x0 = pointSel.x;
    1064. float y0 = pointSel.y;
    1065. float z0 = pointSel.z;
    1066. // 局部map对应中心角点,沿着特征向量(直线方向)方向,前后各取一个点
    1067. float x1 = cx + 0.1 * matV1.at<float>(0, 0);
    1068. float y1 = cy + 0.1 * matV1.at<float>(0, 1);
    1069. float z1 = cz + 0.1 * matV1.at<float>(0, 2);
    1070. float x2 = cx - 0.1 * matV1.at<float>(0, 0);
    1071. float y2 = cy - 0.1 * matV1.at<float>(0, 1);
    1072. float z2 = cz - 0.1 * matV1.at<float>(0, 2);
    1073. // area_012,也就是三个点组成的三角形面积*2,叉积的模|axb|=a*b*sin(theta)
    1074. float a012 = sqrt(((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1)) * ((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))
    1075. + ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1)) * ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))
    1076. + ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1)) * ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1)));
    1077. // line_12,底边边长
    1078. float l12 = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2));
    1079. // 两次叉积,得到点到直线的垂线段单位向量,x分量,下面同理
    1080. float la = ((y1 - y2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))
    1081. + (z1 - z2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))) / a012 / l12;
    1082. float lb = -((x1 - x2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1))
    1083. - (z1 - z2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12;
    1084. float lc = -((x1 - x2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))
    1085. + (y1 - y2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12;
    1086. // 三角形的高,也就是点到直线距离
    1087. float ld2 = a012 / l12;
    1088. // 距离越大,s越小,是个距离惩罚因子(权重)
    1089. float s = 1 - 0.9 * fabs(ld2);
    1090. // 点到直线的垂线段单位向量
    1091. coeff.x = s * la;
    1092. coeff.y = s * lb;
    1093. coeff.z = s * lc;
    1094. // 点到直线距离
    1095. coeff.intensity = s * ld2;
    1096. if (s > 0.1) {
    1097. // 当前激光帧角点,加入匹配集合中
    1098. laserCloudOriCornerVec[i] = pointOri;
    1099. // 角点的参数
    1100. coeffSelCornerVec[i] = coeff;
    1101. laserCloudOriCornerFlag[i] = true;
    1102. }
    1103. }
    1104. }
    1105. }
    1106. }
    1107. /**
    1108. * 当前激光帧平面点寻找局部map匹配点
    1109. * 1、更新当前帧位姿,将当前帧平面点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成平面(最小二乘拟合平面),则认为匹配上了
    1110. * 2、计算当前帧平面点到平面的距离、垂线的单位向量,存储为平面点参数
    1111. */
    1112. void surfOptimization()
    1113. {
    1114. // 更新当前帧位姿
    1115. updatePointAssociateToMap();
    1116. // 遍历当前帧平面点集合
    1117. #pragma omp parallel for num_threads(numberOfCores)
    1118. for (int i = 0; i < laserCloudSurfLastDSNum; i++)
    1119. {
    1120. PointType pointOri, pointSel, coeff;
    1121. std::vector<int> pointSearchInd;
    1122. std::vector<float> pointSearchSqDis;
    1123. // 平面点(坐标还是lidar系)
    1124. pointOri = laserCloudSurfLastDS->points[i];
    1125. // 根据当前帧位姿,变换到世界坐标系(map系)下
    1126. pointAssociateToMap(&pointOri, &pointSel);
    1127. // 在局部平面点map中查找当前平面点相邻的5个平面点
    1128. kdtreeSurfFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis);
    1129. Eigen::Matrix<float, 5, 3> matA0;
    1130. Eigen::Matrix<float, 5, 1> matB0;
    1131. Eigen::Vector3f matX0;
    1132. matA0.setZero();
    1133. matB0.fill(-1);
    1134. matX0.setZero();
    1135. // 要求距离都小于1m
    1136. if (pointSearchSqDis[4] < 1.0) {
    1137. for (int j = 0; j < 5; j++) {
    1138. matA0(j, 0) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].x;
    1139. matA0(j, 1) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].y;
    1140. matA0(j, 2) = laserCloudSurfFromMapDS->points[pointSearchInd[j]].z;
    1141. }
    1142. // 假设平面方程为ax+by+cz+1=0,这里就是求方程的系数abc,d=1
    1143. matX0 = matA0.colPivHouseholderQr().solve(matB0);
    1144. // 平面方程的系数,也是法向量的分量
    1145. float pa = matX0(0, 0);
    1146. float pb = matX0(1, 0);
    1147. float pc = matX0(2, 0);
    1148. float pd = 1;
    1149. // 单位法向量
    1150. float ps = sqrt(pa * pa + pb * pb + pc * pc);
    1151. pa /= ps; pb /= ps; pc /= ps; pd /= ps;
    1152. // 检查平面是否合格,如果5个点中有点到平面的距离超过0.2m,那么认为这些点太分散了,不构成平面
    1153. bool planeValid = true;
    1154. for (int j = 0; j < 5; j++) {
    1155. if (fabs(pa * laserCloudSurfFromMapDS->points[pointSearchInd[j]].x +
    1156. pb * laserCloudSurfFromMapDS->points[pointSearchInd[j]].y +
    1157. pc * laserCloudSurfFromMapDS->points[pointSearchInd[j]].z + pd) > 0.2) {
    1158. planeValid = false;
    1159. break;
    1160. }
    1161. }
    1162. // 平面合格
    1163. if (planeValid) {
    1164. // 当前激光帧点到平面距离
    1165. float pd2 = pa * pointSel.x + pb * pointSel.y + pc * pointSel.z + pd;
    1166. float s = 1 - 0.9 * fabs(pd2) / sqrt(sqrt(pointSel.x * pointSel.x
    1167. + pointSel.y * pointSel.y + pointSel.z * pointSel.z));
    1168. // 点到平面垂线单位法向量(其实等价于平面法向量)
    1169. coeff.x = s * pa;
    1170. coeff.y = s * pb;
    1171. coeff.z = s * pc;
    1172. // 点到平面距离
    1173. coeff.intensity = s * pd2;
    1174. if (s > 0.1) {
    1175. // 当前激光帧平面点,加入匹配集合中
    1176. laserCloudOriSurfVec[i] = pointOri;
    1177. // 参数
    1178. coeffSelSurfVec[i] = coeff;
    1179. laserCloudOriSurfFlag[i] = true;
    1180. }
    1181. }
    1182. }
    1183. }
    1184. }
    1185. /**
    1186. * 提取当前帧中与局部map匹配上了的角点、平面点,加入同一集合
    1187. */
    1188. void combineOptimizationCoeffs()
    1189. {
    1190. // 遍历当前帧角点集合,提取出与局部map匹配上了的角点
    1191. for (int i = 0; i < laserCloudCornerLastDSNum; ++i){
    1192. if (laserCloudOriCornerFlag[i] == true){
    1193. laserCloudOri->push_back(laserCloudOriCornerVec[i]);
    1194. coeffSel->push_back(coeffSelCornerVec[i]);
    1195. }
    1196. }
    1197. // 遍历当前帧平面点集合,提取出与局部map匹配上了的平面点
    1198. for (int i = 0; i < laserCloudSurfLastDSNum; ++i){
    1199. if (laserCloudOriSurfFlag[i] == true){
    1200. laserCloudOri->push_back(laserCloudOriSurfVec[i]);
    1201. coeffSel->push_back(coeffSelSurfVec[i]);
    1202. }
    1203. }
    1204. // 清空标记
    1205. std::fill(laserCloudOriCornerFlag.begin(), laserCloudOriCornerFlag.end(), false);
    1206. std::fill(laserCloudOriSurfFlag.begin(), laserCloudOriSurfFlag.end(), false);
    1207. }
    1208. /**
    1209. * scan-to-map优化
    1210. * 对匹配特征点计算Jacobian矩阵,观测值为特征点到直线、平面的距离,构建高斯牛顿方程,迭代优化当前位姿,存transformTobeMapped
    1211. * 公式推导:todo
    1212. */
    1213. bool LMOptimization(int iterCount)
    1214. {
    1215. // This optimization is from the original loam_velodyne by Ji Zhang, need to cope with coordinate transformation
    1216. // lidar <- camera --- camera <- lidar
    1217. // x = z --- x = y
    1218. // y = x --- y = z
    1219. // z = y --- z = x
    1220. // roll = yaw --- roll = pitch
    1221. // pitch = roll --- pitch = yaw
    1222. // yaw = pitch --- yaw = roll
    1223. // lidar -> camera
    1224. float srx = sin(transformTobeMapped[1]);
    1225. float crx = cos(transformTobeMapped[1]);
    1226. float sry = sin(transformTobeMapped[2]);
    1227. float cry = cos(transformTobeMapped[2]);
    1228. float srz = sin(transformTobeMapped[0]);
    1229. float crz = cos(transformTobeMapped[0]);
    1230. // 当前帧匹配特征点数太少
    1231. int laserCloudSelNum = laserCloudOri->size();
    1232. if (laserCloudSelNum < 50) {
    1233. return false;
    1234. }
    1235. cv::Mat matA(laserCloudSelNum, 6, CV_32F, cv::Scalar::all(0));
    1236. cv::Mat matAt(6, laserCloudSelNum, CV_32F, cv::Scalar::all(0));
    1237. cv::Mat matAtA(6, 6, CV_32F, cv::Scalar::all(0));
    1238. cv::Mat matB(laserCloudSelNum, 1, CV_32F, cv::Scalar::all(0));
    1239. cv::Mat matAtB(6, 1, CV_32F, cv::Scalar::all(0));
    1240. cv::Mat matX(6, 1, CV_32F, cv::Scalar::all(0));
    1241. PointType pointOri, coeff;
    1242. // 遍历匹配特征点,构建Jacobian矩阵
    1243. for (int i = 0; i < laserCloudSelNum; i++) {
    1244. // lidar -> camera todo
    1245. pointOri.x = laserCloudOri->points[i].y;
    1246. pointOri.y = laserCloudOri->points[i].z;
    1247. pointOri.z = laserCloudOri->points[i].x;
    1248. // lidar -> camera
    1249. coeff.x = coeffSel->points[i].y;
    1250. coeff.y = coeffSel->points[i].z;
    1251. coeff.z = coeffSel->points[i].x;
    1252. coeff.intensity = coeffSel->points[i].intensity;
    1253. // in camera
    1254. float arx = (crx*sry*srz*pointOri.x + crx*crz*sry*pointOri.y - srx*sry*pointOri.z) * coeff.x
    1255. + (-srx*srz*pointOri.x - crz*srx*pointOri.y - crx*pointOri.z) * coeff.y
    1256. + (crx*cry*srz*pointOri.x + crx*cry*crz*pointOri.y - cry*srx*pointOri.z) * coeff.z;
    1257. float ary = ((cry*srx*srz - crz*sry)*pointOri.x
    1258. + (sry*srz + cry*crz*srx)*pointOri.y + crx*cry*pointOri.z) * coeff.x
    1259. + ((-cry*crz - srx*sry*srz)*pointOri.x
    1260. + (cry*srz - crz*srx*sry)*pointOri.y - crx*sry*pointOri.z) * coeff.z;
    1261. float arz = ((crz*srx*sry - cry*srz)*pointOri.x + (-cry*crz-srx*sry*srz)*pointOri.y)*coeff.x
    1262. + (crx*crz*pointOri.x - crx*srz*pointOri.y) * coeff.y
    1263. + ((sry*srz + cry*crz*srx)*pointOri.x + (crz*sry-cry*srx*srz)*pointOri.y)*coeff.z;
    1264. // lidar -> camera
    1265. matA.at<float>(i, 0) = arz;
    1266. matA.at<float>(i, 1) = arx;
    1267. matA.at<float>(i, 2) = ary;
    1268. matA.at<float>(i, 3) = coeff.z;
    1269. matA.at<float>(i, 4) = coeff.x;
    1270. matA.at<float>(i, 5) = coeff.y;
    1271. // 点到直线距离、平面距离,作为观测值
    1272. matB.at<float>(i, 0) = -coeff.intensity;
    1273. }
    1274. cv::transpose(matA, matAt);
    1275. matAtA = matAt * matA;
    1276. matAtB = matAt * matB;
    1277. // J^T·J·delta_x = -J^T·f 高斯牛顿
    1278. cv::solve(matAtA, matAtB, matX, cv::DECOMP_QR);
    1279. // 首次迭代,检查近似Hessian矩阵(J^T·J)是否退化,或者称为奇异,行列式值=0 todo
    1280. if (iterCount == 0) {
    1281. cv::Mat matE(1, 6, CV_32F, cv::Scalar::all(0));
    1282. cv::Mat matV(6, 6, CV_32F, cv::Scalar::all(0));
    1283. cv::Mat matV2(6, 6, CV_32F, cv::Scalar::all(0));
    1284. cv::eigen(matAtA, matE, matV);
    1285. matV.copyTo(matV2);
    1286. isDegenerate = false;
    1287. float eignThre[6] = {100, 100, 100, 100, 100, 100};
    1288. for (int i = 5; i >= 0; i--) {
    1289. if (matE.at<float>(0, i) < eignThre[i]) {
    1290. for (int j = 0; j < 6; j++) {
    1291. matV2.at<float>(i, j) = 0;
    1292. }
    1293. isDegenerate = true;
    1294. } else {
    1295. break;
    1296. }
    1297. }
    1298. matP = matV.inv() * matV2;
    1299. }
    1300. if (isDegenerate)
    1301. {
    1302. cv::Mat matX2(6, 1, CV_32F, cv::Scalar::all(0));
    1303. matX.copyTo(matX2);
    1304. matX = matP * matX2;
    1305. }
    1306. // 更新当前位姿 x = x + delta_x
    1307. transformTobeMapped[0] += matX.at<float>(0, 0);
    1308. transformTobeMapped[1] += matX.at<float>(1, 0);
    1309. transformTobeMapped[2] += matX.at<float>(2, 0);
    1310. transformTobeMapped[3] += matX.at<float>(3, 0);
    1311. transformTobeMapped[4] += matX.at<float>(4, 0);
    1312. transformTobeMapped[5] += matX.at<float>(5, 0);
    1313. float deltaR = sqrt(
    1314. pow(pcl::rad2deg(matX.at<float>(0, 0)), 2) +
    1315. pow(pcl::rad2deg(matX.at<float>(1, 0)), 2) +
    1316. pow(pcl::rad2deg(matX.at<float>(2, 0)), 2));
    1317. float deltaT = sqrt(
    1318. pow(matX.at<float>(3, 0) * 100, 2) +
    1319. pow(matX.at<float>(4, 0) * 100, 2) +
    1320. pow(matX.at<float>(5, 0) * 100, 2));
    1321. // delta_x很小,认为收敛
    1322. if (deltaR < 0.05 && deltaT < 0.05) {
    1323. return true;
    1324. }
    1325. return false;
    1326. }
    1327. /**
    1328. * scan-to-map优化当前帧位姿
    1329. * 1、要求当前帧特征点数量足够多,且匹配的点数够多,才执行优化
    1330. * 2、迭代30次(上限)优化
    1331. * 1) 当前激光帧角点寻找局部map匹配点
    1332. * a.更新当前帧位姿,将当前帧角点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成直线(用距离中心点的协方差矩阵,特征值进行判断),则认为匹配上了
    1333. * b.计算当前帧角点到直线的距离、垂线的单位向量,存储为角点参数
    1334. * 2) 当前激光帧平面点寻找局部map匹配点
    1335. * a.更新当前帧位姿,将当前帧平面点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成平面(最小二乘拟合平面),则认为匹配上了
    1336. * b.计算当前帧平面点到平面的距离、垂线的单位向量,存储为平面点参数
    1337. * 3) 提取当前帧中与局部map匹配上了的角点、平面点,加入同一集合
    1338. * 4) 对匹配特征点计算Jacobian矩阵,观测值为特征点到直线、平面的距离,构建高斯牛顿方程,迭代优化当前位姿,存transformTobeMapped
    1339. * 3、用imu原始RPY数据与scan-to-map优化后的位姿进行加权融合,更新当前帧位姿的roll、pitch,约束z坐标
    1340. */
    1341. void scan2MapOptimization()
    1342. {
    1343. // 要求有关键帧
    1344. if (cloudKeyPoses3D->points.empty())
    1345. return;
    1346. // 当前激光帧的角点、平面点数量足够多
    1347. if (laserCloudCornerLastDSNum > edgeFeatureMinValidNum && laserCloudSurfLastDSNum > surfFeatureMinValidNum)
    1348. {
    1349. // kdtree输入为局部map点云
    1350. kdtreeCornerFromMap->setInputCloud(laserCloudCornerFromMapDS);
    1351. kdtreeSurfFromMap->setInputCloud(laserCloudSurfFromMapDS);
    1352. // 迭代30次
    1353. for (int iterCount = 0; iterCount < 30; iterCount++)
    1354. {
    1355. // 每次迭代清空特征点集合
    1356. laserCloudOri->clear();
    1357. coeffSel->clear();
    1358. // 当前激光帧角点寻找局部map匹配点
    1359. // 1、更新当前帧位姿,将当前帧角点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成直线(用距离中心点的协方差矩阵,特征值进行判断),则认为匹配上了
    1360. // 2、计算当前帧角点到直线的距离、垂线的单位向量,存储为角点参数
    1361. cornerOptimization();
    1362. // 当前激光帧平面点寻找局部map匹配点
    1363. // 1、更新当前帧位姿,将当前帧平面点坐标变换到map系下,在局部map中查找5个最近点,距离小于1m,且5个点构成平面(最小二乘拟合平面),则认为匹配上了
    1364. // 2、计算当前帧平面点到平面的距离、垂线的单位向量,存储为平面点参数
    1365. surfOptimization();
    1366. // 提取当前帧中与局部map匹配上了的角点、平面点,加入同一集合
    1367. combineOptimizationCoeffs();
    1368. // scan-to-map优化
    1369. // 对匹配特征点计算Jacobian矩阵,观测值为特征点到直线、平面的距离,构建高斯牛顿方程,迭代优化当前位姿,存transformTobeMapped
    1370. if (LMOptimization(iterCount) == true)
    1371. break;
    1372. }
    1373. // 用imu原始RPY数据与scan-to-map优化后的位姿进行加权融合,更新当前帧位姿的roll、pitch,约束z坐标
    1374. transformUpdate();
    1375. } else {
    1376. ROS_WARN("Not enough features! Only %d edge and %d planar features available.", laserCloudCornerLastDSNum, laserCloudSurfLastDSNum);
    1377. }
    1378. }
    1379. /**
    1380. * 用imu原始RPY数据与scan-to-map优化后的位姿进行加权融合,更新当前帧位姿的roll、pitch,约束z坐标
    1381. */
    1382. void transformUpdate()
    1383. {
    1384. if (cloudInfo.imuAvailable == true)
    1385. {
    1386. // 俯仰角小于1.4
    1387. if (std::abs(cloudInfo.imuPitchInit) < 1.4)
    1388. {
    1389. double imuWeight = imuRPYWeight;
    1390. tf::Quaternion imuQuaternion;
    1391. tf::Quaternion transformQuaternion;
    1392. double rollMid, pitchMid, yawMid;
    1393. // roll角求加权均值,用scan-to-map优化得到的位姿与imu原始RPY数据,进行加权平均
    1394. transformQuaternion.setRPY(transformTobeMapped[0], 0, 0);
    1395. imuQuaternion.setRPY(cloudInfo.imuRollInit, 0, 0);
    1396. tf::Matrix3x3(transformQuaternion.slerp(imuQuaternion, imuWeight)).getRPY(rollMid, pitchMid, yawMid);
    1397. transformTobeMapped[0] = rollMid;
    1398. // pitch角求加权均值,用scan-to-map优化得到的位姿与imu原始RPY数据,进行加权平均
    1399. transformQuaternion.setRPY(0, transformTobeMapped[1], 0);
    1400. imuQuaternion.setRPY(0, cloudInfo.imuPitchInit, 0);
    1401. tf::Matrix3x3(transformQuaternion.slerp(imuQuaternion, imuWeight)).getRPY(rollMid, pitchMid, yawMid);
    1402. transformTobeMapped[1] = pitchMid;
    1403. }
    1404. }
    1405. // 更新当前帧位姿的roll, pitch, z坐标;因为是小车,roll、pitch是相对稳定的,不会有很大变动,一定程度上可以信赖imu的数据,z是进行高度约束
    1406. transformTobeMapped[0] = constraintTransformation(transformTobeMapped[0], rotation_tollerance);
    1407. transformTobeMapped[1] = constraintTransformation(transformTobeMapped[1], rotation_tollerance);
    1408. transformTobeMapped[5] = constraintTransformation(transformTobeMapped[5], z_tollerance);
    1409. // 当前帧位姿
    1410. incrementalOdometryAffineBack = trans2Affine3f(transformTobeMapped);
    1411. }
    1412. /**
    1413. * 值约束
    1414. */
    1415. float constraintTransformation(float value, float limit)
    1416. {
    1417. if (value < -limit)
    1418. value = -limit;
    1419. if (value > limit)
    1420. value = limit;
    1421. return value;
    1422. }
    1423. /**
    1424. * 计算当前帧与前一帧位姿变换,如果变化太小,不设为关键帧,反之设为关键帧
    1425. */
    1426. bool saveFrame()
    1427. {
    1428. if (cloudKeyPoses3D->points.empty())
    1429. return true;
    1430. // 前一帧位姿
    1431. Eigen::Affine3f transStart = pclPointToAffine3f(cloudKeyPoses6D->back());
    1432. // 当前帧位姿
    1433. Eigen::Affine3f transFinal = pcl::getTransformation(transformTobeMapped[3], transformTobeMapped[4], transformTobeMapped[5],
    1434. transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
    1435. // 位姿变换增量
    1436. Eigen::Affine3f transBetween = transStart.inverse() * transFinal;
    1437. float x, y, z, roll, pitch, yaw;
    1438. pcl::getTranslationAndEulerAngles(transBetween, x, y, z, roll, pitch, yaw);
    1439. // 旋转和平移量都较小,当前帧不设为关键帧
    1440. if (abs(roll) < surroundingkeyframeAddingAngleThreshold &&
    1441. abs(pitch) < surroundingkeyframeAddingAngleThreshold &&
    1442. abs(yaw) < surroundingkeyframeAddingAngleThreshold &&
    1443. sqrt(x*x + y*y + z*z) < surroundingkeyframeAddingDistThreshold)
    1444. return false;
    1445. return true;
    1446. }
    1447. /**
    1448. * 添加激光里程计因子
    1449. */
    1450. void addOdomFactor()
    1451. {
    1452. if (cloudKeyPoses3D->points.empty())
    1453. {
    1454. // 第一帧初始化先验因子
    1455. noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Variances((Vector(6) << 1e-2, 1e-2, M_PI*M_PI, 1e8, 1e8, 1e8).finished()); // rad*rad, meter*meter
    1456. gtSAMgraph.add(PriorFactor(0, trans2gtsamPose(transformTobeMapped), priorNoise));
    1457. // 变量节点设置初始值
    1458. initialEstimate.insert(0, trans2gtsamPose(transformTobeMapped));
    1459. }else{
    1460. // 添加激光里程计因子
    1461. noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Variances((Vector(6) << 1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4).finished());
    1462. gtsam::Pose3 poseFrom = pclPointTogtsamPose3(cloudKeyPoses6D->points.back());
    1463. gtsam::Pose3 poseTo = trans2gtsamPose(transformTobeMapped);
    1464. // 参数:前一帧id,当前帧id,前一帧与当前帧的位姿变换(作为观测值),噪声协方差
    1465. gtSAMgraph.add(BetweenFactor(cloudKeyPoses3D->size()-1, cloudKeyPoses3D->size(), poseFrom.between(poseTo), odometryNoise));
    1466. // 变量节点设置初始值
    1467. initialEstimate.insert(cloudKeyPoses3D->size(), poseTo);
    1468. }
    1469. }
    1470. /**
    1471. * 添加GPS因子
    1472. */
    1473. void addGPSFactor()
    1474. {
    1475. if (gpsQueue.empty())
    1476. return;
    1477. // 如果没有关键帧,或者首尾关键帧距离小于5m,不添加gps因子
    1478. if (cloudKeyPoses3D->points.empty())
    1479. return;
    1480. else
    1481. {
    1482. if (pointDistance(cloudKeyPoses3D->front(), cloudKeyPoses3D->back()) < 5.0)
    1483. return;
    1484. }
    1485. // 位姿协方差很小,没必要加入GPS数据进行校正
    1486. if (poseCovariance(3,3) < poseCovThreshold && poseCovariance(4,4) < poseCovThreshold)
    1487. return;
    1488. static PointType lastGPSPoint;
    1489. while (!gpsQueue.empty())
    1490. {
    1491. // 删除当前帧0.2s之前的里程计
    1492. if (gpsQueue.front().header.stamp.toSec() < timeLaserInfoCur - 0.2)
    1493. {
    1494. gpsQueue.pop_front();
    1495. }
    1496. // 超过当前帧0.2s之后,退出
    1497. else if (gpsQueue.front().header.stamp.toSec() > timeLaserInfoCur + 0.2)
    1498. {
    1499. break;
    1500. }
    1501. else
    1502. {
    1503. nav_msgs::Odometry thisGPS = gpsQueue.front();
    1504. gpsQueue.pop_front();
    1505. // GPS噪声协方差太大,不能用
    1506. float noise_x = thisGPS.pose.covariance[0];
    1507. float noise_y = thisGPS.pose.covariance[7];
    1508. float noise_z = thisGPS.pose.covariance[14];
    1509. if (noise_x > gpsCovThreshold || noise_y > gpsCovThreshold)
    1510. continue;
    1511. // GPS里程计位置
    1512. float gps_x = thisGPS.pose.pose.position.x;
    1513. float gps_y = thisGPS.pose.pose.position.y;
    1514. float gps_z = thisGPS.pose.pose.position.z;
    1515. if (!useGpsElevation)
    1516. {
    1517. gps_z = transformTobeMapped[5];
    1518. noise_z = 0.01;
    1519. }
    1520. // (0,0,0)无效数据
    1521. if (abs(gps_x) < 1e-6 && abs(gps_y) < 1e-6)
    1522. continue;
    1523. // 每隔5m添加一个GPS里程计
    1524. PointType curGPSPoint;
    1525. curGPSPoint.x = gps_x;
    1526. curGPSPoint.y = gps_y;
    1527. curGPSPoint.z = gps_z;
    1528. if (pointDistance(curGPSPoint, lastGPSPoint) < 5.0)
    1529. continue;
    1530. else
    1531. lastGPSPoint = curGPSPoint;
    1532. // 添加GPS因子
    1533. gtsam::Vector Vector3(3);
    1534. Vector3 << max(noise_x, 1.0f), max(noise_y, 1.0f), max(noise_z, 1.0f);
    1535. noiseModel::Diagonal::shared_ptr gps_noise = noiseModel::Diagonal::Variances(Vector3);
    1536. gtsam::GPSFactor gps_factor(cloudKeyPoses3D->size(), gtsam::Point3(gps_x, gps_y, gps_z), gps_noise);
    1537. gtSAMgraph.add(gps_factor);
    1538. aLoopIsClosed = true;
    1539. break;
    1540. }
    1541. }
    1542. }
    1543. /**
    1544. * 添加闭环因子
    1545. */
    1546. void addLoopFactor()
    1547. {
    1548. if (loopIndexQueue.empty())
    1549. return;
    1550. // 闭环队列
    1551. for (int i = 0; i < (int)loopIndexQueue.size(); ++i)
    1552. {
    1553. // 闭环边对应两帧的索引
    1554. int indexFrom = loopIndexQueue[i].first;
    1555. int indexTo = loopIndexQueue[i].second;
    1556. // 闭环边的位姿变换
    1557. gtsam::Pose3 poseBetween = loopPoseQueue[i];
    1558. gtsam::noiseModel::Diagonal::shared_ptr noiseBetween = loopNoiseQueue[i];
    1559. gtSAMgraph.add(BetweenFactor(indexFrom, indexTo, poseBetween, noiseBetween));
    1560. }
    1561. loopIndexQueue.clear();
    1562. loopPoseQueue.clear();
    1563. loopNoiseQueue.clear();
    1564. aLoopIsClosed = true;
    1565. }
    1566. /**
    1567. * 设置当前帧为关键帧并执行因子图优化
    1568. * 1、计算当前帧与前一帧位姿变换,如果变化太小,不设为关键帧,反之设为关键帧
    1569. * 2、添加激光里程计因子、GPS因子、闭环因子
    1570. * 3、执行因子图优化
    1571. * 4、得到当前帧优化后位姿,位姿协方差
    1572. * 5、添加cloudKeyPoses3D,cloudKeyPoses6D,更新transformTobeMapped,添加当前关键帧的角点、平面点集合
    1573. */
    1574. void saveKeyFramesAndFactor()
    1575. {
    1576. // 计算当前帧与前一帧位姿变换,如果变化太小,不设为关键帧,反之设为关键帧
    1577. if (saveFrame() == false)
    1578. return;
    1579. // 激光里程计因子
    1580. addOdomFactor();
    1581. // GPS因子
    1582. addGPSFactor();
    1583. // 闭环因子
    1584. addLoopFactor();
    1585. // cout << "****************************************************" << endl;
    1586. // gtSAMgraph.print("GTSAM Graph:\n");
    1587. // 执行优化
    1588. isam->update(gtSAMgraph, initialEstimate);
    1589. isam->update();
    1590. if (aLoopIsClosed == true)
    1591. {
    1592. isam->update();
    1593. isam->update();
    1594. isam->update();
    1595. isam->update();
    1596. isam->update();
    1597. }
    1598. // update之后要清空一下保存的因子图,注:历史数据不会清掉,ISAM保存起来了
    1599. gtSAMgraph.resize(0);
    1600. initialEstimate.clear();
    1601. PointType thisPose3D;
    1602. PointTypePose thisPose6D;
    1603. Pose3 latestEstimate;
    1604. // 优化结果
    1605. isamCurrentEstimate = isam->calculateEstimate();
    1606. // 当前帧位姿结果
    1607. latestEstimate = isamCurrentEstimate.at(isamCurrentEstimate.size()-1);
    1608. // cout << "****************************************************" << endl;
    1609. // isamCurrentEstimate.print("Current estimate: ");
    1610. // cloudKeyPoses3D加入当前帧位姿
    1611. thisPose3D.x = latestEstimate.translation().x();
    1612. thisPose3D.y = latestEstimate.translation().y();
    1613. thisPose3D.z = latestEstimate.translation().z();
    1614. // 索引
    1615. thisPose3D.intensity = cloudKeyPoses3D->size();
    1616. cloudKeyPoses3D->push_back(thisPose3D);
    1617. // cloudKeyPoses6D加入当前帧位姿
    1618. thisPose6D.x = thisPose3D.x;
    1619. thisPose6D.y = thisPose3D.y;
    1620. thisPose6D.z = thisPose3D.z;
    1621. thisPose6D.intensity = thisPose3D.intensity ;
    1622. thisPose6D.roll = latestEstimate.rotation().roll();
    1623. thisPose6D.pitch = latestEstimate.rotation().pitch();
    1624. thisPose6D.yaw = latestEstimate.rotation().yaw();
    1625. thisPose6D.time = timeLaserInfoCur;
    1626. cloudKeyPoses6D->push_back(thisPose6D);
    1627. // cout << "****************************************************" << endl;
    1628. // cout << "Pose covariance:" << endl;
    1629. // cout << isam->marginalCovariance(isamCurrentEstimate.size()-1) << endl << endl;
    1630. // 位姿协方差
    1631. poseCovariance = isam->marginalCovariance(isamCurrentEstimate.size()-1);
    1632. // transformTobeMapped更新当前帧位姿
    1633. transformTobeMapped[0] = latestEstimate.rotation().roll();
    1634. transformTobeMapped[1] = latestEstimate.rotation().pitch();
    1635. transformTobeMapped[2] = latestEstimate.rotation().yaw();
    1636. transformTobeMapped[3] = latestEstimate.translation().x();
    1637. transformTobeMapped[4] = latestEstimate.translation().y();
    1638. transformTobeMapped[5] = latestEstimate.translation().z();
    1639. // 当前帧激光角点、平面点,降采样集合
    1640. pcl::PointCloud::Ptr thisCornerKeyFrame(new pcl::PointCloud());
    1641. pcl::PointCloud::Ptr thisSurfKeyFrame(new pcl::PointCloud());
    1642. pcl::copyPointCloud(*laserCloudCornerLastDS, *thisCornerKeyFrame);
    1643. pcl::copyPointCloud(*laserCloudSurfLastDS, *thisSurfKeyFrame);
    1644. // 保存特征点降采样集合
    1645. cornerCloudKeyFrames.push_back(thisCornerKeyFrame);
    1646. surfCloudKeyFrames.push_back(thisSurfKeyFrame);
    1647. // 更新里程计轨迹
    1648. updatePath(thisPose6D);
    1649. }
    1650. /**
    1651. * 更新因子图中所有变量节点的位姿,也就是所有历史关键帧的位姿,更新里程计轨迹
    1652. */
    1653. void correctPoses()
    1654. {
    1655. if (cloudKeyPoses3D->points.empty())
    1656. return;
    1657. if (aLoopIsClosed == true)
    1658. {
    1659. // 清空局部map
    1660. laserCloudMapContainer.clear();
    1661. // 清空里程计轨迹
    1662. globalPath.poses.clear();
    1663. // 更新因子图中所有变量节点的位姿,也就是所有历史关键帧的位姿
    1664. int numPoses = isamCurrentEstimate.size();
    1665. for (int i = 0; i < numPoses; ++i)
    1666. {
    1667. cloudKeyPoses3D->points[i].x = isamCurrentEstimate.at(i).translation().x();
    1668. cloudKeyPoses3D->points[i].y = isamCurrentEstimate.at(i).translation().y();
    1669. cloudKeyPoses3D->points[i].z = isamCurrentEstimate.at(i).translation().z();
    1670. cloudKeyPoses6D->points[i].x = cloudKeyPoses3D->points[i].x;
    1671. cloudKeyPoses6D->points[i].y = cloudKeyPoses3D->points[i].y;
    1672. cloudKeyPoses6D->points[i].z = cloudKeyPoses3D->points[i].z;
    1673. cloudKeyPoses6D->points[i].roll = isamCurrentEstimate.at(i).rotation().roll();
    1674. cloudKeyPoses6D->points[i].pitch = isamCurrentEstimate.at(i).rotation().pitch();
    1675. cloudKeyPoses6D->points[i].yaw = isamCurrentEstimate.at(i).rotation().yaw();
    1676. // 更新里程计轨迹
    1677. updatePath(cloudKeyPoses6D->points[i]);
    1678. }
    1679. aLoopIsClosed = false;
    1680. }
    1681. }
    1682. /**
    1683. * 更新里程计轨迹
    1684. */
    1685. void updatePath(const PointTypePose& pose_in)
    1686. {
    1687. geometry_msgs::PoseStamped pose_stamped;
    1688. pose_stamped.header.stamp = ros::Time().fromSec(pose_in.time);
    1689. pose_stamped.header.frame_id = odometryFrame;
    1690. pose_stamped.pose.position.x = pose_in.x;
    1691. pose_stamped.pose.position.y = pose_in.y;
    1692. pose_stamped.pose.position.z = pose_in.z;
    1693. tf::Quaternion q = tf::createQuaternionFromRPY(pose_in.roll, pose_in.pitch, pose_in.yaw);
    1694. pose_stamped.pose.orientation.x = q.x();
    1695. pose_stamped.pose.orientation.y = q.y();
    1696. pose_stamped.pose.orientation.z = q.z();
    1697. pose_stamped.pose.orientation.w = q.w();
    1698. globalPath.poses.push_back(pose_stamped);
    1699. }
    1700. /**
    1701. * 发布激光里程计
    1702. */
    1703. void publishOdometry()
    1704. {
    1705. // 发布激光里程计,odom等价map
    1706. nav_msgs::Odometry laserOdometryROS;
    1707. laserOdometryROS.header.stamp = timeLaserInfoStamp;
    1708. laserOdometryROS.header.frame_id = odometryFrame;
    1709. laserOdometryROS.child_frame_id = "odom_mapping";
    1710. laserOdometryROS.pose.pose.position.x = transformTobeMapped[3];
    1711. laserOdometryROS.pose.pose.position.y = transformTobeMapped[4];
    1712. laserOdometryROS.pose.pose.position.z = transformTobeMapped[5];
    1713. laserOdometryROS.pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]);
    1714. pubLaserOdometryGlobal.publish(laserOdometryROS);
    1715. // 发布TF,odom->lidar
    1716. static tf::TransformBroadcaster br;
    1717. tf::Transform t_odom_to_lidar = tf::Transform(tf::createQuaternionFromRPY(transformTobeMapped[0], transformTobeMapped[1], transformTobeMapped[2]),
    1718. tf::Vector3(transformTobeMapped[3], transformTobeMapped[4], transformTobeMapped[5]));
    1719. tf::StampedTransform trans_odom_to_lidar = tf::StampedTransform(t_odom_to_lidar, timeLaserInfoStamp, odometryFrame, "lidar_link");
    1720. br.sendTransform(trans_odom_to_lidar);
    1721. // Publish odometry for ROS (incremental)
    1722. static bool lastIncreOdomPubFlag = false;
    1723. static nav_msgs::Odometry laserOdomIncremental;
    1724. static Eigen::Affine3f increOdomAffine;
    1725. if (lastIncreOdomPubFlag == false)
    1726. {
    1727. lastIncreOdomPubFlag = true;
    1728. laserOdomIncremental = laserOdometryROS;
    1729. increOdomAffine = trans2Affine3f(transformTobeMapped);
    1730. } else {
    1731. // 当前帧与前一帧之间的位姿变换
    1732. Eigen::Affine3f affineIncre = incrementalOdometryAffineFront.inverse() * incrementalOdometryAffineBack;
    1733. // 还是当前帧位姿(打印一下数据,可以看到与激光里程计的位姿transformTobeMapped是一样的)
    1734. increOdomAffine = increOdomAffine * affineIncre;
    1735. float x, y, z, roll, pitch, yaw;
    1736. pcl::getTranslationAndEulerAngles (increOdomAffine, x, y, z, roll, pitch, yaw);
    1737. if (cloudInfo.imuAvailable == true)
    1738. {
    1739. if (std::abs(cloudInfo.imuPitchInit) < 1.4)
    1740. {
    1741. double imuWeight = 0.1;
    1742. tf::Quaternion imuQuaternion;
    1743. tf::Quaternion transformQuaternion;
    1744. double rollMid, pitchMid, yawMid;
    1745. // roll姿态角加权平均
    1746. transformQuaternion.setRPY(roll, 0, 0);
    1747. imuQuaternion.setRPY(cloudInfo.imuRollInit, 0, 0);
    1748. tf::Matrix3x3(transformQuaternion.slerp(imuQuaternion, imuWeight)).getRPY(rollMid, pitchMid, yawMid);
    1749. roll = rollMid;
    1750. // pitch姿态角加权平均
    1751. transformQuaternion.setRPY(0, pitch, 0);
    1752. imuQuaternion.setRPY(0, cloudInfo.imuPitchInit, 0);
    1753. tf::Matrix3x3(transformQuaternion.slerp(imuQuaternion, imuWeight)).getRPY(rollMid, pitchMid, yawMid);
    1754. pitch = pitchMid;
    1755. }
    1756. }
    1757. laserOdomIncremental.header.stamp = timeLaserInfoStamp;
    1758. laserOdomIncremental.header.frame_id = odometryFrame;
    1759. laserOdomIncremental.child_frame_id = "odom_mapping";
    1760. laserOdomIncremental.pose.pose.position.x = x;
    1761. laserOdomIncremental.pose.pose.position.y = y;
    1762. laserOdomIncremental.pose.pose.position.z = z;
    1763. laserOdomIncremental.pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);
    1764. if (isDegenerate)
    1765. laserOdomIncremental.pose.covariance[0] = 1;
    1766. else
    1767. laserOdomIncremental.pose.covariance[0] = 0;
    1768. }
    1769. pubLaserOdometryIncremental.publish(laserOdomIncremental);
    1770. }
    1771. /**
    1772. * 发布里程计、点云、轨迹
    1773. * 1、发布历史关键帧位姿集合
    1774. * 2、发布局部map的降采样平面点集合
    1775. * 3、发布历史帧(累加的)的角点、平面点降采样集合
    1776. * 4、发布里程计轨迹
    1777. */
    1778. void publishFrames()
    1779. {
    1780. if (cloudKeyPoses3D->points.empty())
    1781. return;
    1782. // 发布历史关键帧位姿集合
    1783. publishCloud(&pubKeyPoses, cloudKeyPoses3D, timeLaserInfoStamp, odometryFrame);
    1784. // 发布局部map的降采样平面点集合
    1785. publishCloud(&pubRecentKeyFrames, laserCloudSurfFromMapDS, timeLaserInfoStamp, odometryFrame);
    1786. // 发布历史帧(累加的)的角点、平面点降采样集合
    1787. if (pubRecentKeyFrame.getNumSubscribers() != 0)
    1788. {
    1789. pcl::PointCloud::Ptr cloudOut(new pcl::PointCloud());
    1790. PointTypePose thisPose6D = trans2PointTypePose(transformTobeMapped);
    1791. *cloudOut += *transformPointCloud(laserCloudCornerLastDS, &thisPose6D);
    1792. *cloudOut += *transformPointCloud(laserCloudSurfLastDS, &thisPose6D);
    1793. publishCloud(&pubRecentKeyFrame, cloudOut, timeLaserInfoStamp, odometryFrame);
    1794. }
    1795. // 发布当前帧原始点云配准之后的点云
    1796. if (pubCloudRegisteredRaw.getNumSubscribers() != 0)
    1797. {
    1798. pcl::PointCloud::Ptr cloudOut(new pcl::PointCloud());
    1799. pcl::fromROSMsg(cloudInfo.cloud_deskewed, *cloudOut);
    1800. PointTypePose thisPose6D = trans2PointTypePose(transformTobeMapped);
    1801. *cloudOut = *transformPointCloud(cloudOut, &thisPose6D);
    1802. publishCloud(&pubCloudRegisteredRaw, cloudOut, timeLaserInfoStamp, odometryFrame);
    1803. }
    1804. // 发布里程计轨迹
    1805. if (pubPath.getNumSubscribers() != 0)
    1806. {
    1807. globalPath.header.stamp = timeLaserInfoStamp;
    1808. globalPath.header.frame_id = odometryFrame;
    1809. pubPath.publish(globalPath);
    1810. }
    1811. }
    1812. };
    1813. int main(int argc, char** argv)
    1814. {
    1815. ros::init(argc, argv, "lio_sam");
    1816. mapOptimization MO;
    1817. ROS_INFO("\033[1;32m----> Map Optimization Started.\033[0m");
    1818. std::thread loopthread(&mapOptimization::loopClosureThread, &MO);
    1819. std::thread visualizeMapThread(&mapOptimization::visualizeGlobalMapThread, &MO);
    1820. ros::spin();
    1821. loopthread.join();
    1822. visualizeMapThread.join();
    1823. return 0;
    1824. }

    参考文献

    LIOSAM代码架构 - 知乎

    SLAM学习笔记(二十)LIO-SAM流程及代码详解(最全)_zkk9527的博客-CSDN博客_lio-sam 

  • 相关阅读:
    cad怎么转换成黑白的pdf图纸?分享3个常用的软件!
    基于SpringBoot的个人博客系统设计与实现
    Gson转换错误导致Int变为Double类型
    [Java]线上监控诊断工具Arathas,入门使用
    洛谷P1506 拯救oibh总部 —DFS—围墙
    BigDecimal 详解
    CROS和JSONP配置
    解密Vue中key的神奇原理:优化列表渲染效率的关键策略!
    KY91 String Matching
    多维时序 | MATLAB实现GWO-LSTM灰狼算法优化长短期记忆神经网络的多变量时间序列预测
  • 原文地址:https://blog.csdn.net/xhtchina/article/details/128160103