写在前面


关于安装配置,博客LIO_SAM实测运行,论文学习及代码注释[附对应google driver数据] 我觉得已经写的比较完善了。但是我觉得在注释方面,这位博主写的还不够完善,因此在学习以后,我想补充一些内容。


关于本身论文的原理,参见我的专栏内容:


SLAM学习笔记(十九)开源3D激光SLAM总结大全——Cartographer3D,LOAM,Lego-LOAM,LIO-SAM,LVI-SAM,Livox-LOAM的原理解析及区别


上面这篇文章内容比较多,我放了目录,可以只看对应位置。


而现在这篇文章的主要目的是理清LIO-SAM的流程,对其中的数据处理的思路、程序设计的流程等各方面做一个总结。代码的注释有我自己写的内容,还有就是参考了一些别人的网络博客的内容。总之在总结的过程中,我发现有些东西其实最开始的时候自己理解的不够深刻。


因此,总结此文,一来为自己对代码更熟悉,便于之后回顾,二来也希望能帮到大家。如果这篇文章有幸被你读到,我希望读者可以自己总结一下流程,自己一行一行亲手把代码注释写进去。否则如果只是整篇复制下来读一遍的话,说实话没啥意义,如同过眼云烟,等过个两天脑子里什么都没了。


截至目前,我认为我这篇文章是对代码梳理的最详细的一篇文章。


目录


写在前面


utility.h


imageProjection.cpp


注释


总结


featureExtraction.cpp


注释


总结


imuPreintergration.cpp


注释


总结


mapOptimization.cpp


注释


总结




LIO-SAM说白了只有五个文件,一个头文件utility.h,还有四个cpp文件。我们从头文件开始介绍。


utility.h


头文件里主要是放了一些通用的参数定义,比方说:


nh.param<std::string>(“lio_sam/pointCloudTopic”, pointCloudTopic, “points_raw”);

这个意思就是我launch文件里面有这个”lio_sam/pointCloudTopic”(前面这个)的参数值的赋值,那么就赋值给pointCloudTopic(后面这个),后面的”/points_raw”就会忽略。那假如launch文件里面没有这个”lio_sam/pointCloudTopic”的定义,则就用”points_raw”。我们打开run.launch文件,可以看到是有加载参数的:


    <rosparam file=$(find lio_sam)/config/params.yaml” command=“load” />

 那么相关的参数就放在params.yaml文件中。


关于这个params.yaml,里面的东西乍一看很多,其实就几个比较重要:


第一:IMU Settings 来记录IMU的bias和噪声。当然IMU其实是加速度计和陀螺仪一共三个轴,这里却不分轴,用了一个平均数。如果没有转台之类的设备,就跑艾伦方差也可以标出各个轴的bias。作者的处理是:在imu预积分部分,三个轴都用了同样的bias方差(也就是写在配置文件里的这个),当然你要是有能力标的更准,那不妨这里把各个轴的bias都写进去,然后在imupreintegration.cpp文件里面改一改。


第二,IMU和雷达之间的外参。我不知道为什么作者TiXiaoshan很骚包的在这里写了一个Extrinsics (lidar -> IMU),其实不能这样写,应该写成IMU->Lidar。因为它其实是<img alt=”T_{LB}” class=”mathcode” src=”https://latex.codecogs.com/gif.latex?T_%7BLB%7D">,也就是说在IMU坐标系下的一个点,左乘T_{LB},就可以变换到lidar坐标系下。 而且作者用的IMU也不是正常IMU,我推测他用的应该是左手系IMU。对于正常人使用的话,就普通的IMU就行,假如你就是那个机器人,x射向正前方,y射向左边,z射向头顶。雷达和IMU都是这样摆放,所以extrinsicRot和extrinsicRPY全部弄成单位矩阵就行。差的不太远的话,extrinsicTrans弄成[0,0,0]就行。


