版权声明:本文为博主原创文章,转载请注明出处: http://www.cnblogs.com/newneul/p/8571653.html 
3、题目回顾:
在稀疏直接法中,假设单个像素周围小块的光度也不变,是否可以提高算法的健壮性?请编程实现、
分析:根据直接法的思想:基于灰度不变假设。因为题目假设了周围小块光度也不变,那么我们可以用单个像素周围的3x3或5x5小块的平均灰度值作为单个像素的灰度值,从一定程度上调高了健壮性,但是效果提升有限。
下面程序集成了direct_sparse.cpp程序的解释和利用半稠密直接法思路结合稀疏直接法以及本题小块思想的结合。共有四种配置方案。默认为稀疏直接法+小块思路 也就是本题目的解法。当然也可以对应修改配置信息。执行相应的功能查看效果。
程序代码如下:

  1. #include <iostream>
  2. #include <fstream>
  3. #include <list>
  4. #include <vector>
  5. #include <chrono>
  6. #include <ctime>
  7. #include <climits>
  8.  
  9. #include <opencv2/core/core.hpp>
  10. #include <opencv2/imgproc/imgproc.hpp>
  11. #include <opencv2/highgui/highgui.hpp>
  12. #include <opencv2/features2d/features2d.hpp>
  13.  
  14. #include <g2o/core/base_unary_edge.h>
  15. #include <g2o/core/block_solver.h>
  16. #include <g2o/core/optimization_algorithm_levenberg.h>
  17. #include <g2o/solvers/dense/linear_solver_dense.h>
  18. #include <g2o/core/robust_kernel.h>
  19. #include <g2o/types/sba/types_six_dof_expmap.h>
  20.  
  21. using namespace std;
  22. using namespace g2o;
  23.  
  24. /*+++++++++++++++++++++++++++参数配置区+++++++++++++++++++++++++++++++++++++++=*/
  25.  
  26. //下面两种配置参数 可以任意组合 互不冲突 下面列出4种情况:
  27. /* SEMIDENSE BookExercise
  28. * 0 0 : 采用direct_sparse 例子 稀疏直接法(提取FAST特征)
  29. * 0 1 : 采用书上课后习题3(小块均值法)+ 稀疏直接法(提取FAST特征)
  30. * 1 0 : 采用稀疏直接法(提取FAST特征) +半稠密直接法(选取梯度大的)
  31. * 1 1 : 采用半稠密直接法(提取FAST特征)+课后习题3思路(小块均值法)+稀疏直接法(提取FAST特征)
  32. * 从枚举器中选择合适的值,对应修改下面的两个值:
  33. * GradientThread 梯度域值
  34. * PATCH_RADIUS 小块半径
  35. * */
  36. #define SEMIDENSE 0 // 1 (稀疏直接法+半稠密法) 表示利用半稠密方法思想 筛选梯度比较大的点 这里就是从FAST关键点中筛选出梯度大的点
  37. // 0 表示仅仅用稀疏直接法
  38. #define BookExercise 1 // 1 表示运行课后习题3的做法
  39. // 0 表示不采用课后习题3的做法
  40.  
  41. #if SEMIDENSE
  42. enum GradientThreadChoice{
  43. GRADIENT_10 = , //1170点
  44. GRADIENT_15 = , //984点
  45. GRADIENT_20 = , //805点
  46. GRADIENT_25 = , //656点
  47. GRADIENT_30 = , //514点
  48. GRADIENT_50 = , //201点
  49. GRADIENT_100 = //33点
  50. };
  51. #define GradientThread GRADIENT_50 // 默认筛选的梯度域值,通过调节域值(默认50) 可以增加关键点的个数
  52.  
  53. #endif
  54.  
  55. #if BookExercise
  56. enum PatchRadiusChoices{ // 块大小选取类
  57. PATCH_RADIUS_ONE = , // 表示以像素为圆心 半径为1大小的块
  58. PATCH_RADIUS_TWO = // 最多半径为2 否则计算量太大(因为边计算误差函数会进行插值查找 块越大 计算量成平方增加)
  59. };
  60. PatchRadiusChoices PATCH_RADIUS = PATCH_RADIUS_ONE; //将全局变量置为该选项半径为1
  61. #endif // 1对应3x3小块 2对应5x5小块
  62.  
  63. /*+++++++++++++++++++++++++++END参数配置取++++++++++++++++++++++++++++++++++++=*/
  64.  
  65. /********************************************
  66. * 本节演示了RGBD上的稀疏直接法
  67. ********************************************/
  68. //获取小块平均灰度值
  69. // gray:灰度矩阵 x,y表示以(x,y)为中心 计算的小块的平均灰度 patchRadius 表示块的半径
  70. #if BookExercise
  71. float getPatchAverageGray(const cv::Mat &gray ,float u, float v,int patchRadius);
  72. // 一次测量的值,包括一个世界坐标系下三维点(以第一帧为参考系)与一个灰度值(以第一帧为参考的3D点对应灰度图像的灰度值,灰度图是由color图像转换到对应的gray图像得到的 )
  73. #endif
  74. struct Measurement
  75. {
  76. Measurement ( Eigen::Vector3d p, float g ) : pos_world ( p ), grayscale ( g ) {}
  77. Eigen::Vector3d pos_world;
  78. float grayscale;
  79. };
  80.  
  81. //转换成相机坐标系下坐标
  82. inline Eigen::Vector3d project2Dto3D ( int x, int y, int d, float fx, float fy, float cx, float cy, float scale )
  83. {
  84. float zz = float ( d ) /scale;
  85. float xx = zz* ( x-cx ) /fx;
  86. float yy = zz* ( y-cy ) /fy;
  87. return Eigen::Vector3d ( xx, yy, zz );
  88. }
  89.  
  90. inline Eigen::Vector2d project3Dto2D ( float x, float y, float z, float fx, float fy, float cx, float cy )
  91. {
  92. float u = fx*x/z+cx;
  93. float v = fy*y/z+cy;
  94. return Eigen::Vector2d ( u,v );
  95. }
  96.  
  97. // 直接法估计位姿
  98. // 输入:测量值(空间点的灰度),新的灰度图,相机内参; 输出:相机位姿
  99. // 返回:true为成功,false失败 这里并没有设置返回值信息!
  100. bool poseEstimationDirect ( const vector<Measurement>& measurements, cv::Mat* gray, Eigen::Matrix3f& intrinsics, Eigen::Isometry3d& Tcw );
  101.  
  102. // project a 3d point into an image plane, the error is photometric error
  103. // an unary edge with one vertex SE3Expmap (the pose of camera)
  104. //误差值维度 误差类型 顶点类型
  105. class EdgeSE3ProjectDirect: public BaseUnaryEdge< , double, VertexSE3Expmap>
  106. {
  107. public:
  108. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  109.  
  110. EdgeSE3ProjectDirect() = default; //代替下面的方式 默认产生合成的构造函数
  111. //EdgeSE3ProjectDirect(){}
  112. EdgeSE3ProjectDirect ( Eigen::Vector3d point, float fx, float fy, float cx, float cy, cv::Mat* image )
  113. : x_world_ ( point ), fx_ ( fx ), fy_ ( fy ), cx_ ( cx ), cy_ ( cy ), image_ ( image ) //灰度图像指针
  114. {}
  115.  
  116. virtual void computeError()override
  117. {
  118. const VertexSE3Expmap* v =static_cast<const VertexSE3Expmap*> ( _vertices[] );
  119. Eigen::Vector3d x_local = v->estimate().map ( x_world_ );
  120. float x = x_local[]*fx_/x_local[] + cx_; //世界坐标转换到当期帧像素坐标
  121. float y = x_local[]*fy_/x_local[] + cy_;
  122. // check x,y is in the image
  123. //距离图像四条边4个像素大小的区域内作为有效投影区域 对于不在该范围内的点误差值设为0 为了防止计算的误差太大 拉低内点对误差的影响 导致估计的RT严重偏离真值
  124. if ( x-< || ( x+ ) >image_->cols || ( y- ) < || ( y+ ) >image_->rows )
  125. {
  126. _error ( , ) = 0.0;
  127. this->setLevel ( );//???????????????????????????????????????????????????
  128. }
  129. else
  130. {
  131. #if BookExercise //表示运行课后习题3
  132. //选取小块的大小为2x2
  133. float sumValue = 0.0;
  134. for(int i = x-PATCH_RADIUS ; i<= x+PATCH_RADIUS ; ++i)
  135. for (int j = y-PATCH_RADIUS; j <= y+PATCH_RADIUS ; ++j) {
  136. sumValue += getPixelValue(i,j);
  137. }
  138. sumValue /=( (*PATCH_RADIUS +)*(*PATCH_RADIUS+) ); //求得元素周围小块的平均灰度值
  139. _error (,) = sumValue - _measurement;
  140. #else
  141. _error ( , ) = getPixelValue ( x,y ) - _measurement;//经过在灰度图中插值获得的像素值 减去测量值
  142. #endif
  143. }
  144. }
  145.  
  146. // plus in manifold
  147. //提供误差关于位姿的雅克比矩阵 书上8.16式子 只不过负号去掉了 因为用的是当前帧灰度值 - 世界坐标下的测量值
  148. virtual void linearizeOplus( )override
  149. {
  150. if ( level() == )
  151. {
  152. _jacobianOplusXi = Eigen::Matrix<double, , >::Zero();
  153. return;
  154. }
  155. VertexSE3Expmap* vtx = dynamic_cast<VertexSE3Expmap*> ( _vertices[] );
  156. Eigen::Vector3d xyz_trans = vtx->estimate().map ( x_world_ ); // q in book 转换到第二帧坐标系下
  157.  
  158. double x = xyz_trans[];
  159. double y = xyz_trans[];
  160. double invz = 1.0/xyz_trans[];
  161. double invz_2 = invz*invz;
  162.  
  163. float u = x*fx_*invz + cx_;//投影到第二帧像素坐标系
  164. float v = y*fy_*invz + cy_;
  165.  
  166. // jacobian from se3 to u,v
  167. // NOTE that in g2o the Lie algebra is (\omega, \epsilon), where \omega is so(3) and \epsilon the translation
  168. Eigen::Matrix<double, , > jacobian_uv_ksai;
  169.  
  170. //书上8.15式子
  171. jacobian_uv_ksai ( , ) = - x*y*invz_2 *fx_;
  172. jacobian_uv_ksai ( , ) = ( + ( x*x*invz_2 ) ) *fx_;
  173. jacobian_uv_ksai ( , ) = - y*invz *fx_;
  174. jacobian_uv_ksai ( , ) = invz *fx_;
  175. jacobian_uv_ksai ( , ) = ;
  176. jacobian_uv_ksai ( , ) = -x*invz_2 *fx_;
  177.  
  178. jacobian_uv_ksai ( , ) = - ( +y*y*invz_2 ) *fy_;
  179. jacobian_uv_ksai ( , ) = x*y*invz_2 *fy_;
  180. jacobian_uv_ksai ( , ) = x*invz *fy_;
  181. jacobian_uv_ksai ( , ) = ;
  182. jacobian_uv_ksai ( , ) = invz *fy_;
  183. jacobian_uv_ksai ( , ) = -y*invz_2 *fy_;
  184.  
  185. Eigen::Matrix<double, , > jacobian_pixel_uv;
  186.  
  187. //书上I2对像素坐标系的偏导数 这里很有可能 计算出来的梯度为0 因为FAST角点的梯度没有限制
  188. //这也是半稠密法主要改进的地方 就是选关键点的时候 选择梯度大的点 因此这里的梯度就不可能为0了
  189. jacobian_pixel_uv ( , ) = ( getPixelValue ( u+,v )-getPixelValue ( u-,v ) ) /;
  190. jacobian_pixel_uv ( , ) = ( getPixelValue ( u,v+ )-getPixelValue ( u,v- ) ) /;
  191.  
  192. _jacobianOplusXi = jacobian_pixel_uv*jacobian_uv_ksai;//书上8.16式子
  193. }
  194.  
  195. // dummy read and write functions because we don't care...
  196. virtual bool read ( std::istream& in ) {}
  197. virtual bool write ( std::ostream& out ) const {}
  198.  
  199. protected:
  200. // get a gray scale value from reference image (bilinear interpolated)
  201. //cv::Mat中成员变量代表的含义:http://blog.csdn.net/dcrmg/article/details/52294259
  202. //下面的方式 针对单通道的灰度图
  203. inline float getPixelValue ( float x, float y )//通过双线性插值获取浮点坐标对应的插值后的像素值
  204. {
  205. uchar* data = & image_->data[ int ( y ) * image_->step + int ( x ) ];//step表示图像矩阵一行的所有字节(包括所有通道的总和),data表示存储图像的开始指针
  206. float xx = x - floor ( x ); //取整函数
  207. float yy = y - floor ( y );
  208. return float ( //公式f(i+u,j+v) = (1-u)(1-v)f(i,j) + u(1-v)f(i+1,j) + (1-u)vf(i,j+1) + uvf(i+1,j+1)
  209. //这里的xx 就是u yy就是v
  210. ( -xx ) * ( -yy ) * data[] +
  211. xx* ( -yy ) * data[] +
  212. ( -xx ) *yy*data[ image_->step ] + //I(i+1,j) //这里相当于像素的周期是image_->step,即每一行存储像素的个数为image_->step
  213. xx*yy*data[image_->step+] //I(i+1,j+1) //data[image_->step]是I(i,j)对应的下一行像素为I(i+1,j)
  214. );
  215. }
  216. public:
  217. Eigen::Vector3d x_world_; // 3D point in world frame
  218. float cx_=, cy_=, fx_=, fy_=; // Camera intrinsics
  219. cv::Mat* image_=nullptr; // reference image
  220. };
  221.  
  222. int main ( int argc, char** argv )
  223. {
  224. if ( argc != )
  225. {
  226. cout<<"usage: useLK path_to_dataset"<<endl;
  227. return ;
  228. }
  229. srand ( ( unsigned int ) time ( ) );
  230. string path_to_dataset = argv[];
  231. string associate_file = path_to_dataset + "/associate.txt";
  232.  
  233. ifstream fin ( associate_file );
  234.  
  235. string rgb_file, depth_file, time_rgb, time_depth;
  236. cv::Mat color, depth, gray;
  237. vector<Measurement> measurements;//Measurement类 存储世界坐标点(以第一帧为参考的FAST关键点) 和 对应的灰度图像(由color->gray)的灰度值
  238. // 相机内参
  239. float cx = 325.5;
  240. float cy = 253.5;
  241. float fx = 518.0;
  242. float fy = 519.0;
  243. float depth_scale = 1000.0;
  244. Eigen::Matrix3f K;
  245. K<<fx,.f,cx,.f,fy,cy,.f,.f,1.0f;
  246.  
  247. Eigen::Isometry3d Tcw = Eigen::Isometry3d::Identity();//三维变换矩阵T 4X4 初始时刻是单位R矩阵+0平移向量
  248.  
  249. cv::Mat prev_color;
  250. // 我们以第一个图像为参考,对后续图像和参考图像做直接法 ,每一副图像 都会与第一帧图像做直接法计算第一帧到当前帧的RT 但是经过更多的帧后 关键点的数量会减少,
  251. //所以实际应用时 应当规定关键点的数量少于多少 就该从新设定参考系,再次利用直接法 ,但是会累计的误差需要解决????
  252. for ( int index=; index<; index++ )//总共10帧
  253. {
  254. cout<<"*********** loop "<<index<<" ************"<<endl;
  255. fin>>time_rgb>>rgb_file>>time_depth>>depth_file;
  256. color = cv::imread ( path_to_dataset+"/"+rgb_file );
  257. depth = cv::imread ( path_to_dataset+"/"+depth_file, - );//-1 按原图像的方式存储 detph 16位存储
  258. if ( color.data==nullptr || depth.data==nullptr )
  259. continue;
  260. //转换后的灰度图为g2o优化需要的边提供灰度值
  261. cv::cvtColor ( color, gray, cv::COLOR_BGR2GRAY ); //将颜色图3通道 转换为灰度图单通道 8位无符号 对应边类的双线性插值计算放法以单通道计算的
  262.  
  263. //第一帧为世界坐标系 计算FAST关键点 为之后与当前帧用直接法计算RT做准备
  264. if ( index == )//以第一帧为参考系 计算关键点后存储测量值(关键点对应的灰度值) 以此为基准跟踪后面的图像 计算位姿
  265. {
  266. // 对第一帧提取FAST特征点
  267. vector<cv::KeyPoint> keypoints;
  268. cv::Ptr<cv::FastFeatureDetector> detector = cv::FastFeatureDetector::create();
  269. detector->detect ( color, keypoints );
  270. //对于2D关键点获取 3D信息 并去掉范围外的点 存储符合要求的关键点的深度值和3D信息
  271. //对所有关键点挑选出符合要求且有深度值的 存储到vector<Measurement> measurements中 为g2o边提供灰度测量值和空间点坐标
  272. for ( auto kp:keypoints )
  273. {
  274. #if SEMIDENSE //表示利用半稠密法的思想 只不过结果由原来的1402个点 变为了201个点 特征点数目降低了 但是看起来精度还是很高 可以适当调整梯度域值
  275. Eigen::Vector2d delta ( //计算像素坐标系下 两个方向的变化量
  276. gray.ptr<uchar>(int ( kp.pt.y))[ int(kp.pt.x+)] - gray.ptr<uchar>(int(kp.pt.y))[int(kp.pt.x-)],
  277. gray.ptr<uchar>(int(kp.pt.y+))[int(kp.pt.x)] - gray.ptr<uchar>(int(kp.pt.y-))[int(kp.pt.x)]
  278. );
  279. //cout<<" keypoints坐标值: "<<kp.pt.x<<" "<<kp.pt.y<<endl;//可以看出点虽然存储方式是浮点数 但是实际的值都是int类型
  280. if ( delta.norm() < GradientThread )//可以转变为变化量的2范数小于50/16 默认域值为30 可调
  281. continue;
  282. #endif
  283. // 去掉邻近边缘处的点 在离图像四条边20个像素构成的内矩阵范围内是符合要求的关键点
  284. if ( kp.pt.x < || kp.pt.y < || ( kp.pt.x+ ) >color.cols || ( kp.pt.y+ ) >color.rows )
  285. continue;
  286. //depth.ptr<ushort>( kp.pt.y)获取行指针 cvRound(kp.pt,y) 表示返回跟参数值最接近的整数值 因为像素量化后是整数,而kp.pt.y存储方式是float,所以强制转换一下即可
  287. ushort d = depth.ptr<ushort> ( cvRound ( kp.pt.y ) ) [ cvRound ( kp.pt.x ) ];//16位深度图
  288. if ( d== )
  289. continue;
  290. Eigen::Vector3d p3d = project2Dto3D ( kp.pt.x, kp.pt.y, d, fx, fy, cx, cy, depth_scale ); //3D相机坐标系(第一帧 也是世界帧)
  291. #if BookExercise //计算小块平均灰度值作为对应单一像素的测量值 增加算法健壮性
  292. float grayscale = getPatchAverageGray( gray , kp.pt.x , kp.pt.y , PATCH_RADIUS_ONE );
  293. #else //否则是正常以单个像素的灰度值作为测量值
  294. float grayscale = float ( gray.ptr<uchar> ( cvRound ( kp.pt.y ) ) [ cvRound ( kp.pt.x ) ] ); //8位无符号也取整数 因为灰度图 是对应整数(int)的像素的 kp.pt.y是float
  295. #endif
  296. measurements.push_back ( Measurement ( p3d, grayscale ) );
  297. }
  298. prev_color = color.clone(); //深拷贝color图像
  299. continue;
  300. }
  301. // 使用直接法计算相机运动
  302. //从第二帧开始计算相机位姿g2o优化
  303. chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
  304. //优化过程中要提供灰度图像 边里面计算误差函数需要 为getPixelValue()该函数提供灰度值查找
  305. poseEstimationDirect ( measurements, &gray, K, Tcw );//Tcw为世界坐标到下一帧坐标的累计值 最后Tcw的结果是从世界坐标 到当前帧下的转换
  306. chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
  307. chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> ( t2-t1 );
  308. cout<<"direct method costs time: "<<time_used.count() <<" seconds."<<endl;
  309. cout<<"Tcw="<<Tcw.matrix() <<endl;
  310.  
  311. // plot the feature points
  312. cv::Mat img_show ( color.rows*, color.cols, CV_8UC3 );//目的是为了之后对比前后两帧图像的关键点数量 所以建立一个可以存储pre_color 和color 大小的矩阵
  313. //Rect(参数)表示坐标0,0 到cols,rows 那么大的矩形
  314. //img_show.operator(const Rect &roi 参数:表示这个矩阵的某个兴趣区域)
  315. //img_show.opertor返回一个构造的矩阵 Mat(const Mat& m, const Rect& roi);这个构造函数返回引用m矩阵中roi那部分感兴趣的范围
  316. //最终结果是:prev_color矩阵元素拷贝到了 img_show矩阵对应Rect兴趣区域 因为img_show 是一个2*row行 cols列 可以包含两个prev_color矩阵
  317. prev_color.copyTo ( img_show ( cv::Rect ( ,,color.cols, color.rows ) ) );//0列 0行 ->cols列 rows行 大小 //实际上就是把第一帧的图像拷贝到img_show中
  318. //因为我们针对每一帧图像都会把第一帧图像拷贝到这里 所以这里实际上执行一次即可
  319. //可以修改 前加上仅仅对第二帧执行一次即可
  320. color.copyTo ( img_show ( cv::Rect ( ,color.rows,color.cols, color.rows ) ) );//0列 rows行 ->cols列 rows行 大小
  321.  
  322. //在measurements容器中 随机挑选出符合要求的测量值 在img_show矩阵中对应部分进行标记(因为img_show上半部分是第一帧图像,下半部分是当前图像)
  323. for ( Measurement m:measurements )
  324. {
  325. if ( rand() > RAND_MAX/ )
  326. continue;
  327. Eigen::Vector3d p = m.pos_world;
  328. Eigen::Vector2d pixel_prev = project3Dto2D ( float( p ( , ) ), p ( , ), p ( , ), fx, fy, cx, cy );//世界坐标系下的 图像坐标2D
  329. Eigen::Vector3d p2 = Tcw*m.pos_world;//将空间点转换到下一帧相机坐标系下
  330. Eigen::Vector2d pixel_now = project3Dto2D ( p2 ( , ), p2 ( , ), p2 ( , ), fx, fy, cx, cy );//当前帧坐标系下的图像像素坐标
  331. //对于超出下一帧图像像素坐标轴范围的点 舍弃不画
  332. if ( pixel_now(,)< || pixel_now(,)>=color.cols || pixel_now(,)< || pixel_now(,)>=color.rows )
  333. continue;
  334. //随机获取bgr颜色 在cv::circle中 为关键点用不同的颜色圆来画出
  335. float b = *float ( rand() ) /RAND_MAX;
  336. float g = *float ( rand() ) /RAND_MAX;
  337. float r = *float ( rand() ) /RAND_MAX;
  338. //在img_show包含两帧图像上 以关键点为圆心画圆 半径为8个像素 颜色为bgr随机组合 2表示外轮廓线宽度为2 如果为负数则表示填充圆
  339. //pixel_prev 都是世界坐标系下的坐标 (以第一帧为参考系) 和当前帧下的对比 可以看出关键点的数量会逐渐减少
  340. cv::circle ( img_show, cv::Point2d ( pixel_prev ( , ), pixel_prev ( , ) ), , cv::Scalar ( b,g,r ), );
  341. cv::circle ( img_show, cv::Point2d ( pixel_now ( , ), pixel_now ( , ) +color.rows ), , cv::Scalar ( b,g,r ), );//注意这里+color.rows 当前帧在img_show的下半部分
  342. //连接前后两针匹配好的点
  343. cv::line ( img_show, cv::Point2d ( pixel_prev ( , ), pixel_prev ( , ) ), cv::Point2d ( pixel_now ( , ), pixel_now ( , ) +color.rows ), cv::Scalar ( ,, ), );
  344. }
  345. cv::imshow ( "result", img_show );
  346. cv::waitKey ( );
  347.  
  348. }
  349. return ;
  350. }
  351.  
  352. bool poseEstimationDirect ( const vector< Measurement >& measurements, cv::Mat* gray, Eigen::Matrix3f& K, Eigen::Isometry3d& Tcw )
  353. {
  354. // 初始化g2o
  355. typedef g2o::BlockSolver<g2o::BlockSolverTraits<,>> DirectBlock; // 求解的向量是6*1的 因为一元边 所以后面的1可以是其他的数字
  356. auto linearSolver = g2o::make_unique<g2o::LinearSolverDense< DirectBlock::PoseMatrixType >>();
  357. auto solver_ptr = g2o::make_unique<DirectBlock>( std::move(linearSolver) );
  358. g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg ( std::move(solver_ptr) );
  359. // DirectBlock::LinearSolverType* linearSolver = new g2o::LinearSolverDense< DirectBlock::PoseMatrixType > ();
  360. // DirectBlock* solver_ptr = new DirectBlock ( linearSolver );
  361. // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr ); // G-N
  362. // g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr ); // L-M
  363. g2o::SparseOptimizer optimizer;
  364. optimizer.setAlgorithm ( solver );
  365. optimizer.setVerbose( true );
  366.  
  367. auto pose = new g2o::VertexSE3Expmap();
  368. pose->setEstimate ( g2o::SE3Quat ( Tcw.rotation(), Tcw.translation() ) );
  369. pose->setId ( );
  370. optimizer.addVertex ( pose );
  371.  
  372. // 添加边
  373. int id=;
  374. for ( Measurement m: measurements )
  375. {
  376. auto edge = new EdgeSE3ProjectDirect (
  377. m.pos_world,
  378. K ( , ), K ( , ), K ( , ), K ( , ), gray
  379. );
  380. edge->setVertex ( , pose );//设置一元边链接的顶点
  381. edge->setMeasurement ( m.grayscale );//设置测量值 即把前一帧关键点的灰度值作为测量值 供给下一帧进行匹配计算RT
  382. edge->setInformation ( Eigen::Matrix<double,,>::Identity() );//因为误差维度是1 所以信心矩阵为1x1
  383. edge->setId ( id++ );
  384. optimizer.addEdge ( edge );
  385. }
  386. cout<<"edges in graph: "<<optimizer.edges().size() <<endl;//边的个数 实际上反应了关键点的个数
  387. optimizer.initializeOptimization();
  388. optimizer.optimize ( );
  389. Tcw = pose->estimate();
  390. }
  391.  
  392. #if BookExercise
  393. //获取小块平均灰度值
  394. // gray:灰度矩阵 x,y表示以(x,y)为中心 计算的小块的平均灰度 patchSize 表示块的半径
  395. float getPatchAverageGray(const cv::Mat &gray ,float u, float v,int patchRadius){
  396. int x = cvRound(u);
  397. int y = cvRound(v);
  398. if( (patchRadius < ) || ( (*patchRadius+) > ) ){
  399. std::cout<<"Error:请修改PATCH_RADIUS为指定值1 or 2! "<<std::endl;
  400. exit();
  401. }
  402. float grayscale = 0.0;
  403. // y - patchRadius;//代表y坐标
  404. // x - patchRadius;//代表x坐标
  405. for (int j = y-patchRadius; j <= y+patchRadius ; ++j)
  406. for(auto i = x-patchRadius;i<= (x+patchRadius); ++i){
  407. grayscale += float ( gray.ptr<uchar> (j)[i] );
  408. }
  409. grayscale/= ( (*patchRadius + )*(*patchRadius +) );
  410. return grayscale;
  411. }
  412. #endif