不过有精力的话还是标定了一下,就用浙大在2020开源的标定工具,lidar_IMU_calib ,(这个博客讲怎么配置的,我用的是这个),我个人拿尺子量出来大致比一下,我觉得他们估的还挺准。顺便提一嘴,ETH还有一个标定雷达和IMU的,那个准确来说标的是雷达和里程计的,原理也比较简单,反正雷达运动算一个轨迹,IMU也来一个轨迹,两边用外参联系起来,构成一个环,来求解外参。但是这种是有问题的,因为IMU估计的轨迹本身也就不准,这样估出来的外参也就不对,所以人家是标雷达和里程计的,不能单估雷达和IMU。浙大的这个lidar_IMU_calib的文章我大致看了看,大致是用样条插值,相机去对齐IMU,通过这种方式来初始化,之后构建surfelsMap,迭代优化来精修。(细节以我的性格正常我会展开说的,但是我不喜欢他们这篇论文所以不讲,主要是因为他们在论文里表示坐标系变换,<img alt=”R_{LI}” class=”mathcode” src=”https://latex.codecogs.com/gif.latex?R_%7BLI%7D">非要写成^L_I R,像这种反人类的写法我们应该坚决抵制 ^ _ ^)


第三,z_tollerance,可以给z一个比较大的限制,如果用的是无人车,那就不可能在z轴变化过大,这里就可以限制它,防止它飘走。


第四,voxel filter paprams,这个是一些体素滤波的下采样参数,注意室内和室外是有区别的。



现在回到这个头文件里,可以注意两个内容:


第一,imuConverter函数,这个函数之后会被频繁调用。它主要的作用,是把IMU的信息,从IMU坐标系,转换到雷达坐标系。(注意,这个函数只旋转,没有平移,和真正的雷达坐标系之间还是差了一个平移的。至于为什么没有平移,先提前剧透一下,在imuPreintegration.cpp文件中,还有两个imu2Lidar,lidar2imu变量,这俩变量只有平移,没有旋转。


事实上,作者后续是把imu数据先用imuConverter旋转到雷达系下(但其实还差了个平移)。然后他把雷达数据又根据lidar2Imu反向平移了一下,和转换以后差了个平移的imu数据在“中间系”对齐,之后算完又从中间系通过imu2Lidar挪回了雷达系进行publish。


第二,publishCloud函数,这个函数传入句柄,然后发布形参里的内容,在cpp文件涉及到话题发布的地方,都会调用它。


其他的函数都是一些数据转换函数,没什么可说的。




imageProjection.cpp


注释


  1. #include “utility.h”
  2. #include “lio_sam/cloud_info.h”
  3. struct <span class=”hljs-title class_“>VelodynePointXYZIRT
  4. {
  5. PCL_ADD_POINT4D
  6. PCL_ADD_INTENSITY;
  7. uint16_t ring;
  8. float time;
  9. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  10. } EIGEN_ALIGN16;
  11. POINT_CLOUD_REGISTER_POINT_STRUCT (VelodynePointXYZIRT,
  12. (float, x, x) (float, y, y) (float, z, z) (float, intensity, intensity)
  13. (uint16_t, ring, ring) (float, time, time)
  14. )
  15. struct <span class=”hljs-title class_“>OusterPointXYZIRT {
  16. PCL_ADD_POINT4D;
  17. float intensity;
  18. uint32_t t;
  19. uint16_t reflectivity;
  20. uint8_t ring;
  21. uint16_t noise;
  22. uint32_t range;
  23. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  24. } EIGEN_ALIGN16;
  25. POINT_CLOUD_REGISTER_POINT_STRUCT(OusterPointXYZIRT,
  26. (float, x, x) (float, y, y) (float, z, z) (float, intensity, intensity)
  27. (uint32_t, t, t) (uint16_t, reflectivity, reflectivity)
  28. (uint8_t, ring, ring) (uint16_t, noise, noise) (uint32_t, range, range)
  29. )
  30. // Use the Velodyne point format as a common representation
  31. using PointXYZIRT = VelodynePointXYZIRT;
  32. const int queueLength = 2000;
  33. class <span class=”hljs-title class_“>ImageProjection : public ParamServer
  34. {
  35. private:
  36. std::mutex imuLock;
  37. std::mutex odoLock;
  38. ros::Subscriber subLaserCloud;
  39. ros::Publisher pubLaserCloud;
  40. ros::Publisher pubExtractedCloud;
  41. ros::Publisher pubLaserCloudInfo;
  42. ros::Subscriber subImu;
  43. std::deque<sensor_msgs::Imu> imuQueue;
  44. ros::Subscriber subOdom;
  45. std::deque<nav_msgs::Odometry> odomQueue;
  46. std::deque<sensor_msgs::PointCloud2> cloudQueue;
  47. sensor_msgs::PointCloud2 currentCloudMsg;
  48. double _imuTime = new double[queueLength];
  49. double _imuRotX = new double[queueLength];
  50. double _imuRotY = new double[queueLength];
  51. double _imuRotZ = new double[queueLength];
  52. int imuPointerCur;
  53. bool firstPointFlag;
  54. Eigen::Affine3f transStartInverse;
  55. pcl::PointCloud<PointXYZIRT>::Ptr laserCloudIn;
  56. pcl::PointCloud<OusterPointXYZIRT>::Ptr tmpOusterCloudIn;
  57. pcl::PointCloud<PointType>::Ptr fullCloud;
  58. pcl::PointCloud<PointType>::Ptr extractedCloud;
  59. int deskewFlag;
  60. cv::Mat rangeMat;
  61. bool odomDeskewFlag;
  62. float odomIncreX;
  63. float odomIncreY;
  64. float odomIncreZ;
  65. lio_sam::cloud_info cloudInfo;
  66. double timeScanCur;
  67. double timeScanEnd;
  68. std_msgs::Header cloudHeader;
  69. public:
  70. ImageProjection():
  71. deskewFlag(0)
  72. {
  73. //订阅话题进入回调函数 imu数据 激光点云.
  74. // imuTopic:topic name; 2000:queue size; &ImageProjection::imuHandler:callback function
  75. // this: 调用这个class里的返回函数,可以使用第四个参数,例如有个对象叫listener,
  76. // 调用该对象内部的回调函数,则传入&listener,这里调用自己的,则传入this指针
  77. // ros::TransportHints().tcpNoDelay() :被用于指定hints,确定传输层的作用话题的方式:无延迟的TCP传输方式
  78. subImu = nh.subscribe<sensor_msgs::Imu>(imuTopic, 2000, &ImageProjection::imuHandler, this, ros::TransportHints().tcpNoDelay());
  79. //订阅话题进入回调函数
  80. //订阅imu里程计: 来自IMUPreintegration(IMUPreintegration.cpp中的类IMUPreintegration)发布的里程计话题(增量式)
  81. subOdom = nh.subscribe<nav_msgs::Odometry>(odomTopic+“_incremental”, 2000, &ImageProjection::odometryHandler, this, ros::TransportHints().tcpNoDelay());
  82. //订阅话题进入回调函数 激光点云
  83. subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>(pointCloudTopic, 5, &ImageProjection::cloudHandler, this, ros::TransportHints().tcpNoDelay());
  84. //发布去畸变的点云,”lio_sam/deskew/cloud_deskewed”:topic name; 1:queue_size
  85. pubExtractedCloud = nh.advertise<sensor_msgs::PointCloud2> (“lio_sam/deskew/cloud_deskewed”, 1);
  86. //发布激光点云信息 这里建议看一下自定义的lio_sam::cloud_info的msg文件 里面包含了较多信息
  87. pubLaserCloudInfo = nh.advertise<lio_sam::cloud_info> (“lio_sam/deskew/cloud_info”, 1);
  88. //分配内存
  89. allocateMemory();
  90. //重置部分参数
  91. resetParameters();
  92. //setVerbosityLevel用于设置控制台输出的信息。(pcl::console::L_ALWAYS)不会输出任何信息;L_DEBUG会输出DEBUG信息;
  93. //L_ERROR会输出ERROR信息
  94. pcl::console::setVerbosityLevel(pcl::console::L_ERROR);
  95. }
  96. void allocateMemory()
  97. {
  98. //根据params.yaml中给出的N_SCAN Horizon_SCAN参数值分配内存
  99. //用智能指针的reset方法在构造函数里面进行初始化
  100. laserCloudIn.reset(new pcl::PointCloud<PointXYZIRT>());
  101. tmpOusterCloudIn.reset(new pcl::PointCloud<OusterPointXYZIRT>());
  102. fullCloud.reset(new pcl::PointCloud<PointType>());
  103. extractedCloud.reset(new pcl::PointCloud<PointType>());
  104. fullCloud->points.resize(N_SCAN_Horizon_SCAN);
  105. //cloudinfo是msg文件下自定义的cloud_info消息,对其中的变量进行赋值操作
  106. //(int size, int value):size-要分配的值数,value-要分配给向量名称的值
  107. cloudInfo.startRingIndex.assign(N_SCAN, 0);
  108. cloudInfo.endRingIndex.assign(N_SCAN, 0);
  109. cloudInfo.pointColInd.assign(N_SCAN_Horizon_SCAN, 0);
  110. cloudInfo.pointRange.assign(N_SCAN_Horizon_SCAN, 0);
  111. resetParameters();
  112. }
  113. void resetParameters()
  114. {
  115. //清零操作
  116. laserCloudIn->clear();
  117. extractedCloud->clear();
  118. // reset range matrix for range image projection,
  119. //初始全部用FLT_MAX 填充,
  120. //因此后文函数projectPointCloud中有一句if (rangeMat.at<float>(rowIdn, columnIdn) != FLT_MAX) continue;
  121. rangeMat = cv::Mat(N_SCAN, Horizon_SCAN, CV_32F, cv::Scalar::all(FLT_MAX));
  122. imuPointerCur = 0;
  123. firstPointFlag = true;
  124. odomDeskewFlag = false;
  125. for (int i = 0; i < queueLength; ++i)
  126. {
  127. imuTime[i] = 0;
  128. imuRotX[i] = 0;
  129. imuRotY[i] = 0;
  130. imuRotZ[i] = 0;
  131. }
  132. }
  133. ~ImageProjection(){}
  134. /**
  135. _ 订阅原始imu数据
  136. _ 1、imu原始测量数据转换到lidar系,加速度、角速度、RPY
  137. _/
  138. void imuHandler(const sensor_msgs::Imu::ConstPtr& imuMsg)
  139. {
  140. //imuConverter在头文件utility.h中,作用是把imu数据转换到lidar坐标系
  141. sensor_msgs::Imu thisImu = imuConverter(_imuMsg);
  142. // 上锁,添加数据的时候队列不可用
  143. std::lock_guard<std::mutex> lock1(imuLock);
  144. imuQueue.push_back(thisImu);
  145. //debug IMU data
  146. cout << std::setprecision(6);
  147. cout << “IMU acc: “ << endl;
  148. cout << “x: “ << thisImu.linear_acceleration.x <<
  149. “, y: “ << thisImu.linear_acceleration.y <<
  150. “, z: “ << thisImu.linear_acceleration.z << endl;
  151. cout << “IMU gyro: “ << endl;
  152. cout << “x: “ << thisImu.angular_velocity.x <<
  153. “, y: “ << thisImu.angular_velocity.y <<
  154. “, z: “ << thisImu.angular_velocity.z << endl;
  155. double imuRoll, imuPitch, imuYaw;
  156. tf::Quaternion orientation;
  157. tf::quaternionMsgToTF(thisImu.orientation, orientation);
  158. tf::Matrix3x3(orientation).getRPY(imuRoll, imuPitch, imuYaw);
  159. cout << “IMU roll pitch yaw: “ << endl;
  160. cout << “roll: “ << imuRoll << “, pitch: “ << imuPitch << “, yaw: “ << imuYaw << endl << endl;
  161. }
  162. /**
  163. _ 订阅imu里程计,由imuPreintegration积分计算得到的每时刻imu位姿.(地图优化程序中发布的)
  164. _/
  165. void odometryHandler(const nav_msgs::Odometry::ConstPtr& odometryMsg)
  166. {
  167. std::lock_guard<std::mutex> lock2(odoLock);
  168. odomQueue.push_back(_odometryMsg);
  169. }
  170. void cloudHandler(const sensor_msgs::PointCloud2ConstPtr& laserCloudMsg)
  171. {
  172. //添加一帧激光点云到队列,取出最早一帧作为当前帧,计算起止时间戳,检查数据有效性
  173. if (!cachePointCloud(laserCloudMsg))
  174. return;
  175. // 当前帧起止时刻对应的imu数据、imu里程计数据处理
  176. if (!deskewInfo())
  177. return;
  178. // 当前帧激光点云运动畸变校正
  179. // 1、检查激光点距离、扫描线是否合规
  180. // 2、激光运动畸变校正,保存激光点
  181. projectPointCloud();
  182. // 提取有效激光点,存extractedCloud
  183. cloudExtraction();
  184. // 发布当前帧校正后点云,有效点
  185. publishClouds();
  186. // 重置参数,接收每帧lidar数据都要重置这些参数
  187. resetParameters();
  188. }
  189. bool cachePointCloud(const sensor_msgs::PointCloud2ConstPtr& laserCloudMsg)
  190. {
  191. // cache point cloud
  192. cloudQueue.push_back(_laserCloudMsg);
  193. if (cloudQueue.size() <= 2)
  194. return false;
  195. // convert cloud
  196. // 取出激光点云队列中最早的一帧
  197. currentCloudMsg = std::move(cloudQueue.front());
  198. cloudQueue.pop_front();
  199. if (sensor == SensorType::VELODYNE)
  200. {
  201. // 转换成pcl点云格式 形参: (in,out)
  202. pcl::moveFromROSMsg(currentCloudMsg, _laserCloudIn);
  203. }
  204. else if (sensor == SensorType::OUSTER)
  205. {
  206. // Convert to Velodyne format
  207. pcl::moveFromROSMsg(currentCloudMsg, _tmpOusterCloudIn);
  208. laserCloudIn->points.resize(tmpOusterCloudIn->size());
  209. laserCloudIn->is_dense = tmpOusterCloudIn->is_dense;
  210. for (size_t i = 0; i < tmpOusterCloudIn->size(); i++)
  211. {
  212. auto &src = tmpOusterCloudIn->points[i];
  213. auto &dst = laserCloudIn->points[i];
  214. dst.x = src.x;
  215. dst.y = src.y;
  216. dst.z = src.z;
  217. dst.intensity = src.intensity;
  218. dst.ring = src.ring;
  219. dst.time = src.t _ 1e-9f;
  220. }
  221. }
  222. else
  223. {
  224. ROS_ERROR_STREAM(“Unknown sensor type: “ << int(sensor));
  225. ros::shutdown();
  226. }
  227. // get timestamp
  228. cloudHeader = currentCloudMsg.header;
  229. //这一点的时间被记录下来,存入timeScanCur中,函数deskewPoint中会被加上laserCloudIn->points[i].time
  230. timeScanCur = cloudHeader.stamp.toSec();
  231. //可以看出lasercloudin中存储的time是一帧中距离起始点的相对时间,timeScanEnd是该帧点云的结尾时间
  232. timeScanEnd = timeScanCur + laserCloudIn->points.back().time;
  233. // check dense flag
  234. if (laserCloudIn->is_dense == false)
  235. {
  236. ROS_ERROR(“Point cloud is not in dense format, please remove NaN points first!”);
  237. ros::shutdown();
  238. }
  239. // check ring channel
  240. //由于static关键字,只检查一次,检查ring这个field是否存在. veloodyne和ouster都有;
  241. //ring代表线数,0是最下面那条
  242. static int ringFlag = 0;
  243. if (ringFlag == 0)
  244. {
  245. ringFlag = -1;
  246. for (int i = 0; i < (int)currentCloudMsg.fields.size(); ++i)
  247. {
  248. if (currentCloudMsg.fields[i].name == “ring”)
  249. {
  250. ringFlag = 1;
  251. break;
  252. }
  253. }
  254. if (ringFlag == -1)
  255. {
  256. ROS_ERROR(“Point cloud ring channel not available, please configure your point cloud data!”);
  257. ros::shutdown();
  258. }
  259. }
  260. // check point time
  261. // 检查是否存在time通道
  262. if (deskewFlag == 0)
  263. {
  264. deskewFlag = -1;
  265. for (auto &field : currentCloudMsg.fields)
  266. {
  267. if (field.name == “time” || field.name == “t”)
  268. {
  269. deskewFlag = 1;
  270. break;
  271. }
  272. }
  273. if (deskewFlag == -1)
  274. ROS_WARN(“Point cloud timestamp not available, deskew function disabled, system will drift significantly!”);
  275. }
  276. return true;
  277. }
  278. bool deskewInfo()
  279. {
  280. std::lock_guard<std::mutex> lock1(imuLock);
  281. std::lock_guard<std::mutex> lock2(odoLock);
  282. // make sure IMU data available for the scan
  283. // 要求imu数据时间上包含激光数据,否则不往下处理了
  284. if (imuQueue.empty() || imuQueue.front().header.stamp.toSec() > timeScanCur || imuQueue.back().header.stamp.toSec() < timeScanEnd)
  285. {
  286. ROS_DEBUG(“Waiting for IMU data …”);
  287. return false;
  288. }
  289. // 当前帧对应imu数据处理
  290. // 1、遍历当前激光帧起止时刻之间的imu数据,初始时刻对应imu的姿态角RPY设为当前帧的初始姿态角
  291. // 2、用角速度、时间积分,计算每一时刻相对于初始时刻的旋转量,初始时刻旋转设为0
  292. // 注:imu数据都已经转换到lidar系下了
  293. //imu去畸变参数计算
  294. imuDeskewInfo();
  295. // 当前帧对应imu里程计处理
  296. // 1、遍历当前激光帧起止时刻之间的imu里程计数据,初始时刻对应imu里程计设为当前帧的初始位姿
  297. // 2、用起始、终止时刻对应imu里程计,计算相对位姿变换,保存平移增量
  298. // 注:imu数据都已经转换到lidar系下了
  299. //里程计去畸变参数计算
  300. odomDeskewInfo();
  301. return true;
  302. }
  303. void imuDeskewInfo()
  304. {
  305. cloudInfo.imuAvailable = false;
  306. // 从imu队列中删除当前激光帧0.01s前面时刻的imu数据
  307. while (!imuQueue.empty())
  308. {
  309. if (imuQueue.front().header.stamp.toSec() < timeScanCur - 0.01)
  310. imuQueue.pop_front();
  311. else
  312. break;
  313. }
  314. if (imuQueue.empty())
  315. return;
  316. imuPointerCur = 0;
  317. // 遍历当前激光帧起止时刻(前后扩展0.01s)之间的imu数据
  318. for (int i = 0; i < (int)imuQueue.size(); ++i)
  319. {
  320. sensor_msgs::Imu thisImuMsg = imuQueue[i];
  321. double currentImuTime = thisImuMsg.header.stamp.toSec();
  322. // get roll, pitch, and yaw estimation for this scan
  323. // 提取imu姿态角RPY,作为当前lidar帧初始姿态角
  324. if (currentImuTime <= timeScanCur)
  325. imuRPY2rosRPY(&thisImuMsg, &cloudInfo.imuRollInit, &cloudInfo.imuPitchInit, &cloudInfo.imuYawInit);
  326. // 超过当前激光帧结束时刻0.01s,结束
  327. if (currentImuTime > timeScanEnd + 0.01)
  328. break;
  329. // 第一帧imu旋转角初始化
  330. if (imuPointerCur == 0){
  331. imuRotX[0] = 0;
  332. imuRotY[0] = 0;
  333. imuRotZ[0] = 0;
  334. imuTime[0] = currentImuTime;
  335. ++imuPointerCur;
  336. continue;
  337. }
  338. // get angular velocity
  339. // 提取imu角速度
  340. double angular_x, angular_y, angular_z;
  341. imuAngular2rosAngular(&thisImuMsg, &angular_x, &angular_y, &angular_z);
  342. // integrate rotation
  343. double timeDiff = currentImuTime - imuTime[imuPointerCur-1];
  344. imuRotX[imuPointerCur] = imuRotX[imuPointerCur-1] + angular_x _ timeDiff;
  345. imuRotY[imuPointerCur] = imuRotY[imuPointerCur-1] + angular_y _ timeDiff;
  346. imuRotZ[imuPointerCur] = imuRotZ[imuPointerCur-1] + angular_z _ timeDiff;
  347. imuTime[imuPointerCur] = currentImuTime;
  348. ++imuPointerCur;
  349. }
  350. —imuPointerCur;
  351. // 没有合规的imu数据
  352. if (imuPointerCur <= 0)
  353. return;
  354. cloudInfo.imuAvailable = true;
  355. }
  356. //初始pose信息保存在cloudInfo里
  357. void odomDeskewInfo()
  358. {
  359. cloudInfo.odomAvailable = false;
  360. // 从imu里程计队列中删除当前激光帧0.01s前面时刻的imu数据
  361. while (!odomQueue.empty())
  362. {
  363. if (odomQueue.front().header.stamp.toSec() < timeScanCur - 0.01)
  364. odomQueue.pop_front();
  365. else
  366. break;
  367. }
  368. if (odomQueue.empty())
  369. return;
  370. // 要求必须有当前激光帧时刻之前的里程计数据
  371. if (odomQueue.front().header.stamp.toSec() > timeScanCur)
  372. return;
  373. // get start odometry at the beinning of the scan(地图优化程序中发布的)
  374. nav_msgs::Odometry startOdomMsg;
  375. for (int i = 0; i < (int)odomQueue.size(); ++i)
  376. {
  377. startOdomMsg = odomQueue[i];
  378. // 在cloudHandler的cachePointCloud函数中,timeScanCur = cloudHeader.stamp.toSec();,即当前帧点云的初始时刻
  379. //找到第一个大于初始时刻的odom
  380. if (ROS_TIME(&startOdomMsg) < timeScanCur)
  381. continue;
  382. else
  383. break;
  384. }
  385. // 提取imu里程计姿态角
  386. tf::Quaternion orientation;
  387. tf::quaternionMsgToTF(startOdomMsg.pose.pose.orientation, orientation);
  388. double roll, pitch, yaw;
  389. tf::Matrix3x3(orientation).getRPY(roll, pitch, yaw);
  390. // Initial guess used in mapOptimization
  391. // 用当前激光帧起始时刻的imu里程计,初始化lidar位姿,后面用于mapOptmization
  392. cloudInfo.initialGuessX = startOdomMsg.pose.pose.position.x;
  393. cloudInfo.initialGuessY = startOdomMsg.pose.pose.position.y;
  394. cloudInfo.initialGuessZ = startOdomMsg.pose.pose.position.z;
  395. cloudInfo.initialGuessRoll = roll;
  396. cloudInfo.initialGuessPitch = pitch;
  397. cloudInfo.initialGuessYaw = yaw;
  398. cloudInfo.odomAvailable = true;
  399. // get end odometry at the end of the scan
  400. odomDeskewFlag = false;
  401. // 如果当前激光帧结束时刻之后没有imu里程计数据,返回
  402. if (odomQueue.back().header.stamp.toSec() < timeScanEnd)
  403. return;
  404. nav_msgs::Odometry endOdomMsg;
  405. // 提取当前激光帧结束时刻的imu里程计
  406. for (int i = 0; i < (int)odomQueue.size(); ++i)
  407. {
  408. endOdomMsg = odomQueue[i];
  409. // 在cloudHandler的cachePointCloud函数中, timeScanEnd = timeScanCur + laserCloudIn->points.back().time;
  410. // 找到第一个大于一帧激光结束时刻的odom
  411. if (ROS_TIME(&endOdomMsg) < timeScanEnd)
  412. continue;
  413. else
  414. break;
  415. }
  416. // 如果起止时刻对应imu里程计的方差不等,返回
  417. if (int(round(startOdomMsg.pose.covariance[0])) != int(round(endOdomMsg.pose.covariance[0])))
  418. return;
  419. //感觉之后计算的信息并没有被用到
  420. Eigen::Affine3f transBegin = pcl::getTransformation(startOdomMsg.pose.pose.position.x, startOdomMsg.pose.pose.position.y, startOdomMsg.pose.pose.position.z, roll, pitch, yaw);
  421. tf::quaternionMsgToTF(endOdomMsg.pose.pose.orientation, orientation);
  422. tf::Matrix3x3(orientation).getRPY(roll, pitch, yaw);
  423. Eigen::Affine3f transEnd = pcl::getTransformation(endOdomMsg.pose.pose.position.x, endOdomMsg.pose.pose.position.y, endOdomMsg.pose.pose.position.z, roll, pitch, yaw);
  424. // 起止时刻imu里程计的相对变换
  425. Eigen::Affine3f transBt = transBegin.inverse() _ transEnd;
  426. // 相对变换,提取增量平移、旋转(欧拉角)
  427. float rollIncre, pitchIncre, yawIncre;
  428. // 给定的转换中,提取XYZ以及欧拉角,通过tranBt 获得增量值 后续去畸变用到
  429. pcl::getTranslationAndEulerAngles(transBt, odomIncreX, odomIncreY, odomIncreZ, rollIncre, pitchIncre, yawIncre);
  430. odomDeskewFlag = true;
  431. }
  432. /
  433. _ 在当前激光帧起止时间范围内,计算某一时刻的旋转(相对于起始时刻的旋转增量)
  434. _/
  435. void findRotation(double pointTime, float _rotXCur, float _rotYCur, float _rotZCur)
  436. {
  437. _rotXCur = 0; _rotYCur = 0; _rotZCur = 0;
  438. // 查找当前时刻在imuTime下的索引
  439. int imuPointerFront = 0;
  440. //imuDeskewInfo中,对imuPointerCur进行计数(计数到超过当前激光帧结束时刻0.01s)
  441. while (imuPointerFront < imuPointerCur)
  442. {
  443. //imuTime在imuDeskewInfo(deskewInfo中调用,deskewInfo在cloudHandler中调用)被赋值,从imuQueue中取值
  444. //pointTime为当前时刻,由此函数的函数形参传入,要找到imu积分列表里第一个大于当前时间的索引
  445. if (pointTime < imuTime[imuPointerFront])
  446. break;
  447. ++imuPointerFront;
  448. }
  449. // 设为离当前时刻最近的旋转增量
  450. //如果计数为0或该次imu时间戳小于了当前时间戳(异常退出)
  451. if (pointTime > imuTime[imuPointerFront] || imuPointerFront == 0)
  452. {
  453. //未找到大于当前时刻的imu积分索引
  454. //imuRotX等为之前积分出的内容.(imuDeskewInfo中)
  455. _rotXCur = imuRotX[imuPointerFront];
  456. _rotYCur = imuRotY[imuPointerFront];
  457. _rotZCur = imuRotZ[imuPointerFront];
  458. } else {
  459. //
  460. // 前后时刻插值计算当前时刻的旋转增量
  461. //此时front的时间是大于当前pointTime时间,back=front-1刚好小于当前pointTime时间,前后时刻插值计算
  462. int imuPointerBack = imuPointerFront - 1;
  463. //算一下该点时间戳在本组imu中的位置
  464. double ratioFront = (pointTime - imuTime[imuPointerBack]) / (imuTime[imuPointerFront] - imuTime[imuPointerBack]);
  465. double ratioBack = (imuTime[imuPointerFront] - pointTime) / (imuTime[imuPointerFront] - imuTime[imuPointerBack]);
  466. //这三项作为函数返回值,以形参指针的方式返回
  467. //按前后百分比赋予旋转量
  468. _rotXCur = imuRotX[imuPointerFront] _ ratioFront + imuRotX[imuPointerBack] _ ratioBack;
  469. _rotYCur = imuRotY[imuPointerFront] _ ratioFront + imuRotY[imuPointerBack] _ ratioBack;
  470. _rotZCur = imuRotZ[imuPointerFront] _ ratioFront + imuRotZ[imuPointerBack] _ ratioBack;
  471. }
  472. }
  473. void findPosition(double relTime, float _posXCur, float _posYCur, float _posZCur)
  474. {
  475. // // 如果传感器移动速度较慢,例如人行走的速度,那么可以认为激光在一帧时间范围内,平移量小到可以忽略不计
  476. _posXCur = 0; _posYCur = 0; _posZCur = 0;
  477. // If the sensor moves relatively slow, like walking speed, positional deskew seems to have little benefits. Thus code below is commented.
  478. // if (cloudInfo.odomAvailable == false || odomDeskewFlag == false)
  479. // return;
  480. // float ratio = relTime / (timeScanEnd - timeScanCur);
  481. // _posXCur = ratio _ odomIncreX;
  482. // _posYCur = ratio _ odomIncreY;
  483. // _posZCur = ratio _ odomIncreZ;
  484. }
  485. /
  486. _ 激光运动畸变校正
  487. _ 利用当前帧起止时刻之间的imu数据计算旋转增量,imu里程计数据计算平移增量,进而将每一时刻激光点位置变换到第一个激光点坐标系下,进行运动补偿
  488. _/
  489. //relTime:laserCloudIn->points[i].time
  490. PointType deskewPoint(PointType _point, double relTime)
  491. {
  492. //这个来源于上文的时间戳通道和imu可用判断,没有或是不可用则返回点
  493. if (deskewFlag == -1 || cloudInfo.imuAvailable == false)
  494. return _point;
  495. //点的时间等于scan时间加relTime(后文的laserCloudIn->points[i].time)
  496. //lasercloudin中存储的time是一帧中距离起始点的相对时间
  497. // 在cloudHandler的cachePointCloud函数中,timeScanCur = cloudHeader.stamp.toSec();,即当前帧点云的初始时刻
  498. //二者相加即可得到当前点的准确时刻
  499. double pointTime = timeScanCur + relTime;
  500. //根据时间戳插值获取imu计算的旋转量与位置量(注意imu计算的相对于起始时刻的旋转增量)
  501. float rotXCur, rotYCur, rotZCur;
  502. findRotation(pointTime, &rotXCur, &rotYCur, &rotZCur);
  503. float posXCur, posYCur, posZCur;
  504. findPosition(relTime, &posXCur, &posYCur, &posZCur);
  505. //这里的firstPointFlag来源于resetParameters函数,而resetParameters函数每次ros调用cloudHandler都会启动
  506. 第一个点的位姿增量(0),求逆
  507. if (firstPointFlag == true)
  508. {
  509. transStartInverse = (pcl::getTransformation(posXCur, posYCur, posZCur, rotXCur, rotYCur, rotZCur)).inverse();
  510. firstPointFlag = false;//改成false以后,同一帧激光数据的下一次就不执行了
  511. }
  512. // transform points to start
  513. //扫描当前点时lidar的世界坐标系下变换矩阵
  514. Eigen::Affine3f transFinal = pcl::getTransformation(posXCur, posYCur, posZCur, rotXCur, rotYCur, rotZCur);
  515. //扫描该点相对扫描本次scan第一个点的lidar变换矩阵=
  516. //第一个点时lidar世界坐标系下变换矩阵的逆×当前点时lidar世界坐标系下变换矩阵
  517. //Tij=Twi^-1 _ Twj
  518. //注:这里准确的来说,不是世界坐标系,
  519. //根据代码来看,是把imu积分:
  520. //从imuDeskewInfo函数中,在当前激光帧开始的前0.01秒的imu数据开始积分,
  521. //把它作为原点,然后获取当前激光帧第一个点时刻的位姿增量transStartInverse,
  522. //和当前点时刻的位姿增量transFinal,根据逆矩阵计算二者变换transBt。
  523. //因此相对的不是“世界坐标系”,
  524. //而是“当前激光帧开始前的0.01秒的雷达坐标系(在imucallback函数中已经把imu转换到了雷达坐标系了)
  525. Eigen::Affine3f transBt = transStartInverse _ transFinal;
  526. PointType newPoint;
  527. //根据lidar位姿变换 Tij,修正点云位置: Tij _ Pj
  528. newPoint.x = transBt(0,0) _ point->x + transBt(0,1) _ point->y + transBt(0,2) _ point->z + transBt(0,3);
  529. newPoint.y = transBt(1,0) _ point->x + transBt(1,1) _ point->y + transBt(1,2) _ point->z + transBt(1,3);
  530. newPoint.z = transBt(2,0) _ point->x + transBt(2,1) _ point->y + transBt(2,2) _ point->z + transBt(2,3);
  531. newPoint.intensity = point->intensity;
  532. return newPoint;
  533. }
  534. void projectPointCloud()
  535. {
  536. int cloudSize = laserCloudIn->points.size(); //点云数据量 用于下面一个个点投影
  537. // range image projection
  538. for (int i = 0; i < cloudSize; ++i)
  539. {
  540. PointType thisPoint;
  541. //laserCloudIn就是原始的点云话题中的数据
  542. thisPoint.x = laserCloudIn->points[i].x;
  543. thisPoint.y = laserCloudIn->points[i].y;
  544. thisPoint.z = laserCloudIn->points[i].z;
  545. thisPoint.intensity = laserCloudIn->points[i].intensity;
  546. float range = pointDistance(thisPoint);
  547. if (range < lidarMinRange || range > lidarMaxRange)
  548. continue;
  549. //距离图像的行 与点云中ring对应,
  550. //rowIdn计算出该点激光雷达是水平方向上第几线的。从下往上计数,-15度记为初始线,第0线,一共16线(N_SCAN=16
  551. int rowIdn = laserCloudIn->points[i].ring;
  552. if (rowIdn < 0 || rowIdn >= N_SCAN)
  553. continue;
  554. if (rowIdn % downsampleRate != 0)
  555. continue;
  556. //水平角分辨率
  557. float horizonAngle = atan2(thisPoint.x, thisPoint.y) _ 180 / M_PI;
  558. //Horizon_SCAN=1800,每格0.2度
  559. static float ang_res_x = 360.0/float(Horizon_SCAN);
  560. //horizonAngle 为[-180,180],horizonAngle -90 为[-270,90],-round 为[-90,270], /ang_res_x 为[-450,1350]
  561. //+Horizon_SCAN/2为[450,2250]
  562. // 即把horizonAngle从[-180,180]映射到[450,2250]
  563. int columnIdn = -round((horizonAngle-90.0)/ang_res_x) + Horizon_SCAN/2;
  564. //大于1800,则减去1800,相当于把1801~2250映射到1~450
  565. //先把columnIdn从horizonAngle:(-PI,PI]转换到columnIdn:[H/4,5H/4],
  566. //然后判断columnIdn大小,把H到5H/4的部分切下来,补到0~H/4的部分。
  567. //将它的范围转换到了[0,H] (H:Horizon_SCAN)。
  568. //这样就把扫描开始的地方角度为0与角度为360的连在了一起,非常巧妙。
  569. //如果前方是x,左侧是y,那么正后方左边是180,右边是-180。这里的操作就是,把它展开成一幅图:
  570. // 0
  571. // 90 -90
  572. // 180 || (-180)
  573. // (-180) ——- (-90) ——— 0 ——— 90 ———-180
  574. //变为: 90 ——180(-180) —— (-90) ——- (0) ——- 90
  575. if (columnIdn >= Horizon_SCAN)
  576. columnIdn -= Horizon_SCAN;
  577. if (columnIdn < 0 || columnIdn >= Horizon_SCAN)
  578. continue;
  579. if (rangeMat.at<float>(rowIdn, columnIdn) != FLT_MAX)
  580. continue;
  581. //去畸变 运动补偿 这里需要用到雷达信息中的time 这个field
  582. thisPoint = deskewPoint(&thisPoint, laserCloudIn->points[i].time);
  583. //图像中填入欧几里得深度
  584. rangeMat.at<float>(rowIdn, columnIdn) = range;
  585. // 转换成一维索引,存校正之后的激光点
  586. int index = columnIdn + rowIdn _ Horizon_SCAN;
  587. fullCloud->points[index] = thisPoint;
  588. }
  589. }
  590. void cloudExtraction()
  591. {
  592. // 有效激光点数量
  593. int count = 0;
  594. // extract segmented cloud for lidar odometry
  595. for (int i = 0; i < N_SCAN; ++i)
  596. {
  597. //提取特征的时候,每一行的前5个和最后5个不考虑
  598. //记录每根扫描线起始第5个激光点在一维数组中的索引
  599. //cloudInfo为自定义的msg
  600. // 记录每根扫描线起始第5个激光点在一维数组中的索引
  601. cloudInfo.startRingIndex[i] = count - 1 + 5;
  602. ///Horizon_SCAN=1800
  603. for (int j = 0; j < Horizon_SCAN; ++j)
  604. {
  605. if (rangeMat.at<float>(i,j) != FLT_MAX)
  606. {
  607. // mark the points’ column index for marking occlusion later
  608. // 记录激光点对应的Horizon_SCAN方向上的索引
  609. cloudInfo.pointColInd[count] = j;
  610. // save range info激光点距离
  611. cloudInfo.pointRange[count] = rangeMat.at<float>(i,j);
  612. // save extracted cloud
  613. // 加入有效激光点
  614. extractedCloud->push_back(fullCloud->points[j + i_Horizon_SCAN]);
  615. // size of extracted cloud
  616. ++count;
  617. }
  618. }
  619. // 记录每根扫描线倒数第5个激光点在一维数组中的索引
  620. cloudInfo.endRingIndex[i] = count -1 - 5;
  621. }
  622. }
  623. /
  624. _ 发布当前帧校正后点云,有效点
  625. _/
  626. void publishClouds()
  627. {
  628. cloudInfo.header = cloudHeader;
  629. //publishCloud在utility.h头文件中,需要传入发布句柄pubExtractedCloud,提取出的有效点云,该帧时间戳,
  630. //pubExtractedCloud定义在构造函数中,用来发布去畸变的点云.
  631. //extractedCloud主要在cloudExtraction中被提取,点云被去除了畸变,
  632. //另外每行头五个和后五个不要((仍然被保存,但是之后在提取特征时不要,因为要根据前后五个点算曲率)
  633. //cloudHeader.stamp 来源于currentCloudMsg,cloudHeader在cachePointCloud中被赋值currentCloudMsg.header
  634. //而currentCloudMsg是点云队列cloudQueue中提取的
  635. //lidarFrame:在utility.h中被赋为base_link,
  636. //在publishCloud函数中,tempCloud.header.frame_id=”base_link”(lidarFrame)
  637. //之后用发布句柄pubExtractedCloud来发布去畸变的点云
  638. cloudInfo.cloud_deskewed = publishCloud(&pubExtractedCloud, extractedCloud, cloudHeader.stamp, lidarFrame);
  639. //发布自定义cloud_info信息
  640. pubLaserCloudInfo.publish(cloudInfo);
  641. //pubExtractedCloud发布的只有点云信息,而pubLaserCloudInfo发布的为自定义的很多信息
  642. }
  643. };
  644. int main(int argc, char argv)
  645. {
  646. ros::init(argc, argv, “lio_sam”);
  647. ImageProjection IP;
  648. ROS_INFO(“\033[1;32m——> Image Projection Started.\033[0m”);
  649. //对于一些只订阅一个话题的简单节点来说,我们使用ros::spin()进入接收循环,
  650. //每当有订阅的话题发布时,进入回调函数接收和处理消息数据。
  651. //但是更多的时候,一个节点往往要接收和处理不同来源的数据,并且这些数据的产生频率也各不相同,
  652. //当我们在一个回调函数里耗费太多时间时,会导致其他回调函数被阻塞,导致数据丢失。
  653. //这种场合需要给一个节点开辟多个线程,保证数据流的畅通。
  654. ros::MultiThreadedSpinner spinner(3);
  655. spinner.spin();
  656. return 0;
  657. }



总结


我会依次把下面的内容标号,请注意我的标号。


和大多数的SLAM算法一样,程序就在回调函数里处理算法。


1:imu原始数据送入imuhandle,放入imuqueue中;


2.odometry/imu_incremental送入odomhandle,放入odomqueue中。



这里要说一下,注意两点:


第一,这个话题是imu里程计,是来自IMUPreintegration(imuPreintegration.cpp中的类IMUPreintegration)发布的里程计话题。既然叫里程计,就不是两帧之间的预积分数据。不要被它名字里的incremental误导了,以为它好像是一个增加的量,以为是一段中间时刻内的数据。这种理解是不对的。它就是一个里程计数据,通过imu预积分计算优化来得到的任意时刻在世界坐标系下的位姿。


第二,mapOptimization.cpp文件还会发布一个叫”lio_sam/mapping/odometry_incremental”,它代表的是激光里程计,不要和这里的odometry/imu_incremental混起来。


3.原始点云数据送入cloudhandle:


3.1 点云加入cloudQueue,检查数据有效性(格式上,主要因为雷达款式不同)


3.2 deskewinfo:



 3.2.1 imuDeskewInfo:遍历激光帧,从imuqueue中找当前激光帧前0.01s开始,当前帧后0.01s结束,找到最近的一个imu数据,把它的原始角度数据,作为cloudInfo.imuRollInit等变量。cloudInfo是自定义的一个消息类型,用来之后发布去畸变的点云,具体可以看cloud_info.msg里面的定义。与此同时,要根据角速度信息做一个积分,保存到imuRotX等数据结构中,之后用来去畸变。


3.2.2 odomDeskewInfo:遍历imu里程计的odomqueue队列,剔除当前0.01s之前的数据,找到第一个大于当前激光帧的数据,然后用里程计数据来初始化雷达,也是填充角度,不过这次填充的是cloudInfo.initialGuessRoll等变量,位置也会被填充到initialGuessX里。


注意:cloudInfo.initialGuessRoll和cloudInfo.imuRollInit,这些东西都是角度数据,带Guess的为imu里程计提供的数据,imuRollInit这种为imu原始数据。如果有合适的,分别会填充cloudInfo.odomAvailable和cloudInfo.imuAvailable变量为true,代表这块的数据可用。这些数据到底用在哪里呢?


这也需要剧透:会被用在mapOptimization.cpp的updateInitGuess函数,给激光里程计做一个初始化,然后在这个初始化的基础上进行非线性优化。


 3.3 projectPointCloud:



3.3.1 获取点云中的每一个点,投影图像。


3.3.2 去畸变。假设一帧激光数据,是在一个很小的时间段内获取的,但是由于这段时间内,激光雷达可能处于运动状态,那么就可能导致运动畸变。这里就要用到了3.2.1中提到的imuRotX等玩意,根据imu的运动信息,把这段时间内依次接收的每个点统一投影到初始时刻,去除运动畸变。


3.4 CloudExtraction:


这个是想把特征依次装到一个一维数组中,然后发布到别的进程里处理。


既然是一维数组,16线的点都弄到一维数组里,那就比较麻烦。虽然说这里要弄一个深度投影图像,但是其实进程之间传输的并不是这个深度投影图像,而是自定义的cloudinfo形式的数据。


实际上是想把有效的数据记录进来,例如空值不要,每根线前5个和后5个也不要……那这样16线的数据混到一维组里就分不清了,所以要记录下每根扫瞄线起始点在1维数组中的索引startRingIndex,结束点的索引endRingIndex,在原始图像中的列数pointColInd,距离值pointRange。然后把有效激光点,放到extractedCloud中。


3.5 publishClouds:


把extractedCloud发布出去,/lio_sam/deskew/cloud_deskewed,这个只有点云信息。


然后再把这些点,赋值到cloudInfo.cloud_deskewed中,把整个的cloudInfo发布出去,名字就叫“lio_sam/deskew/cloud_info”,这个就是作者自己定义的特殊的msg。




featureExtraction.cpp


注释


  1. #include “utility.h”
  2. #include “lio_sam/cloud_info.h”
  3. struct <span class=”hljs-title class_“>smoothness_t{
  4. float value; // 曲率值
  5. size_t ind; // 激光点一维索引
  6. };
  7. /_*
  8. _ 曲率比较函数,从小到大排序
  9. */
  10. struct <span class=”hljs-title class_“>by_value{
  11. bool operator()(smoothness_t const &left, smoothness_t const &right) {
  12. return left.value < right.value;
  13. }
  14. };
  15. class <span class=”hljs-title class_“>FeatureExtraction : public ParamServer
  16. {
  17. public:
  18. ros::Subscriber subLaserCloudInfo;
  19. // 发布当前激光帧提取特征之后的点云信息
  20. ros::Publisher pubLaserCloudInfo;
  21. // 发布当前激光帧提取的角点点云
  22. ros::Publisher pubCornerPoints;
  23. // 发布当前激光帧提取的平面点点云
  24. ros::Publisher pubSurfacePoints;
  25. // 当前激光帧运动畸变校正后的有效点云
  26. pcl::PointCloud<PointType>::Ptr extractedCloud;
  27. // 当前激光帧角点点云集合
  28. pcl::PointCloud<PointType>::Ptr cornerCloud;
  29. // 当前激光帧平面点点云集合
  30. pcl::PointCloud<PointType>::Ptr surfaceCloud;
  31. pcl::VoxelGrid<PointType> downSizeFilter;
  32. // 当前激光帧点云信息,包括的历史数据有:运动畸变校正,点云数据,初始位姿,姿态角,有效点云数据,角点点云,平面点点云等
  33. lio_sam::cloud_info cloudInfo;
  34. std_msgs::Header cloudHeader;
  35. std::vector<smoothness_t> cloudSmoothness;
  36. //用来做曲率计算的中间变量
  37. float _cloudCurvature;
  38. // 特征提取标记,1表示遮挡、平行,或者已经进行特征提取的点,0表示还未进行特征提取处理
  39. int _cloudNeighborPicked;
  40. // 1表示角点,-1表示平面点
  41. int _cloudLabel;
  42. FeatureExtraction()
  43. {
  44. // 订阅当前激光帧运动畸变校正后的点云信息
  45. subLaserCloudInfo = nh.subscribe<lio_sam::cloud_info>(“lio_sam/deskew/cloud_info”, 1, &FeatureExtraction::laserCloudInfoHandler, this, ros::TransportHints().tcpNoDelay());
  46. // 发布当前激光帧提取特征之后的点云信息
  47. pubLaserCloudInfo = nh.advertise<lio_sam::cloud_info> (“lio_sam/feature/cloud_info”, 1);
  48. // 发布当前激光帧的角点点云
  49. pubCornerPoints = nh.advertise<sensor_msgs::PointCloud2>(“lio_sam/feature/cloud_corner”, 1);
  50. // 发布当前激光帧的面点点云
  51. pubSurfacePoints = nh.advertise<sensor_msgs::PointCloud2>(“lio_sam/feature/cloud_surface”, 1);
  52. // 初始化
  53. initializationValue();
  54. }
  55. void initializationValue()
  56. {
  57. cloudSmoothness.resize(N_SCAN_Horizon_SCAN);
  58. downSizeFilter.setLeafSize(odometrySurfLeafSize, odometrySurfLeafSize, odometrySurfLeafSize);
  59. extractedCloud.reset(new pcl::PointCloud<PointType>());
  60. cornerCloud.reset(new pcl::PointCloud<PointType>());
  61. surfaceCloud.reset(new pcl::PointCloud<PointType>());
  62. cloudCurvature = new float[N_SCAN_Horizon_SCAN];
  63. cloudNeighborPicked = new int[N_SCAN_Horizon_SCAN];
  64. cloudLabel = new int[N_SCAN_Horizon_SCAN];
  65. }
  66. //接收imageProjection.cpp中发布的去畸变的点云,实时处理的回调函数
  67. void laserCloudInfoHandler(const lio_sam::cloud_infoConstPtr& msgIn)
  68. {
  69. //msgIn即为回调函数获取的去畸变点云信息
  70. cloudInfo = _msgIn; // new cloud info
  71. cloudHeader = msgIn->header; // new cloud header
  72. pcl::fromROSMsg(msgIn->cloud_deskewed, _extractedCloud); // new cloud for extraction
  73. // 计算当前激光帧点云中每个点的曲率
  74. calculateSmoothness();
  75. // 标记属于遮挡、平行两种情况的点,不做特征提取
  76. markOccludedPoints();
  77. // 点云角点、平面点特征提取
  78. // 1、遍历扫描线,每根扫描线扫描一周的点云划分为6段,针对每段提取20个角点、不限数量的平面点,加入角点集合、平面点集合
  79. // 2、认为非角点的点都是平面点,加入平面点云集合,最后降采样
  80. extractFeatures();
  81. // 发布角点、面点点云,发布带特征点云数据的当前激光帧点云信息
  82. publishFeatureCloud();
  83. }
  84. void calculateSmoothness()
  85. {
  86. // 遍历当前激光帧运动畸变校正后的有效点云
  87. int cloudSize = extractedCloud->points.size();
  88. for (int i = 5; i < cloudSize - 5; i++)
  89. {
  90. // 用当前激光点前后5个点计算当前点的曲率
  91. //注意,这里把前后五个点共10个点加起来,还减去了10倍的当前点
  92. float diffRange = cloudInfo.pointRange[i-5] + cloudInfo.pointRange[i-4]
  93. + cloudInfo.pointRange[i-3] + cloudInfo.pointRange[i-2]
  94. + cloudInfo.pointRange[i-1] - cloudInfo.pointRange[i] _ 10
  95. + cloudInfo.pointRange[i+1] + cloudInfo.pointRange[i+2]
  96. + cloudInfo.pointRange[i+3] + cloudInfo.pointRange[i+4]
  97. + cloudInfo.pointRange[i+5];
  98. // 距离差值平方作为曲率
  99. cloudCurvature[i] = diffRange_diffRange;//diffX _ diffX + diffY _ diffY + diffZ _ diffZ;
  100. //0表示还未进行特征提取处理,1表示遮挡、平行,或者已经进行特征提取的点
  101. cloudNeighborPicked[i] = 0;
  102. //1表示角点,-1表示平面点
  103. cloudLabel[i] = 0;
  104. // 存储该点曲率值、激光点一维索引
  105. //之所以可以这样操作,是因为在initializationValue部分,对cloudSmoothness进行过初始化,
  106. //否则直接对cloudSmoothness[i]赋值,一定会报段错误
  107. cloudSmoothness[i].value = cloudCurvature[i];
  108. cloudSmoothness[i].ind = i;
  109. }
  110. }
  111. void markOccludedPoints()
  112. {
  113. int cloudSize = extractedCloud->points.size();
  114. // mark occluded points and parallel beam points
  115. for (int i = 5; i < cloudSize - 6; ++i)
  116. {
  117. // 当前点和下一个点的range值
  118. float depth1 = cloudInfo.pointRange[i];
  119. float depth2 = cloudInfo.pointRange[i+1];
  120. // 两个激光点之间的一维索引差值,如果在一条扫描线上,那么值为1;
  121. //如果两个点之间有一些无效点被剔除了,可能会比1大,但不会特别大
  122. // 如果恰好前一个点在扫描一周的结束时刻,下一个点是另一条扫描线的起始时刻,那么值会很大
  123. int columnDiff = std::abs(int(cloudInfo.pointColInd[i+1] - cloudInfo.pointColInd[i]));
  124. // 两个点在同一扫描线上,且距离相差大于0.3,认为存在遮挡关系
  125. //(也就是这两个点不在同一平面上,如果在同一平面上,距离相差不会太大)
  126. // 远处的点会被遮挡,标记一下该点以及相邻的5个点,后面不再进行特征提取
  127. if (columnDiff < 10){
  128. // 10 pixel diff in range image
  129. if (depth1 - depth2 > 0.3){
  130. cloudNeighborPicked[i - 5] = 1;
  131. cloudNeighborPicked[i - 4] = 1;
  132. cloudNeighborPicked[i - 3] = 1;
  133. cloudNeighborPicked[i - 2] = 1;
  134. cloudNeighborPicked[i - 1] = 1;
  135. cloudNeighborPicked[i] = 1;
  136. }else if (depth2 - depth1 > 0.3){
  137. cloudNeighborPicked[i + 1] = 1;
  138. cloudNeighborPicked[i + 2] = 1;
  139. cloudNeighborPicked[i + 3] = 1;
  140. cloudNeighborPicked[i + 4] = 1;
  141. cloudNeighborPicked[i + 5] = 1;
  142. cloudNeighborPicked[i + 6] = 1;
  143. }
  144. }
  145. // parallel beam
  146. // 用前后相邻点判断当前点所在平面是否与激光束方向平行
  147. //diff1和diff2是当前点距离前后两个点的距离
  148. float diff1 = std::abs(float(cloudInfo.pointRange[i-1] - cloudInfo.pointRange[i]));
  149. float diff2 = std::abs(float(cloudInfo.pointRange[i+1] - cloudInfo.pointRange[i]));
  150. //如果当前点距离左右邻点都过远,则视其为瑕点,因为入射角可能太小导致误差较大
  151. // 选择距离变化较大的点,并将他们标记为1
  152. if (diff1 > 0.02 _ cloudInfo.pointRange[i] && diff2 > 0.02 _ cloudInfo.pointRange[i])
  153. cloudNeighborPicked[i] = 1;
  154. }
  155. }
  156. void extractFeatures()
  157. {
  158. cornerCloud->clear();
  159. surfaceCloud->clear();
  160. pcl::PointCloud<PointType>::Ptr surfaceCloudScan(new pcl::PointCloud<PointType>());
  161. pcl::PointCloud<PointType>::Ptr surfaceCloudScanDS(new pcl::PointCloud<PointType>());
  162. for (int i = 0; i < N_SCAN; i++)
  163. {
  164. surfaceCloudScan->clear();
  165. // 将一条扫描线扫描一周的点云数据,划分为6段,每段分开提取有限数量的特征,保证特征均匀分布
  166. for (int j = 0; j < 6; j++)
  167. {
  168. // 每段点云的起始、结束索引;startRingIndex为扫描线起始第5个激光点在一维数组中的索引
  169. //注意:所有的点云在这里都是以”一维数组”的形式保存
  170. //startRingIndex和 endRingIndex 在imageProjection.cpp中的 cloudExtraction函数里被填入
  171. //假设 当前ring在一维数组中起始点是m,结尾点为n(不包括n),那么6段的起始点分别为:
  172. // m + [(n-m)/6]_j j从0~5
  173. // 化简为 [(6-j)_m + nj ]/6
  174. // 6段的终止点分别为:
  175. // m + (n-m)/6 + [(n-m)/6]_j -1 j从0~5,-1是因为最后一个,减去1
  176. // 化简为 [(5-j)_m + (j+1)_n ]/6 -1
  177. //这块不必细究边缘值到底是不是划分的准(例如考虑前五个点是不是都不要,还是说只不要前四个点),
  178. //只是尽可能的分开成六段,首位相接的地方不要。因为庞大的点云中,一两个点其实无关紧要。
  179. int sp = (cloudInfo.startRingIndex[i] _ (6 - j) + cloudInfo.endRingIndex[i] _ j) / 6;
  180. int ep = (cloudInfo.startRingIndex[i] _ (5 - j) + cloudInfo.endRingIndex[i] _ (j + 1)) / 6 - 1;
  181. if (sp >= ep)
  182. continue;
  183. // 按照曲率从小到大排序点云
  184. //可以看出之前的byvalue在这里被当成了判断函数来用
  185. std::sort(cloudSmoothness.begin()+sp, cloudSmoothness.begin()+ep, by_value());
  186. int largestPickedNum = 0;
  187. // 按照曲率从大到小遍历
  188. for (int k = ep; k >= sp; k—)
  189. {
  190. // 激光点的索引
  191. int ind = cloudSmoothness[k].ind;
  192. // 当前激光点还未被处理,且曲率大于阈值,则认为是角点
  193. if (cloudNeighborPicked[ind] == 0 && cloudCurvature[ind] > edgeThreshold)
  194. {
  195. // 每段只取20个角点,如果单条扫描线扫描一周是1800个点,则划分6段,每段300个点,从中提取20个角点
  196. largestPickedNum++;
  197. if (largestPickedNum <= 20){
  198. // 标记为角点,加入角点点云
  199. cloudLabel[ind] = 1;
  200. cornerCloud->push_back(extractedCloud->points[ind]);
  201. } else {
  202. break;
  203. }
  204. // 标记已被处理
  205. cloudNeighborPicked[ind] = 1;
  206. // 同一条扫描线上后5个点标记一下,不再处理,避免特征聚集
  207. for (int l = 1; l <= 5; l++)
  208. {
  209. int columnDiff = std::abs(int(cloudInfo.pointColInd[ind + l] - cloudInfo.pointColInd[ind + l - 1]));
  210. //大于10,说明距离远,则不作标记
  211. if (columnDiff > 10)
  212. break;
  213. cloudNeighborPicked[ind + l] = 1;
  214. }
  215. // 同一条扫描线上前5个点标记一下,不再处理,避免特征聚集
  216. for (int l = -1; l >= -5; l—)
  217. {
  218. int columnDiff = std::abs(int(cloudInfo.pointColInd[ind + l] - cloudInfo.pointColInd[ind + l + 1]));
  219. if (columnDiff > 10)
  220. break;
  221. cloudNeighborPicked[ind + l] = 1;
  222. }
  223. }
  224. }
  225. // 按照曲率从小到大遍历
  226. for (int k = sp; k <= ep; k++)
  227. {
  228. // 激光点的索引
  229. int ind = cloudSmoothness[k].ind;
  230. // 当前激光点还未被处理,且曲率小于阈值,则认为是平面点
  231. if (cloudNeighborPicked[ind] == 0 && cloudCurvature[ind] < surfThreshold)
  232. {
  233. // 标记为平面点
  234. cloudLabel[ind] = -1;
  235. // 标记已被处理
  236. cloudNeighborPicked[ind] = 1;
  237. // 同一条扫描线上后5个点标记一下,不再处理,避免特征聚集
  238. for (int l = 1; l <= 5; l++) {
  239. int columnDiff = std::abs(int(cloudInfo.pointColInd[ind + l] - cloudInfo.pointColInd[ind + l - 1]));
  240. if (columnDiff > 10)
  241. break;
  242. cloudNeighborPicked[ind + l] = 1;
  243. }
  244. // 同一条扫描线上前5个点标记一下,不再处理,避免特征聚集
  245. for (int l = -1; l >= -5; l—) {
  246. int columnDiff = std::abs(int(cloudInfo.pointColInd[ind + l] - cloudInfo.pointColInd[ind + l + 1]));
  247. if (columnDiff > 10)
  248. break;
  249. cloudNeighborPicked[ind + l] = 1;
  250. }
  251. }
  252. }
  253. // 平面点和未被处理的点(<=0),都认为是平面点,加入平面点云集合
  254. for (int k = sp; k <= ep; k++)
  255. {
  256. if (cloudLabel[k] <= 0){
  257. surfaceCloudScan->push_back(extractedCloud->points[k]);
  258. }
  259. }
  260. }
  261. // 平面点云降采样
  262. surfaceCloudScanDS->clear();
  263. downSizeFilter.setInputCloud(surfaceCloudScan);
  264. downSizeFilter.filter(_surfaceCloudScanDS);
  265. // 加入平面点云集合
  266. _surfaceCloud += _surfaceCloudScanDS;
  267. //用surfaceCloudScan来装数据,然后放到downSizeFilter里,
  268. //再用downSizeFilter进行.filter()操作,把结果输出到_surfaceCloudScanDS里。
  269. //最后把DS装到surfaceCloud中。DS指的是DownSample。
  270. //同样角点(边缘点)则没有这样的操作,直接就用cornerCloud来装点云。
  271. }
  272. }
  273. /**
  274. _ 清理
  275. _/
  276. void freeCloudInfoMemory()
  277. {
  278. cloudInfo.startRingIndex.clear();
  279. cloudInfo.endRingIndex.clear();
  280. cloudInfo.pointColInd.clear();
  281. cloudInfo.pointRange.clear();
  282. }
  283. /**
  284. _ 发布角点、面点点云,发布带特征点云数据的当前激光帧点云信息
  285. _/
  286. void publishFeatureCloud()
  287. {
  288. // free cloud info memory
  289. freeCloudInfoMemory();
  290. // save newly extracted features
  291. // 发布角点、面点点云,用于rviz展示
  292. cloudInfo.cloud_corner = publishCloud(&pubCornerPoints, cornerCloud, cloudHeader.stamp, lidarFrame);
  293. cloudInfo.cloud_surface = publishCloud(&pubSurfacePoints, surfaceCloud, cloudHeader.stamp, lidarFrame);
  294. // publish to mapOptimization
  295. // 发布当前激光帧点云信息,加入了角点、面点点云数据,发布给mapOptimization
  296. // 和imageProjection.cpp发布的不是同一个话题,
  297. // image发布的是”lio_sam/deskew/cloud_info”,
  298. // 这里发布的是”lio_sam/feature/cloud_info”,
  299. // 因此不用担心地图优化部分的冲突
  300. pubLaserCloudInfo.publish(cloudInfo);
  301. }
  302. };
  303. int main(int argc, char** argv)
  304. {
  305. ros::init(argc, argv, “lio_sam”);
  306. FeatureExtraction FE;
  307. ROS_INFO(“\033[1;32m——> Feature Extraction Started.\033[0m”);
  308. ros::spin();
  309. return 0;
  310. }



总结


这个cpp原理比较简单,就是订阅刚刚在imageProjection.cpp总结中的3.5部分中发布的lio_sam/deskew/cloud_info消息,然后提取边缘点(角点),平面点,然后填充cloud_info的cloud_corner和cloud_surface字段,重新以”lio_sam/feature/cloud_info”的形式发布出去。


1.calculateSmoothness,计算当前激光帧点云中每个点的曲率,比较简单不详细说了。


2.markOccludedPoints,标记被遮挡的点。



这点还是可以说一下,第一个,在cloudinfo中,pointCollnd记录的是当前点在原始扫瞄线图像中的列值,列值在10以内,即2度范围内(10_360/1800),两点之间深度差0.3m,就不考虑这种点;第二,当前点左右的有效点的距离和它比都太大了,那么不要这个点。


 3.extractFeatures:


对每条线上大曲率进行排序,每条线分为6段,每段最多提取20个。大于阈值就是角点(默认0.1),并且标记该点周围其他点已经被提取了。小于阈值同理,当成平面点。不过平面点要经过一个降采样过程(角点不用,可能是平面点比较多)。角点以”lio_sam/feature/cloud_corner”发布,平面点以”lio_sam/feature/cloud_surface”发布,然后把二者合在一起,在lio_sam/deskew/cloud_info的基础上,填充cloud_corner和cloud_surface字段,重新以”lio_sam/feature/cloud_info”的形式发布出去。(注意名字不一样了,同样是cloud_info,只不过deskew/cloud_info是imageProjection.cpp发布的,feature/cloud_info是featureExtraction.cpp发布的,后者比前者多了角点和平面点字段。deskew/cloud_info在此之后就算寿终正寝了,没有其他的进程需要监听它了。)




imuPreintergration.cpp


注释


  1. #include “utility.h”
  2. #include <gtsam/geometry/Rot3.h>
  3. #include <gtsam/geometry/Pose3.h>
  4. #include <gtsam/slam/PriorFactor.h>
  5. #include <gtsam/slam/BetweenFactor.h>
  6. #include <gtsam/navigation/GPSFactor.h>
  7. #include <gtsam/navigation/ImuFactor.h>
  8. #include <gtsam/navigation/CombinedImuFactor.h>
  9. #include <gtsam/nonlinear/NonlinearFactorGraph.h>
  10. #include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
  11. #include <gtsam/nonlinear/Marginals.h>
  12. #include <gtsam/nonlinear/Values.h>
  13. #include <gtsam/inference/Symbol.h>
  14. #include <gtsam/nonlinear/ISAM2.h>
  15. #include <gtsam_unstable/nonlinear/IncrementalFixedLagSmoother.h>
  16. using gtsam::symbol_shorthand::X; // Pose3 (x,y,z,r,p,y)
  17. using gtsam::symbol_shorthand::V; // Vel (xdot,ydot,zdot)
  18. using gtsam::symbol_shorthand::B; // Bias (ax,ay,az,gx,gy,gz)
  19. // 订阅激光里程计(来自MapOptimization)和IMU里程计,
  20. //根据前一时刻激光里程计,和该时刻到当前时刻的IMU里程计变换增量,
  21. //计算当前时刻IMU里程计;
  22. //rviz展示IMU里程计轨迹(局部)。
  23. class <span class=”hljs-title class_“>TransformFusion : public ParamServer
  24. {
  25. public:
  26. std::mutex mtx;
  27. ros::Subscriber subImuOdometry;
  28. ros::Subscriber subLaserOdometry;
  29. ros::Publisher pubImuOdometry;
  30. ros::Publisher pubImuPath;
  31. Eigen::Affine3f lidarOdomAffine;
  32. Eigen::Affine3f imuOdomAffineFront;
  33. Eigen::Affine3f imuOdomAffineBack;
  34. tf::TransformListener tfListener;
  35. tf::StampedTransform lidar2Baselink;
  36. double lidarOdomTime = -1;
  37. deque<nav_msgs::Odometry> imuOdomQueue;
  38. TransformFusion()
  39. {
  40. // 如果lidar系与baselink系不同(激光系和载体系),需要外部提供二者之间的变换关系
  41. if(lidarFrame != baselinkFrame)
  42. {
  43. try
  44. {
  45. // 等待3s
  46. tfListener.waitForTransform(lidarFrame, baselinkFrame, ros::Time(0), ros::Duration(3.0));
  47. // lidar系到baselink系的变换
  48. tfListener.lookupTransform(lidarFrame, baselinkFrame, ros::Time(0), lidar2Baselink);
  49. }
  50. catch (tf::TransformException ex)
  51. {
  52. ROS_ERROR(“%s”,ex.what());
  53. }
  54. }
  55. // 订阅激光里程计,来自mapOptimization
  56. subLaserOdometry = nh.subscribe<nav_msgs::Odometry>(“lio_sam/mapping/odometry”, 5, &TransformFusion::lidarOdometryHandler, this, ros::TransportHints().tcpNoDelay());
  57. // 订阅imu里程计,来自IMUPreintegration(IMUPreintegration.cpp中的类IMUPreintegration)
  58. //topic name: odometry/imu_incremental
  59. //注意区分lio_sam/mapping/odometry_incremental
  60. //目前可以明确的一点,odometry/imu_incremental是增量内容,即两帧激光里程计之间的预积分内容,(加上开始的激光里程计本身有的位姿)
  61. //imuIntegratorImu_本身是个积分器,只有两帧之间的预积分,但是发布的时候发布的实际是结合了前述里程计本身有的位姿
  62. //如这个predict里的prevStateOdom:
  63. //currentState = imuIntegratorImu_->predict(prevStateOdom, prevBiasOdom);
  64. subImuOdometry = nh.subscribe<nav_msgs::Odometry>(odomTopic+“_incremental”, 2000, &TransformFusion::imuOdometryHandler, this, ros::TransportHints().tcpNoDelay());
  65. // 发布imu里程计,用于rviz展示
  66. pubImuOdometry = nh.advertise<nav_msgs::Odometry>(odomTopic, 2000);
  67. // 发布imu里程计轨迹
  68. pubImuPath = nh.advertise<nav_msgs::Path> (“lio_sam/imu/path”, 1);
  69. }
  70. /
  71. _ 里程计对应变换矩阵
  72. _/
  73. Eigen::Affine3f odom2affine(nav_msgs::Odometry odom)
  74. {
  75. double x, y, z, roll, pitch, yaw;
  76. x = odom.pose.pose.position.x;
  77. y = odom.pose.pose.position.y;
  78. z = odom.pose.pose.position.z;
  79. tf::Quaternion orientation;
  80. tf::quaternionMsgToTF(odom.pose.pose.orientation, orientation);
  81. tf::Matrix3x3(orientation).getRPY(roll, pitch, yaw);
  82. return pcl::getTransformation(x, y, z, roll, pitch, yaw);
  83. }
  84. /
  85. _ 订阅激光里程计的回调函数,来自mapOptimization
  86. _/
  87. void lidarOdometryHandler(const nav_msgs::Odometry::ConstPtr& odomMsg)
  88. {
  89. std::lock_guard<std::mutex> lock(mtx);
  90. // 激光里程计对应变换矩阵
  91. lidarOdomAffine = odom2affine(_odomMsg);
  92. // 激光里程计时间戳
  93. lidarOdomTime = odomMsg->header.stamp.toSec();
  94. //这二者里面保存的都是最近的一个雷达激光里程计的变换和时间戳(不再是用一个vector之类的东西保存起来)
  95. }
  96. /**
  97. _ 订阅imu里程计,来自IMUPreintegration
  98. _ 1、以最近一帧激光里程计位姿为基础,计算该时刻与当前时刻间imu里程计增量位姿变换,相乘得到当前时刻imu里程计位姿
  99. _ 2、发布当前时刻里程计位姿,用于rviz展示;发布imu里程计路径,注:只是最近一帧激光里程计时刻与当前时刻之间的一段
  100. _/
  101. void imuOdometryHandler(const nav_msgs::Odometry::ConstPtr& odomMsg)
  102. {
  103. // 发布tf,map与odom系设为同一个系
  104. static tf::TransformBroadcaster tfMap2Odom;
  105. static tf::Transform map_to_odom = tf::Transform(tf::createQuaternionFromRPY(0, 0, 0), tf::Vector3(0, 0, 0));
  106. tfMap2Odom.sendTransform(tf::StampedTransform(map_to_odom, odomMsg->header.stamp, mapFrame, odometryFrame));
  107. std::lock_guard<std::mutex> lock(mtx);
  108. // 添加imu里程计到队列,注:imu里程计由本cpp中的另一个类imuPreintegration来发布
  109. imuOdomQueue.push_back(_odomMsg);
  110. // get latest odometry (at current IMU stamp)
  111. // 从imu里程计队列中删除当前(最近的一帧)激光里程计时刻之前的数据
  112. // lidarOdomTime初始化为-1,在收到lidar里程计数据后,在回调函数lidarOdometryHandler中被赋值时间戳
  113. if (lidarOdomTime == -1)
  114. return;
  115. while (!imuOdomQueue.empty())
  116. {
  117. if (imuOdomQueue.front().header.stamp.toSec() <= lidarOdomTime)
  118. imuOdomQueue.pop_front();
  119. else
  120. break;
  121. }
  122. // 最近的一帧激光里程计时刻对应imu里程计位姿
  123. Eigen::Affine3f imuOdomAffineFront = odom2affine(imuOdomQueue.front());
  124. // 当前时刻imu里程计位姿
  125. Eigen::Affine3f imuOdomAffineBack = odom2affine(imuOdomQueue.back());
  126. // imu里程计增量位姿变换
  127. Eigen::Affine3f imuOdomAffineIncre = imuOdomAffineFront.inverse() _ imuOdomAffineBack;
  128. // 当前时刻imu里程计位姿=最近的一帧激光里程计位姿 _ imu里程计增量位姿变换
  129. //lidarOdomAffine在本类的lidarOdometryHandler回调函数中被赋值,消息来源于mapOptimization.cpp发布,是激光里程计
  130. Eigen::Affine3f imuOdomAffineLast = lidarOdomAffine _ imuOdomAffineIncre;
  131. float x, y, z, roll, pitch, yaw;
  132. pcl::getTranslationAndEulerAngles(imuOdomAffineLast, x, y, z, roll, pitch, yaw);
  133. // publish latest odometry
  134. //发布名为”odometry/imu”的话题
  135. //也就是说,这个函数先监听了类IMUPreintegration中发布的odometry/imu_incremental,
  136. //然后计算imu二者之间的增量,然后在激光的基础上加上增量,重新发布
  137. //可以看出发布的并非odometry/imu_incremental的一部分子数据,而是把x,y,z,roll,pitch,yaw都经过了激光里程计的修正,才发布
  138. //可以看出这次发布的内容,是当前时刻里程计位姿.发布名称为”odometry/imu”
  139. nav_msgs::Odometry laserOdometry = imuOdomQueue.back();
  140. laserOdometry.pose.pose.position.x = x; //赋上新的值
  141. laserOdometry.pose.pose.position.y = y;
  142. laserOdometry.pose.pose.position.z = z;
  143. laserOdometry.pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);
  144. pubImuOdometry.publish(laserOdometry);
  145. // 发布tf,当前时刻odom与baselink系变换关系
  146. //由于之前把map和odom坐标系固定了,因此这里我认为发布的就是真正的最终位姿关系
  147. //map优化提供激光,预积分提供imu,imu之间变换再乘以激光里程计得到各个时刻精确位姿
  148. static tf::TransformBroadcaster tfOdom2BaseLink;
  149. tf::Transform tCur;
  150. tf::poseMsgToTF(laserOdometry.pose.pose, tCur);
  151. if(lidarFrame != baselinkFrame)
  152. tCur = tCur _ lidar2Baselink;
  153. tf::StampedTransform odom_2_baselink = tf::StampedTransform(tCur, odomMsg->header.stamp, odometryFrame, baselinkFrame);
  154. tfOdom2BaseLink.sendTransform(odom_2_baselink);
  155. // publish IMU path
  156. // 发布imu里程计路径,注:只是最近一帧激光里程计时刻与当前时刻之间的一段
  157. static nav_msgs::Path imuPath;
  158. static double last_path_time = -1;
  159. double imuTime = imuOdomQueue.back().header.stamp.toSec();
  160. // 每隔0.1s添加一个
  161. if (imuTime - last_path_time > 0.1)
  162. {
  163. last_path_time = imuTime;
  164. geometry_msgs::PoseStamped pose_stamped;
  165. pose_stamped.header.stamp = imuOdomQueue.back().header.stamp;
  166. pose_stamped.header.frame_id = odometryFrame; //就叫”odom”
  167. pose_stamped.pose = laserOdometry.pose.pose;
  168. imuPath.poses.push_back(pose_stamped);
  169. // 删除最近一帧激光里程计时刻之前的imu里程计
  170. while(!imuPath.poses.empty() && imuPath.poses.front().header.stamp.toSec() < lidarOdomTime - 1.0)
  171. imuPath.poses.erase(imuPath.poses.begin());
  172. if (pubImuPath.getNumSubscribers() != 0)
  173. {
  174. imuPath.header.stamp = imuOdomQueue.back().header.stamp;
  175. imuPath.header.frame_id = odometryFrame;
  176. pubImuPath.publish(imuPath);
  177. }
  178. }
  179. }
  180. };
  181. class <span class=”hljs-title class_“>IMUPreintegration : public ParamServer
  182. {
  183. public:
  184. std::mutex mtx;
  185. ros::Subscriber subImu;
  186. ros::Subscriber subOdometry;
  187. ros::Publisher pubImuOdometry;
  188. bool systemInitialized = false;
  189. // 噪声协方差
  190. gtsam::noiseModel::Diagonal::shared_ptr priorPoseNoise;
  191. gtsam::noiseModel::Diagonal::shared_ptr priorVelNoise;
  192. gtsam::noiseModel::Diagonal::shared_ptr priorBiasNoise;
  193. gtsam::noiseModel::Diagonal::shared_ptr correctionNoise;
  194. gtsam::noiseModel::Diagonal::shared_ptr correctionNoise2;
  195. gtsam::Vector noiseModelBetweenBias;
  196. // imu预积分器
  197. //imuIntegratorOpt_负责预积分两个激光里程计之间的imu数据,作为约束加入因子图,并且优化出bias
  198. gtsam::PreintegratedImuMeasurements _imuIntegratorOpt_;
  199. //imuIntegratorImu_用来根据新的激光里程计到达后已经优化好的bias,预测从当前帧开始,下一帧激光里程计到达之前的imu里程计增量
  200. gtsam::PreintegratedImuMeasurements _imuIntegratorImu_;
  201. // imu数据队列
  202. //imuQueOpt用来给imuIntegratorOpt_提供数据来源,不要的就弹出(从队头开始出发,比当前激光里程计数据早的imu通通积分,用一个扔一个);
  203. std::deque<sensor_msgs::Imu> imuQueOpt;
  204. //imuQueImu用来给imuIntegratorImu_提供数据来源,不要的就弹出(弹出当前激光里程计之前的imu数据,预积分用完一个弹一个);
  205. std::deque<sensor_msgs::Imu> imuQueImu;
  206. // imu因子图优化过程中的状态变量
  207. gtsam::Pose3 prevPose_;
  208. gtsam::Vector3 prevVel_;
  209. gtsam::NavState prevState_;
  210. gtsam::imuBias::ConstantBias prevBias_;
  211. // imu状态
  212. gtsam::NavState prevStateOdom;
  213. gtsam::imuBias::ConstantBias prevBiasOdom;
  214. bool doneFirstOpt = false;
  215. double lastImuT_imu = -1;
  216. double lastImuT_opt = -1;
  217. // ISAM2优化器
  218. gtsam::ISAM2 optimizer;
  219. gtsam::NonlinearFactorGraph graphFactors; //总的因子图模型
  220. gtsam::Values graphValues; //因子图模型中的值
  221. const double delta_t = 0;
  222. int key = 1;
  223. // imu-lidar位姿变换
  224. //这点要注意,tixiaoshan这里命名的很垃圾,这只是一个平移变换,
  225. //同样头文件的imuConverter中,也只有一个旋转变换。这里绝对不可以理解为把imu数据转到lidar下的变换矩阵。
  226. //事实上,作者后续是把imu数据先用imuConverter旋转到雷达系下(但其实还差了个平移)。
  227. //作者真正是把雷达数据又根据lidar2Imu反向平移了一下,和转换以后差了个平移的imu数据在“中间系”对齐,
  228. //之后算完又从中间系通过imu2Lidar挪回了雷达系进行publish。
  229. gtsam::Pose3 imu2Lidar = gtsam::Pose3(gtsam::Rot3(1, 0, 0, 0), gtsam::Point3(-extTrans.x(), -extTrans.y(), -extTrans.z()));
  230. gtsam::Pose3 lidar2Imu = gtsam::Pose3(gtsam::Rot3(1, 0, 0, 0), gtsam::Point3(extTrans.x(), extTrans.y(), extTrans.z()));
  231. IMUPreintegration()
  232. {
  233. //订阅imu原始数据,用下面因子图优化的结果,施加两帧之间的imu预计分量,预测每一时刻(imu频率)的imu里程计
  234. //imuTopic name: “imu_correct”
  235. subImu = nh.subscribe<sensor_msgs::Imu> (imuTopic, 2000, &IMUPreintegration::imuHandler, this, ros::TransportHints().tcpNoDelay());
  236. // 订阅激光里程计,来自mapOptimization,用两帧之间的imu预计分量构建因子图,
  237. // 优化当前帧位姿(这个位姿仅用于更新每时刻的imu里程计,以及下一次因子图优化)
  238. subOdometry = nh.subscribe<nav_msgs::Odometry>(“lio_sam/mapping/odometry_incremental”, 5, &IMUPreintegration::odometryHandler, this, ros::TransportHints().tcpNoDelay());
  239. //发布imu里程计: odometry/imu_incremental
  240. pubImuOdometry = nh.advertise<nav_msgs::Odometry> (odomTopic+“_incremental”, 2000);
  241. // imu预积分的噪声协方差
  242. boost::shared_ptr<gtsam::PreintegrationParams> p = gtsam::PreintegrationParams::MakeSharedU(imuGravity);
  243. //imuAccNoise和imuGyrNoise都是定义在头文件中的高斯白噪声,由配置文件中写入
  244. p->accelerometerCovariance = gtsam::Matrix33::Identity(3,3) _ pow(imuAccNoise, 2); // acc white noise in continuous
  245. p->gyroscopeCovariance = gtsam::Matrix33::Identity(3,3) _ pow(imuGyrNoise, 2); // gyro white noise in continuous
  246. //对于速度的积分误差?这块暂时不太理解
  247. p->integrationCovariance = gtsam::Matrix33::Identity(3,3) * pow(1e-4, 2); // error committed in integrating position from velocities
  248. //假设没有初始的bias
  249. gtsam::imuBias::ConstantBias prior_imu_bias((gtsam::Vector(6) << 0, 0, 0, 0, 0, 0).finished());; // assume zero initial bias
  250. // 噪声先验
  251. //Diagonal对角线矩阵
  252. //发现diagonal型一般调用.finished(),注释中说finished()意为设置完所有系数后返回构建的矩阵
  253. priorPoseNoise = gtsam::noiseModel::Diagonal::Sigmas((gtsam::Vector(6) << 1e-2, 1e-2, 1e-2, 1e-2, 1e-2, 1e-2).finished()); // rad,rad,rad,m, m, m
  254. priorVelNoise = gtsam::noiseModel::Isotropic::Sigma(3, 1e4); // m/s
  255. priorBiasNoise = gtsam::noiseModel::Isotropic::Sigma(6, 1e-3); // 1e-2 ~ 1e-3 seems to be good
  256. // 激光里程计scan-to-map优化过程中发生退化,则选择一个较大的协方差
  257. correctionNoise = gtsam::noiseModel::Diagonal::Sigmas((gtsam::Vector(6) << 0.05, 0.05, 0.05, 0.1, 0.1, 0.1).finished()); // rad,rad,rad,m, m, m
  258. correctionNoise2 = gtsam::noiseModel::Diagonal::Sigmas((gtsam::Vector(6) << 1, 1, 1, 1, 1, 1).finished()); // rad,rad,rad,m, m, m
  259. noiseModelBetweenBias = (gtsam::Vector(6) << imuAccBiasN, imuAccBiasN, imuAccBiasN, imuGyrBiasN, imuGyrBiasN, imuGyrBiasN).finished();
  260. //imu预积分器,用于预测每一时刻(imu频率)的imu里程计(转到lidar系了,与激光里程计同一个系)
  261. imuIntegratorImu_ = new gtsam::PreintegratedImuMeasurements(p, prior_imu_bias); // setting up the IMU integration for IMU message thread
  262. //imu预积分器,用于因子图优化
  263. imuIntegratorOpt_ = new gtsam::PreintegratedImuMeasurements(p, prior_imu_bias); // setting up the IMU integration for optimization
  264. }
  265. void resetOptimization()
  266. {
  267. gtsam::ISAM2Params optParameters;
  268. optParameters.relinearizeThreshold = 0.1;
  269. optParameters.relinearizeSkip = 1;
  270. optimizer = gtsam::ISAM2(optParameters);
  271. gtsam::NonlinearFactorGraph newGraphFactors;
  272. graphFactors = newGraphFactors;
  273. gtsam::Values NewGraphValues;
  274. graphValues = NewGraphValues;
  275. }
  276. void resetParams()
  277. {
  278. lastImuT_imu = -1;
  279. doneFirstOpt = false;
  280. systemInitialized = false;
  281. }
  282. // 订阅的是激光里程计,”lio_sam/mapping/odometry_incremental”
  283. void odometryHandler(const nav_msgs::Odometry::ConstPtr& odomMsg)
  284. {
  285. std::lock_guard<std::mutex> lock(mtx);
  286. // 当前帧激光里程计时间戳
  287. double currentCorrectionTime = ROS_TIME(odomMsg);
  288. // 确保imu优化队列中有imu数据进行预积分
  289. if (imuQueOpt.empty())
  290. return;
  291. // 当前帧激光位姿,来自scan-to-map匹配、因子图优化后的位姿
  292. float p_x = odomMsg->pose.pose.position.x;
  293. float p_y = odomMsg->pose.pose.position.y;
  294. float p_z = odomMsg->pose.pose.position.z;
  295. float r_x = odomMsg->pose.pose.orientation.x;
  296. float r_y = odomMsg->pose.pose.orientation.y;
  297. float r_z = odomMsg->pose.pose.orientation.z;
  298. float r_w = odomMsg->pose.pose.orientation.w;
  299. bool degenerate = (int)odomMsg->pose.covariance[0] == 1 ? true : false;
  300. gtsam::Pose3 lidarPose = gtsam::Pose3(gtsam::Rot3::Quaternion(r_w, r_x, r_y, r_z), gtsam::Point3(p_x, p_y, p_z));
  301. // 0. initialize system
  302. // 0. 系统初始化,第一帧
  303. if (systemInitialized == false)
  304. {
  305. // 重置ISAM2优化器
  306. resetOptimization();
  307. // pop old IMU message
  308. // 从imu优化队列中删除当前帧激光里程计时刻之前的imu数据,delta_t=0
  309. while (!imuQueOpt.empty())
  310. {
  311. if (ROS_TIME(&imuQueOpt.front()) < currentCorrectionTime - delta_t)
  312. {
  313. lastImuT_opt = ROS_TIME(&imuQueOpt.front());
  314. imuQueOpt.pop_front();
  315. }
  316. else
  317. break;
  318. }
  319. // initial pose
  320. // 添加里程计位姿先验因子
  321. //lidarPose 为本回调函数收到的激光里程计数据,重组成gtsam的pose格式
  322. //并转到imu坐标系下,我猜测compose可能类似于左乘之类的含义吧
  323. prevPose_ = lidarPose.compose(lidar2Imu);
  324. //X可能是固定搭配(当使用Pose时),如果是速度则是V,bias则是B
  325. gtsam::PriorFactor<gtsam::Pose3> priorPose(X(0), prevPose_, priorPoseNoise);
  326. //通过调用总的因子图模型的add方式,添加第一个因子
  327. //PriorFactor 概念可看gtsam 包括了位姿 速度 bias
  328. //加入PriorFactor在图优化中基本都是必需的前提
  329. //各种noise都定义在构造函数当中
  330. graphFactors.add(priorPose);
  331. // initial velocity
  332. prevVel_ = gtsam::Vector3(0, 0, 0);
  333. gtsam::PriorFactor<gtsam::Vector3> priorVel(V(0), prevVel_, priorVelNoise);
  334. graphFactors.add(priorVel);
  335. // initial bias
  336. prevBias_ = gtsam::imuBias::ConstantBias();
  337. gtsam::PriorFactor<gtsam::imuBias::ConstantBias> priorBias(B(0), prevBias_, priorBiasNoise);
  338. graphFactors.add(priorBias);
  339. // add values
  340. // 变量节点赋初值
  341. graphValues.insert(X(0), prevPose_);
  342. graphValues.insert(V(0), prevVel_);
  343. graphValues.insert(B(0), prevBias_);
  344. // optimize once
  345. // 优化一次
  346. optimizer.update(graphFactors, graphValues);
  347. //图和节点均清零 为什么要清零不能继续用吗?
  348. //是因为节点信息保存在gtsam::ISAM2 optimizer,所以要清理后才能继续使用
  349. graphFactors.resize(0);
  350. graphValues.clear();
  351. //积分器重置,重置优化之后的偏置
  352. imuIntegratorImu_->resetIntegrationAndSetBias(prevBias_);
  353. imuIntegratorOpt_->resetIntegrationAndSetBias(prevBias_);
  354. key = 1;
  355. systemInitialized = true;
  356. return;
  357. }
  358. // reset graph for speed
  359. // 每隔100帧激光里程计,重置ISAM2优化器,保证优化效率
  360. if (key == 100)
  361. {
  362. // get updated noise before reset
  363. // 前一帧的位姿、速度、偏置噪声模型
  364. //保存最后的噪声值
  365. gtsam::noiseModel::Gaussian::shared_ptr updatedPoseNoise = gtsam::noiseModel::Gaussian::Covariance(optimizer.marginalCovariance(X(key-1)));
  366. gtsam::noiseModel::Gaussian::shared_ptr updatedVelNoise = gtsam::noiseModel::Gaussian::Covariance(optimizer.marginalCovariance(V(key-1)));
  367. gtsam::noiseModel::Gaussian::shared_ptr updatedBiasNoise = gtsam::noiseModel::Gaussian::Covariance(optimizer.marginalCovariance(B(key-1)));
  368. // reset graph
  369. // 重置ISAM2优化器
  370. resetOptimization();
  371. // add pose
  372. // 添加位姿先验因子,用前一帧的值初始化
  373. //重置之后还有类似与初始化的过程 区别在于噪声值不同
  374. //prevPose_等三项,也是上一时刻得到的,
  375. //(初始时刻是lidar里程计的pose直接用lidar2IMU变量转到imu坐标系下,而此处则是通过上一时刻,即接下来的后续优化中得到)
  376. gtsam::PriorFactor<gtsam::Pose3> priorPose(X(0), prevPose_, updatedPoseNoise);
  377. graphFactors.add(priorPose);
  378. // add velocity
  379. gtsam::PriorFactor<gtsam::Vector3> priorVel(V(0), prevVel_, updatedVelNoise);
  380. graphFactors.add(priorVel);
  381. // add bias
  382. gtsam::PriorFactor<gtsam::imuBias::ConstantBias> priorBias(B(0), prevBias_, updatedBiasNoise);
  383. graphFactors.add(priorBias);
  384. // add values
  385. graphValues.insert(X(0), prevPose_);
  386. graphValues.insert(V(0), prevVel_);
  387. graphValues.insert(B(0), prevBias_);
  388. // optimize once
  389. optimizer.update(graphFactors, graphValues);
  390. graphFactors.resize(0);
  391. graphValues.clear();
  392. key = 1;
  393. }
  394. // 1. integrate imu data and optimize
  395. // 1. 计算前一帧与当前帧之间的imu预积分量,用前一帧状态施加预积分量得到当前帧初始状态估计,
  396. // 添加来自mapOptimization的当前帧位姿,进行因子图优化,更新当前帧状态
  397. while (!imuQueOpt.empty())
  398. {
  399. // pop and integrate imu data that is between two optimizations
  400. // 提取前一帧与当前帧之间的imu数据,计算预积分
  401. sensor_msgs::Imu *thisImu = &imuQueOpt.front();
  402. double imuTime = ROS_TIME(thisImu);
  403. //currentCorrectionTime是当前回调函数收到的激光里程计数据的时间
  404. if (imuTime < currentCorrectionTime - delta_t)
  405. {
  406. double dt = (lastImuT_opt < 0) ? (1.0 / 500.0) : (imuTime - lastImuT_opt);
  407. // imu预积分数据输入:加速度、角速度、dt
  408. // 加入的是这个用来因子图优化的预积分器imuIntegratorOpt_,注意加入了上一步算出的dt
  409. //作者要求的9轴imu数据中欧拉角在本程序文件中没有任何用到,全在地图优化里用到的
  410. imuIntegratorOpt_->integrateMeasurement(
  411. gtsam::Vector3(thisImu->linear_acceleration.x, thisImu->linear_acceleration.y, thisImu->linear_acceleration.z),
  412. gtsam::Vector3(thisImu->angular_velocity.x, thisImu->angular_velocity.y, thisImu->angular_velocity.z), dt);
  413. //在推出一次数据前保存上一个数据的时间戳
  414. lastImuT_opt = imuTime;
  415. // 从队列中删除已经处理的imu数据
  416. imuQueOpt.pop_front();
  417. }
  418. else
  419. break;
  420. }
  421. // add imu factor to graph
  422. //利用两帧之间的IMU数据完成了预积分后增加imu因子到因子图中,
  423. //注意后面容易被遮挡,imuIntegratorOpt_的值经过格式转换被传入preint_imu,
  424. //因此可以推测imuIntegratorOpt_中的integrateMeasurement函数应该就是一个简单的积分轮子,
  425. //传入数据和dt,得到一个积分量,数据会被存放在imuIntegratorOpt_中
  426. const gtsam::PreintegratedImuMeasurements& preint_imu = dynamic_cast<const gtsam::PreintegratedImuMeasurements&>(*imuIntegratorOpt_);
  427. // 参数:前一帧位姿,前一帧速度,当前帧位姿,当前帧速度,前一帧偏置,预计分量
  428. gtsam::ImuFactor imu_factor(X(key - 1), V(key - 1), X(key), V(key), B(key - 1), preint_imu);
  429. graphFactors.add(imu_factor);
  430. // add imu bias between factor
  431. // 添加imu偏置因子,前一帧偏置B(key - 1),当前帧偏置B(key),观测值,噪声协方差;deltaTij()是积分段的时间
  432. graphFactors.add(gtsam::BetweenFactor<gtsam::imuBias::ConstantBias>(B(key - 1), B(key), gtsam::imuBias::ConstantBias(),
  433. gtsam::noiseModel::Diagonal::Sigmas(sqrt(imuIntegratorOpt_->deltaTij()) _ noiseModelBetweenBias)));
  434. // add pose factor
  435. // 添加位姿因子
  436. gtsam::Pose3 curPose = lidarPose.compose(lidar2Imu);
  437. gtsam::PriorFactor<gtsam::Pose3> pose_factor(X(key), curPose, degenerate ? correctionNoise2 : correctionNoise);
  438. graphFactors.add(pose_factor);
  439. // insert predicted values
  440. // 用前一帧的状态、偏置,施加imu预计分量,得到当前帧的状态
  441. gtsam::NavState propState_ = imuIntegratorOpt_->predict(prevState_, prevBias_);
  442. // 变量节点赋初值
  443. graphValues.insert(X(key), propState_.pose());
  444. graphValues.insert(V(key), propState_.v());
  445. graphValues.insert(B(key), prevBias_);
  446. // optimize
  447. optimizer.update(graphFactors, graphValues);
  448. optimizer.update();
  449. graphFactors.resize(0);
  450. graphValues.clear();
  451. // Overwrite the beginning of the preintegration for the next step.
  452. // 优化结果
  453. gtsam::Values result = optimizer.calculateEstimate();
  454. // 更新当前帧位姿、速度
  455. prevPose_ = result.at<gtsam::Pose3>(X(key));
  456. prevVel_ = result.at<gtsam::Vector3>(V(key));
  457. // 更新当前帧状态
  458. prevState_ = gtsam::NavState(prevPose_, prevVel_);
  459. // 更新当前帧imu偏置
  460. prevBias_ = result.at<gtsam::imuBias::ConstantBias>(B(key));
  461. // Reset the optimization preintegration object.
  462. //重置预积分器,设置新的偏置,这样下一帧激光里程计进来的时候,预积分量就是两帧之间的增量
  463. imuIntegratorOpt_->resetIntegrationAndSetBias(prevBias_);
  464. // check optimization
  465. // imu因子图优化结果,速度或者偏置过大,认为失败
  466. if (failureDetection(prevVel_, prevBias_))
  467. {
  468. resetParams();
  469. return;
  470. }
  471. // 2. after optiization, re-propagate imu odometry preintegration
  472. // 2. 优化之后,执行重传播;优化更新了imu的偏置,
  473. //用最新的偏置重新计算当前激光里程计时刻之后的imu预积分,这个预积分用于计算每时刻位姿
  474. prevStateOdom = prevState_;
  475. prevBiasOdom = prevBias_;
  476. // first pop imu message older than current correction data
  477. // 从imu队列中删除当前激光里程计时刻之前的imu数据
  478. double lastImuQT = -1;
  479. //注意,这里是要“删除”当前帧“之前”的imu数据,是想根据当前帧“之后”的累积递推。
  480. //而前面imuIntegratorOpt_做的事情是,“提取”当前帧“之前”的imu数据,用两帧之间的imu数据进行积分。处理过的就弹出来。
  481. //因此,新到一帧激光帧里程计数据时,imuQueOpt队列变化如下:
  482. //当前帧之前的数据被提出来做积分,用一个删一个(这样下一帧到达后,队列中就不会有现在这帧之前的数据了)
  483. //那么在更新完以后,imuQueOpt队列不再变化,剩下的原始imu数据用作下一次优化时的数据。
  484. //而imuQueImu队列则是把当前帧之前的imu数据都给直接剔除掉,仅保留当前帧之后的imu数据,
  485. //用作两帧lidar里程计到达时刻之间发布的imu增量式里程计的预测。
  486. //imuQueImu和imuQueOpt的区别要明确,imuIntegratorImu_和imuIntegratorOpt_的区别也要明确,见imuhandler中的注释
  487. while (!imuQueImu.empty() && ROS_TIME(&imuQueImu.front()) < currentCorrectionTime - delta_t)
  488. {
  489. lastImuQT = ROS_TIME(&imuQueImu.front());
  490. imuQueImu.pop_front();
  491. }
  492. // repropogate
  493. // 对剩余的imu数据计算预积分
  494. if (!imuQueImu.empty())
  495. {
  496. // reset bias use the newly optimized bias
  497. // 传入状态,重置预积分器和最新的偏置
  498. imuIntegratorImu_->resetIntegrationAndSetBias(prevBiasOdom);
  499. // integrate imu message from the beginning of this optimization
  500. // 计算预积分
  501. //利用imuQueImu中的数据进行预积分 主要区别旧在于上一行的更新了bias
  502. for (int i = 0; i < (int)imuQueImu.size(); ++i)
  503. {
  504. sensor_msgs::Imu _thisImu = &imuQueImu[i];
  505. double imuTime = ROS_TIME(thisImu);
  506. double dt = (lastImuQT < 0) ? (1.0 / 500.0) :(imuTime - lastImuQT);
  507. // 注意:加入的是这个用于传播的的预积分器imuIntegratorImu_,(之前用来计算的是imuIntegratorOpt_,)
  508. //注意加入了上一步算出的dt
  509. //结果被存放在imuIntegratorImu_中
  510. imuIntegratorImu_->integrateMeasurement(gtsam::Vector3(thisImu->linear_acceleration.x, thisImu->linear_acceleration.y, thisImu->linear_acceleration.z),
  511. gtsam::Vector3(thisImu->angular_velocity.x, thisImu->angular_velocity.y, thisImu->angular_velocity.z), dt);
  512. lastImuQT = imuTime;
  513. }
  514. }
  515. ++key;
  516. //设置成True,用来通知另一个负责发布imu里程计的回调函数imuHandler“可以发布了”
  517. doneFirstOpt = true;
  518. }
  519. /
  520. _ imu因子图优化结果,速度或者偏置过大,认为失败
  521. _/
  522. bool failureDetection(const gtsam::Vector3& velCur, const gtsam::imuBias::ConstantBias& biasCur)
  523. {
  524. Eigen::Vector3f vel(velCur.x(), velCur.y(), velCur.z());
  525. if (vel.norm() > 30)
  526. {
  527. ROS_WARN(“Large velocity, reset IMU-preintegration!”);
  528. return true;
  529. }
  530. Eigen::Vector3f ba(biasCur.accelerometer().x(), biasCur.accelerometer().y(), biasCur.accelerometer().z());
  531. Eigen::Vector3f bg(biasCur.gyroscope().x(), biasCur.gyroscope().y(), biasCur.gyroscope().z());
  532. if (ba.norm() > 1.0 || bg.norm() > 1.0)
  533. {
  534. ROS_WARN(“Large bias, reset IMU-preintegration!”);
  535. return true;
  536. }
  537. return false;
  538. }
  539. /
  540. _ 订阅imu原始数据
  541. _ 1、用上一帧激光里程计时刻对应的状态、偏置,
  542. _ 施加从该时刻开始到当前时刻的imu预计分量,得到当前时刻的状态,也就是imu里程计
  543. _ 2、imu里程计位姿转到lidar系,发布里程计
  544. _/
  545. void imuHandler(const sensor_msgs::Imu::ConstPtr& imu_raw)
  546. {
  547. std::lock_guard<std::mutex> lock(mtx);
  548. // imu原始测量数据转换到lidar系,加速度、角速度、RPY
  549. sensor_msgs::Imu thisImu = imuConverter(_imu_raw);
  550. // 添加当前帧imu数据到队列
  551. // 两个双端队列分别装着优化前后的imu数据
  552. imuQueOpt.push_back(thisImu);
  553. imuQueImu.push_back(thisImu);
  554. // 要求上一次imu因子图优化执行成功,确保更新了上一帧(激光里程计帧)的状态、偏置,预积分已经被重新计算
  555. // 这里需要先在odomhandler中优化一次后再进行该函数后续的工作
  556. if (doneFirstOpt == false)
  557. return;
  558. double imuTime = ROS_TIME(&thisImu);
  559. //lastImuT_imu变量初始被赋值为-1
  560. // 获得时间间隔, 第一次为1/500,之后是两次imuTime间的差
  561. double dt = (lastImuT_imu < 0) ? (1.0 / 500.0) : (imuTime - lastImuT_imu);
  562. lastImuT_imu = imuTime;
  563. // integrate this single imu message
  564. // imu预积分器添加一帧imu数据,注:这个预积分器的起始时刻是上一帧激光里程计时刻
  565. imuIntegratorImu_->integrateMeasurement(gtsam::Vector3(thisImu.linear_acceleration.x, thisImu.linear_acceleration.y, thisImu.linear_acceleration.z),
  566. gtsam::Vector3(thisImu.angular_velocity.x, thisImu.angular_velocity.y, thisImu.angular_velocity.z), dt);
  567. // predict odometry
  568. // 用上一帧激光里程计时刻对应的状态、偏置,施加从该时刻开始到当前时刻的imu预计分量,得到当前时刻的状态
  569. gtsam::NavState currentState = imuIntegratorImu_->predict(prevStateOdom, prevBiasOdom);
  570. // publish odometry
  571. // 发布imu里程计(转到lidar系,与激光里程计同一个系)
  572. nav_msgs::Odometry odometry;
  573. odometry.header.stamp = thisImu.header.stamp;
  574. odometry.header.frame_id = odometryFrame; //“odom”
  575. odometry.child_frame_id = “odom_imu”;
  576. // transform imu pose to ldiar
  577. //预测值currentState获得imu位姿, 再由imu到雷达变换, 获得雷达位姿
  578. gtsam::Pose3 imuPose = gtsam::Pose3(currentState.quaternion(), currentState.position());
  579. gtsam::Pose3 lidarPose = imuPose.compose(imu2Lidar);
  580. // 这里留疑问,本cpp读完后补充:
  581. // 为什么currentState获得的是imu的位姿?原始imu数据难道不是先转换成雷达坐标系下的数据(this imu)才再送到imu预积分器中吗?
  582. //答: 在之前的优化函数odometryHandler中,thisIMU是直接从imuQueOpt中取值.
  583. //而imuQueOpt中的内容,是已经从imu原始测量数据转换到了lidar”中间系”系下(在本函数第二行)。离真正的雷达系还差了一个平移
  584. //odometryHandler函数中根据prevPose_ = lidarPose.compose(lidar2Imu)得到激光帧先验位姿(lidarPose)转换到imu系下,(相当于从真正的雷达系扭到上面的中间系中)
  585. //作为初值构建了因子进行优化;
  586. //在其imuIntegratorOpt_->integrateMeasurement中得到的应该是dt之间的预积分量,
  587. //由于其处在循环中,因此是在递推累积计算两帧之间的预积分量。
  588. //(相当于是每到一帧,就把二者之间的预积分量计算一遍,并且优化一遍,存储进imuIntegratorOpt_)中。
  589. //因为本函数为imu回调函数,每收到一个imu数据,当之前因子图算完的情况下,
  590. //在imuIntegratorImu_的基础上继续递推新收到的imu数据,并且进行预测。
  591. //最后把imu再转回lidar系下进行发布。
  592. //注意:这里发布的是两帧之间的“增量”imu里程计信息,
  593. //imuIntegratorImu_本身是个积分器,只有两帧之间的预积分,但是发布的时候发布的实际是结合了前述里程计本身有的位姿
  594. //如这个predict里的prevStateOdom:
  595. //currentState = imuIntegratorImu_->predict(prevStateOdom, prevBiasOdom);
  596. //关于imuIntegratorImu_在两个回调函数中都进行integrateMeasurement操作,之间是否会有冲突呢?
  597. //我觉得关键在于odometryHandler中有一句:imuIntegratorImu_->resetIntegrationAndSetBias(prevBiasOdom),
  598. //在imuIntegratorOpt_优化完两帧imu数据之后,imuIntegratorImu_直接把积分和bias给reset掉,
  599. //然后开始根据imuIntegratorOpt_优化出的bias来更新imuIntegratorImu_。
  600. //imuIntegratorImu_和imuIntegratorOpt_的区别在于,opt存储的是新到一帧,和上一帧之间的预积分量,作为约束,执行优化。
  601. //优化后,imuIntegratorImu_利用新的bias,在新到的这一帧的基础上,递推“之后”的预积分量。
  602. //(绝对不能把imuIntegratorOpt_和imuIntegratorImu_理解为同一批imu数据在优化前后的不同值)
  603. //在更新的过程中不用担心会被imuHandler中的imuIntegratorImu_->integrateMeasurement给顶掉,
  604. //这是因为imuHandler要根据doneFirstOpt来检查odometryHandler是不是已经更新完bias了。
  605. //因为更新并不是实时的,而是一帧激光数据到了才更新。
  606. //可是下一帧激光并没有到,但是在此期间imu增量式里程计还是得照常发布,
  607. //如果当前帧已经更新完bias了,然后就可以直接利用这个bias计算后面新到的ImuIntegratorImu_,
  608. odometry.pose.pose.position.x = lidarPose.translation().x();
  609. odometry.pose.pose.position.y = lidarPose.translation().y();
  610. odometry.pose.pose.position.z = lidarPose.translation().z();
  611. odometry.pose.pose.orientation.x = lidarPose.rotation().toQuaternion().x();
  612. odometry.pose.pose.orientation.y = lidarPose.rotation().toQuaternion().y();
  613. odometry.pose.pose.orientation.z = lidarPose.rotation().toQuaternion().z();
  614. odometry.pose.pose.orientation.w = lidarPose.rotation().toQuaternion().w();
  615. odometry.twist.twist.linear.x = currentState.velocity().x();
  616. odometry.twist.twist.linear.y = currentState.velocity().y();
  617. odometry.twist.twist.linear.z = currentState.velocity().z();
  618. odometry.twist.twist.angular.x = thisImu.angular_velocity.x + prevBiasOdom.gyroscope().x();
  619. odometry.twist.twist.angular.y = thisImu.angular_velocity.y + prevBiasOdom.gyroscope().y();
  620. odometry.twist.twist.angular.z = thisImu.angular_velocity.z + prevBiasOdom.gyroscope().z();
  621. pubImuOdometry.publish(odometry);
  622. }
  623. };
  624. //还有两个问题:
  625. //1.第一个是,为什么imu原始数据先要根据imuConverter变到lidar系,
  626. //那么之后imuintegrator->integrateMeasurement算到的预积分数据不就是lidar系下的吗?
  627. //在处理的时候又是把lidar里程计的坐标系根据compose函数变到imu系?这难道不是不对应了吗:
  628. //2.变量gtsam::Pose3 imu2Lidar = gtsam::Pose3(gtsam::Rot3(1, 0, 0, 0),
  629. //gtsam::Point3(-extTrans.x(), -extTrans.y(), -extTrans.z()));
  630. //这里为什么不用配置文件中的extRot,extQRPY之类的内容呢,而只是用了extTrans数据?
  631. //关于这点,我在github中找到了解释:https://github.com/TixiaoShan/LIO-SAM/issues/30,
  632. //imuConverter() to align the axis of the two coordinates,并没有涉及到平移,
  633. //lidar2Imu or imu2Lidar 却只有平移的内容
  634. //因此收到imu后,先用imuConverter()转换到雷达系下,(但其实和雷达之间仍然差了一个平移),
  635. //因此又把雷达的内容用只含有平移的lidar2Imu 和原本差了一个平移的imu数据真正对齐
  636. //(相当于是imu旋转到雷达系下以后不平移,然后把雷达倒着平移过来,在一个“中间系”对齐)。
  637. //在算完以后,等发布的时候,又用imu2Lidar又倒回到了正儿八经的雷达系。
  638. //那么tixiaoshan为什么在默认里把平移参数设置为0,0,0?
  639. //他在github中的解释为: 我在不同的数据集中改变了几次IMU的安装位置。但是位置总是靠近激光雷达。
  640. //所以每次测试不同的数据集时,我都不必费心去修改这个参数。严格地说,我的方法并不理想。需要提供此参数以获得更好的性能。
  641. int main(int argc, char** argv)
  642. {
  643. ros::init(argc, argv, “roboat_loam”);
  644. IMUPreintegration ImuP;
  645. TransformFusion TF;
  646. ROS_INFO(“\033[1;32m——> IMU Preintegration Started.\033[0m”);
  647. ros::MultiThreadedSpinner spinner(4);
  648. spinner.spin();
  649. return 0;
  650. }



总结


这个cpp文件主要有两个类,一个叫IMUPreintegration类,一个叫TransformFusion类。


现在我们分开讲,先说IMUPreintegration类。


关于IMU原始数据,送入imuhandle中:


1.1 imuhandle:



1.1.1 imu原始数据,会先被坐标系转换,通过调用头文件里的imuConverter函数,转换到一个“雷达中间系”中,其实和真正的雷达系差了一个平移。


1.1.2 转换后,会存入两个队列,一个imuQueOpt队列,一个imuQueImu队列。这两队列有什么区别和联系呢?这个主要在另一个回调函数odometryHandler会被处理,在那个地方我会讲。这里我们可以先理解为,imuQueImu是真正我们要用的数据,imuQueOpt是一个中间缓存的数据结构,用来优化imu的bias之类的东西。


1.1.3 在标志位doneFirstOpt为True的时候(注意这个标志位,这是一个很重要的变量,之后会再提到),每到一个imu数据,就用imuIntegratorImu_这个预积分器,把这一帧imu数据累积进去,然后预测当前时刻的状态:currentState = imuIntegratorImu_->predict(prevStateOdom, prevBiasOdom); 其中prevStateOdom就是之前系统所保持的状态。


1.1.4 把currentState,通过imu2Lidar,从“中间系”给平移到真正的雷达系,然后发布出去。发布的话题就叫odometry/imu_incremental,这也就是imageProjection.cpp的总结部分的第2点部分提到的“imu”里程计。


1.2. odomHandle:这部分订阅的是/mapping/odometry_incremental,这个话题是由mapOptmization.cpp发布的,可以把它理解为激光里程计。同理,也不要被incremental误导,觉得好像是两帧激光之间的变换,可不是这样的啊。它和imu里程计性质类似,就是相对世界坐标系的位姿。



1.2.1 初始化系统:


从imuQueOpt队列里,删掉当前这帧激光里程计时间上之前的数据,然后把雷达的pose变换到“中间系”,保存为prevPose。图优化部分,加入乱七八糟各种东西,priorVel,priorBias,把两个预积分器imuIntegratorImu_,imuIntegratorOpt_给reset一下。(之后简称imu积分器和opt积分器)


这两个预积分器opt积分器和imu积分器有什么区别呢?马上就要讲,在1.2.3部分。


1.2.2 清理缓存:


100帧激光里程计数据了,就把优化器给reset一下(用前面的先验协方差给reset一下)。注意,1.2.1和1.2.2的主要区别在于,1.2.1中的乱七八糟协方差数据,是用构造函数中写入的一大堆(我认为是经验值),而1.2.2这里的协方差,用的是optimizer.marginalCovariance这个轮子算出来的先验协方差。


1.2.3 正式处理:


假设数据如下分布:


之前imu数据 ——————第一帧开始——————第二帧开始————之后imu数据


1.2.3.1 把“第一帧开始”——“第二帧开始”这个之间的imu数据拿出来,送入opt积分器。这样得到二者之间的预积分,构建imu因子。


1.2.3.2 然后把Xkey-1 到Xkey之间,加入这个imu因子以及 激光里程计提供的pose因子,整体做一个优化。优化的结果就是bias,以及“第二帧开始”这个时刻的系统位姿。


1.2.3.3 把优化的结果(主要是bias),重置opt积分器和imu积分器。 然后把当前帧(上图的“第二帧开始”)之前的数据给删掉,用imu积分器,从“第二帧开始”这里开始往后积分。(我们需要明确一点,在这个处理过程中,imu队列也在持续的进数据,(即1.1的imuhandle中)),这里处理完,那么就置donefirst=True,这样1.1.3部分,就可以无缝衔接接着在这里的基础上对imu积分器继续积分。(可以看出,这点处理,Tixiaoshan还是做的比较牛的)


回顾:在1.1.3部分,发布imu里程计,在这里我们可以的出结果,它并非是纯粹的imu里程计,因为时不时是要加入激光里程计的信息做因子来优化得到imu的bias等信息的。


接下来我们开始讲TransformFusion类。


2.1 lidarOdometryHandler:


这部分监听的是/mapping/odometry,(也就是激光雷达里程计)这个回调函数比较特殊,它并没有把雷达里程计的东西再像别的回调函数一样,时刻存到什么队列里去。而是就保存当前的雷达里程计的数据到lidarOdomAffine里面,把时间戳存到lidarOdomTime里面去。



注意,这里/mapping/odometry和/mapping/odometry_incremental有什么区别呢?我认为本质上区别不大,前者是激光里程计部分直接优化得到的激光位姿,后者相当于激光的位姿经过旋转约束和z轴约束的限制以后,又和原始imu信息里面的角度做了一个加权以后的位姿。


2.2 imuOdometryHandler


这部分监听的是/imu/odometry_incremental(也就是上面我一直在说的imu里程计),把imu里程计放到imuodomQueue里面保存,然后把lidarOdomTime之前的数据扔掉,用imu里程计的两时刻差异,再加上lidarOdomAffine的基础进行发布。


实际上,/imu/odometry_incremental本身就是雷达里程计基础上imu数据上的发布,而在现在这里,也是雷达里程计在“imu里程计”上的一个“再次精修”。最后会发布两个内容,一个是odometry/imu,但是这个实际上是无人监听的,我觉得作者主要是发布tf变换,顺手给它发布了。当然我觉得用户可以监听这个数据,我觉得这个应该是频率上最高的一个里程计数据了。


另外还会发布一个path,用来rviz显示,名字叫lio-sam/imu/path。




mapOptimization.cpp


这个cpp的内容和前三个cpp的内容加起来行数差不多,比较复杂。也是最容易混乱的一个cpp文件,主要是里面有太多的变量,和相近的命名。我用A3纸记录流程,足足写了4页,说实话写到这里的时候我已经不想往上打了,想干脆把A3纸扫描一下传上来。但是我的字迹写的实在是太潦草了,所以这里还是硬着头皮敲吧。因为不方便画箭头,所以还是得自己去编号。


老规矩,先放代码注释:


注释


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



总结


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


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


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


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


1.1  UpdateInitGuess:当前帧初始化。



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


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


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


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


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


1.1.3 假如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,返回。


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



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


如果有,就调用extractNearby函数。


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


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


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


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


那么接下来,我介绍extractNearby函数:


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


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


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


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


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


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


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


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


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


1.3 downsampleCurrentScan:


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


1.4 Scan2MapOptimization:



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


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


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


迭代30次:


 1.4.2.1 边缘点匹配优化:CornerOptimization


1.4.2.2 平面点匹配优化:SurfOptimization


1.4.2.3 组合优化多项式系数:combineOptimizationCoeffs


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


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


 接下来,我们依次展开这些函数:



 1.4.2.1 边缘点匹配优化:CornerOptimization


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

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



1.4.2.2 平面点匹配优化:SurfOptimization


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


 1.4.2.3 组合优化多项式系数:combineOptimizationCoeffs


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


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



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


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


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


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


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


LeGO-LOAM中的数学公式推导


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


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


  1. 在历史帧中搜索距离关键帧最近,时间间各较远的关键帧(默认是30s以外,15m以内)没找到就返回,如果找到了,结果就放在loopKeyPre当中,loopKeyCur保存最近一个关键帧。
  2. 把最近一个关键帧的特征点提出来,放入cureKeyframeCloud里;回环候选帧前后各25帧也提取出来,放入prevKeyframeCloud里。
  3. 把prevKeyframeCloud发布出去,名为lio_sam/mapping/icp_loop_closure_history/cloud
  4. 调用pcl库的icp轮子,设定阈值,参数,用setInputSource,setInputTarget传入两个点云,用align对齐。成功阈值设定为0.3,成功则存在icp.getFinalTransformation里面。把当前关键帧的点云,用这个结果icp.getFinalTransformation,转换以后,以lio_sam/mapping/icp_loop_closure_corrected_cloud发布出去。
  5. 把当前帧的的位姿用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文件。




我的专栏地址是 微鉴道长SLAM学习笔记(目录),希望感兴趣的朋友多多关注。我目前在杭州从事强化学习导航和slam建图相关的导航工作,我的联系邮箱是zkyy828@163.com,欢迎交流和合作。