欢迎大家关注我的微信公众号「佛系师兄」,里面有关于 Ceres 以及 OpenCV 等更多技术文章。

比如

反复研究好几遍,我才发现关于 CMake 变量还可以这样理解!

更多好的文章会优先在里面不定期分享!打开微信客户端,扫描下方二维码即可关注!

视觉slam十四讲第8章课后习题3+稀疏直接法程序注释的更多相关文章

  1. 视觉slam十四讲第七章课后习题6

    版权声明:本文为博主原创文章,转载请注明出处: http://www.cnblogs.com/newneul/p/8545450.html 6.在PnP优化中,将第一个相机的观测也考虑进来,程序应如何 ...

  2. 视觉slam十四讲第七章课后习题7

    版权声明:本文为博主原创文章,转载请注明出处:http://www.cnblogs.com/newneul/p/8544369.html  7.题目要求:在ICP程序中,将空间点也作为优化变量考虑进来 ...

  3. 浅读《视觉SLAM十四讲:从理论到实践》--操作1--初识SLAM

    下载<视觉SLAM十四讲:从理论到实践>源码:https://github.com/gaoxiang12/slambook 第二讲:初识SLAM 2.4.2 Hello SLAM(书本P2 ...

  4. 高博-《视觉SLAM十四讲》

    0 讲座 (1)SLAM定义 对比雷达传感器和视觉传感器的优缺点(主要介绍视觉SLAM) 单目:不知道尺度信息 双目:知道尺度信息,但测量范围根据预定的基线相关 RGBD:知道深度信息,但是深度信息对 ...

  5. 《视觉SLAM十四讲》第2讲

    目录 一 视觉SLAM中的传感器 二 经典视觉SLAM框架 三 SLAM问题的数学表述 注:原创不易,转载请务必注明原作者和出处,感谢支持! 本讲主要内容: (1) 视觉SLAM中的传感器 (2) 经 ...

  6. 《视觉SLAM十四讲》第1讲

    目录 一 视觉SLAM 注:原创不易,转载请务必注明原作者和出处,感谢支持! 一 视觉SLAM 什么是视觉SLAM? SLAM是Simultaneous Localization and Mappin ...

  7. 视觉SLAM十四讲:从理论到实践 两版 PDF和源码

    视觉SLAM十四讲:从理论到实践 第一版电子版PDF 链接:https://pan.baidu.com/s/1SuuSpavo_fj7xqTYtgHBfw提取码:lr4t 源码github链接:htt ...

  8. 高翔《视觉SLAM十四讲》从理论到实践

    目录 第1讲 前言:本书讲什么:如何使用本书: 第2讲 初始SLAM:引子-小萝卜的例子:经典视觉SLAM框架:SLAM问题的数学表述:实践-编程基础: 第3讲 三维空间刚体运动 旋转矩阵:实践-Ei ...

  9. 《视觉SLAM十四讲》学习日志(二)——初识SLAM

    小萝卜机器人的例子: 就像这种机器人,它的下面有一组轮子,脑袋上有相机(眼睛),为了让它能够探索一个房间,它需要知道: 1.我在哪——定位 2.周围环境怎么样——建图 定位和建图可以理解成感知的 &q ...

随机推荐

  1. java之斗地主

    hashmap集合+ArrayList集合+Collections集合工具类shuffle()和sort()hashmap中get(key).put(key/value)Arraylist中的add( ...

  2. Codeforces Round #519 by Botan Investments(前五题题解)

    开个新号打打codeforces(以前那号玩废了),结果就遇到了这么难一套.touristD题用了map,被卡掉了(其实是对cf的评测机过分自信),G题没过, 700多行代码,码力惊人.关键是这次to ...

  3. Activity启动过程源码分析(Android 8.0)

    Activity启动过程源码分析 本文来Activity的启动流程,一般我们都是通过startActivity或startActivityForResult来启动目标activity,那么我们就由此出 ...

  4. TensorFlow——常见张量操作的API函数

    1.张量 张量可以说是TensorFlow的标志,因为整个框架的名称TensorFlow就是张量流的意思,全面的认识一下张量.在TensorFlow程序使用tensor数据结构来代表所有的数据,在计算 ...

  5. Java 中级 学习笔记 2 JVM GC 垃圾回收与算法

    前言 在上一节的学习中,已经了解到了关于JVM 内存相关的内容,比如JVM 内存的划分,以及JDK8当中对于元空间的定义,最后就是字符串常量池等基本概念以及容易混淆的内容,我们都已经做过一次总结了.不 ...

  6. P2756 飞行员配对方案问题 二分图匹配 匈牙利算法

    题目背景 第二次世界大战时期.. 题目描述 英国皇家空军从沦陷国征募了大量外籍飞行员.由皇家空军派出的每一架飞机都需要配备在航行技能和语言上能互相配合的2 名飞行员,其中1 名是英国飞行员,另1名是外 ...

  7. SBT与Play配置文件

    1. 配置文件类JSON格式,符合SCALA语法规范2. :=是最常用的方法,其作用就是将key设置成expression的值,相同的key如果被多次赋值,则后面的值会覆盖掉前面的值.适用于简单类型的 ...

  8. spring boot+spring security 使用随笔

    本人最近接受的新任务是从零搭一个管理系统的权限管理模块,从零开始学习了spring security,已完成绝大部分设计和开发,和大家分享一些学习和开发心得. 首先是数据库的设计,这里是 按照产品的需 ...

  9. 01.flask pycharm开启debug模式

    代码照旧

  10. Java入门 - 语言基础 - 09.循环结构

    原文地址:http://www.work100.net/training/java-loop.html 更多教程:光束云 - 免费课程 循环结构 序号 文内章节 视频 1 概述 2 while循环 3 ...