視覺里程計- 位姿


 

 注意到位姿節點之間的變換並不是位姿,之前一直有誤解;

 

一般地;

路標節點也就是觀測方程【數學形式下見】的觀測值,也就是特征點的像素坐標[u,v],或者該幀相機坐標系下的3d坐標[x,y,z];

 

位姿節點也就是運動方程【數學形式下見】的輸出值。例如:上述x1、x2、x3、X4對應位姿為:Tcw1、Tcw2、Tcw3、Tcw4。這里的Tcw表示對應幀相機坐標系->世界坐標系的變換;比如:在x1處看到了路標點p1,在x2處也看到了路標點p1(當然是通過特征匹配才知道再次看到)考慮以下兩種情況:

 

1>  x1對應第一幀,x2對應第二幀

那么x1的相機坐標系即為:世界坐標系;那么第一幀位姿我們直接初始化為:

 

第二幀我們要:通過……solvePNPransac(points3d_1, points2d_2,R,t);來求解,points3d_1對應的是世界坐標系下的3D點(在這種情形,第一幀相機坐標系也就是世界坐標系,所以第一幀相機坐標系下的3D點), points2d_2是第二幀像素點(設第二幀對應3D路標點(在第二幀相機坐標系下)為:points3d_2)。

在這里[左乘],

                                                       Tcw2 * points3d_1 = points3d_2

     同時必須知道:(假設兩幀之間的變換 T12,也就是 位姿變換

                                                                   T12 * Tcw1 = Tcw2

2> x2對應第2幀,x3對應第3幀

接着,我們再次想通過solvePNPransac(points3d_2_, points2d_3,R,t)來求解Tcw3,points3d_2_ (世界坐標系)肯定不是 points3d_2(相機坐標系),所以在第一種情形你就應該提前將points3d_2 從它所在的相機坐標系映射到世界坐標系,故:

                                                                 points3d_2_ = Tcw2.inverse() * points3d_2

我們得出流程圖如下圖:

 

觀測模型:具體見下

運動模型:具體見下

兩個模型與G2O結合了解說明;

 

位姿:位置和姿態;

對於上述位姿圖,我們假設 x1 對應參考幀 ref_(同時假設是第一幀),x2對應 當前幀curr_(同時假設是第二幀);我們通過......最后通過opencv中API solvePNPransac();求出的R|t 其實是Tcw;

Tcw指的是:當前幀與世界坐標系之間的變換;

Trw指的是:參考幀與世界坐標系之間的變換。那么待估計的兩幀之間的變換為:Tcr,構成左乘關系:

                                                                                       Tcr, s.t. Tcr * Trw = Tcw 

P_camera_curr 指的是:當前幀3D路標點 (相機坐標系)

P_world_ref      指的是:參考幀3D路標點    (世界坐標系)

                                                                               P_camera_curr = Tcw*P_world_ref

這里 opencv中的 solvePNPransac 求出來的是 T = (R|t);依據上述公式:所以你要將當前幀3D路標點轉化到世界坐標系,應該是左乘:Tcw.inverse() * P_camera_curr = P_world_ref;請看以下代碼【就是匹配,第一幀相機坐標系當作世界坐標系,第二幀就是相機坐標系,重點關注代碼 81行 - 124行】:

 

 
         
  1 #include <iostream>
  2 #include <opencv2/core/core.hpp>
  3 #include <opencv2/features2d/features2d.hpp>
  4 #include <opencv2/highgui/highgui.hpp>
  5 #include <opencv2/calib3d/calib3d.hpp>
  6 #include <Eigen/Core>
  7 #include <Eigen/Geometry>
  8 #include <g2o/core/base_vertex.h>
  9 #include <g2o/core/base_unary_edge.h>
 10 #include <g2o/core/block_solver.h>
 11 #include <g2o/core/optimization_algorithm_levenberg.h>
 12 #include <g2o/solvers/csparse/linear_solver_csparse.h>
 13 #include <g2o/types/sba/types_six_dof_expmap.h>
 14 #include <chrono>
 15 
 16 using namespace std;
 17 using namespace cv;
 18 
 19 #include"sophus\se3.h"
 20 #include"sophus\so3.h"
 21 
 22 void find_feature_matches(
 23     const Mat& img_1, const Mat& img_2,
 24     std::vector<KeyPoint>& keypoints_1,
 25     std::vector<KeyPoint>& keypoints_2,
 26     std::vector< DMatch >& matches);
 27 
 28 // 像素坐標轉相機歸一化坐標
 29 Point2d pixel2cam(const Point2d& p, const Mat& K);
 30 
 31 void bundleAdjustment(
 32 const vector<Point3f> points_3d,
 33 const vector<Point2f> points_2d,
 34 const Mat& K,
 35 Mat& R, Mat& t
 36 );
 37 
 38 int main()
 39 {
 40     //-- 讀取圖像
 41     Mat img_1 = imread("color/b.png", CV_LOAD_IMAGE_COLOR);
 42     Mat img_2 = imread("color/c.png", CV_LOAD_IMAGE_COLOR);
 43 
 44     vector<KeyPoint> keypoints_1, keypoints_2;
 45     vector<DMatch> matches;
 46     find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);
 47     cout << "一共找到了" << matches.size() << "組匹配點" << endl;
 48 
 49     // 建立3D點
 50     Mat depth_1 = imread("depth/b.pgm", CV_LOAD_IMAGE_UNCHANGED);       // 深度圖為16位無符號數,單通道圖像
 51     Mat depth_2 = imread("depth/c.pgm", CV_LOAD_IMAGE_UNCHANGED);       // 深度圖為16位無符號數,單通道圖像
 52                                                                    //Mat K = (Mat_<double>(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);
 53     Mat K = (Mat_<double>(3, 3) << 518.0, 0, 325.5, 0, 519.0, 253.5, 0, 0, 1);
 54     vector<Point3f> pts_3d1;//世界坐標點
 55     vector<Point3f> pts_3d2;
 56     vector<Point2f> pts_2d;//相機坐標系點(歸一化???)
 57                            //【注:】這里表示同一個3D點在兩幅圖中的圖二對應像素點,本來就是求世界坐標系下的r、t
 58     for (DMatch m : matches)
 59     {
 60         //取出深度值,此時彩圖和深度圖已經對齊
 61         ushort d1 = depth_1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];
 62         ushort d2 = depth_2.ptr<unsigned short>(int(keypoints_2[m.trainIdx].pt.y))[int(keypoints_2[m.trainIdx].pt.x)];
 63         if ((d1 == 0) || (d2 == 0))   // bad depth
 64             continue;
 65         float dd1 = d1 / 1.0;
 66         float dd2 = d2 / 1.0;
 67         Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K); // 相機坐標系歸一化平面:p1的形式 [x/z,y/z,1]
 68         Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);
 69         pts_3d1.push_back(Point3f(p1.x*dd1, p1.y*dd1, dd1));//乘以Z就得到形式  [x,y,z]?????左邊相機為參考,把他當作世界坐標系,確實是這樣的
 70         pts_3d2.push_back(Point3f(p2.x*dd2, p2.y*dd2, dd2));
 71         pts_2d.push_back(keypoints_2[m.trainIdx].pt);//圖二中的2D像素坐標[u,v]
 72     }
 73 
 74     cout << "3d-2d pairs: " << pts_3d1.size() << endl;
 75 
 76     Mat r, t;
 77     // 調用OpenCV 的 PnP 求解r t,可選擇EPNP,DLS等方法
 78     //solvePnP(pts_3d, pts_2d, K, Mat(), r, t, false); 
 79     //solvePnP(pts_3d1, pts_2d, K, Mat(), r, t, false, SOLVEPNP_EPNP);
 80 
 81     cv::solvePnPRansac(pts_3d1, pts_2d, K, Mat(), r, t, false, 100, 1.0, 0.99);
 82 
 83     Mat R;
 84     cv::Rodrigues(r, R); // r為旋轉向量形式,用Rodrigues公式轉換為矩陣
 85                          //RR = -R.inv();
 86     cout << "R=" << endl << R << endl;
 87     cout << "t=" << endl << t << endl;
 88     //************************************************************************************************
 89     // 李群
 90     //************************************************************************************************
 91     Sophus::SE3 T_se3 = Sophus::SE3(
 92         Sophus::SO3(r.at<double>(0, 0), r.at<double>(1, 0), r.at<double>(2, 0)),
 93         Sophus::Vector3d(t.at<double>(0, 0), t.at<double>(1, 0), t.at<double>(2, 0))
 94     );
 95     cout << "T_se3 = " << T_se3.matrix() << endl;
 96     //************************************************************************************************
 97     // 歐氏群
 98     //************************************************************************************************
 99     Eigen::Isometry3d T_Isometry3d = Eigen::Isometry3d::Identity();
100     //Eigen::AngleAxisd rot_vec(r.at<double>(0, 0), r.at<double>(1, 0), r.at<double>(2, 0));
101     Eigen::Vector3d trans(t.at<double>(0, 0), t.at<double>(1, 0), t.at<double>(2, 0));
102     Eigen::Matrix<double, 3, 3> R_;
103     R_ << R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2),
104           R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2),
105           R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2);
106     T_Isometry3d.rotate(R_);
107     T_Isometry3d.pretranslate(trans);
108     cout << " T_Isometry3d = " << T_Isometry3d.matrix() << endl;
109 
110     cout << "calling bundle adjustment" << endl;
111     bundleAdjustment(pts_3d1, pts_2d, K, R, t);
112     //************************************************************************************************
113     // 計算誤差:error = point3d_curr -( R * point3d_ref + t )
114     //************************************************************************************************
115     for (int i = 0; i < 20; i++)
116     {
117         cout << " pts_3d1 =  " << pts_3d1[i] << endl;
118         cout << " pts_3d2 =  " << pts_3d2[i] << endl;
119         cout << " error " <<
120             (Mat_<double>(3, 1) << pts_3d2[i].x, pts_3d2[i].y, pts_3d2[i].z)
121             - R*((Mat_<double>(3, 1) << pts_3d1[i].x, pts_3d1[i].y, pts_3d1[i].z)) - t
122             << endl;
123         cout << endl;
124     }
125 
126     waitKey(0);
127     return 0;
128 }
129 
130 void find_feature_matches(const Mat& img_1, const Mat& img_2,
131     std::vector<KeyPoint>& keypoints_1,
132     std::vector<KeyPoint>& keypoints_2,
133     std::vector< DMatch >& matches)
134 {
135     //-- 初始化
136     Mat descriptors_1, descriptors_2;
137     // used in OpenCV3
138     Ptr<FeatureDetector> detector = ORB::create(1000);
139     Ptr<DescriptorExtractor> descriptor = ORB::create();
140     // use this if you are in OpenCV2
141     // Ptr<FeatureDetector> detector = FeatureDetector::create ( "ORB" );
142     // Ptr<DescriptorExtractor> descriptor = DescriptorExtractor::create ( "ORB" );
143     Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming");
144     //-- 第一步:檢測 Oriented FAST 角點位置
145     detector->detect(img_1, keypoints_1);
146     detector->detect(img_2, keypoints_2);
147 
148     //-- 第二步:根據角點位置計算 BRIEF 描述子
149     descriptor->compute(img_1, keypoints_1, descriptors_1);
150     descriptor->compute(img_2, keypoints_2, descriptors_2);
151 
152     //-- 第三步:對兩幅圖像中的BRIEF描述子進行匹配,使用 Hamming 距離
153     vector<DMatch> match;
154     // BFMatcher matcher ( NORM_HAMMING );
155     matcher->match(descriptors_1, descriptors_2, match);
156 
157     //-- 第四步:匹配點對篩選
158     double min_dist = 10000, max_dist = 0;
159 
160     //找出所有匹配之間的最小距離和最大距離, 即是最相似的和最不相似的兩組點之間的距離
161     for (int i = 0; i < descriptors_1.rows; i++)
162     {
163         double dist = match[i].distance;
164         if (dist < min_dist) min_dist = dist;
165         if (dist > max_dist) max_dist = dist;
166     }
167 
168     printf("-- Max dist : %f \n", max_dist);
169     printf("-- Min dist : %f \n", min_dist);
170 
171     //當描述子之間的距離大於兩倍的最小距離時,即認為匹配有誤.但有時候最小距離會非常小,設置一個經驗值30作為下限.
172     for (int i = 0; i < descriptors_1.rows; i++)
173     {
174         if (match[i].distance <= max(2 * min_dist, 30.0))
175         {
176             matches.push_back(match[i]);
177         }
178     }
179 
180 
181 
182     Mat img_match;
183     Mat img_goodmatch;
184     drawMatches(img_1, keypoints_1, img_2, keypoints_2, match, img_match);
185     drawMatches(img_1, keypoints_1, img_2, keypoints_2, matches, img_goodmatch);
186     namedWindow("所有匹配點對", CV_WINDOW_NORMAL);
187     imshow("所有匹配點對", img_match);
188     namedWindow("優化后匹配點對", CV_WINDOW_NORMAL);
189     imshow("優化后匹配點對", img_goodmatch);
190 }
191 
192 Point2d pixel2cam(const Point2d& p, const Mat& K)// [u,v,1] - > [x/z, y/z, 1]
193 {
194     return Point2d
195     (
196         (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),
197         (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)
198     );
199 }
200 
201 
202 void bundleAdjustment(
203 const vector< Point3f > points_3d,
204 const vector< Point2f > points_2d,
205 const Mat& K,
206 Mat& R, Mat& t)
207 {
208 // 初始化g2o
209 typedef g2o::BlockSolver< g2o::BlockSolverTraits<6, 3> > Block;  // pose 維度為 6, landmark 維度為 3
210 Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // 線性方程求解器
211 Block* solver_ptr = new Block(linearSolver);     // 矩陣塊求解器
212 g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);
213 g2o::SparseOptimizer optimizer;
214 optimizer.setAlgorithm(solver);
215 
216 // vertex
217 g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose
218 Eigen::Matrix3d R_mat;
219 R_mat <<
220 R.at<double>(0, 0), R.at<double>(0, 1), R.at<double>(0, 2),
221 R.at<double>(1, 0), R.at<double>(1, 1), R.at<double>(1, 2),
222 R.at<double>(2, 0), R.at<double>(2, 1), R.at<double>(2, 2);
223 pose->setId(0);
224 pose->setEstimate(g2o::SE3Quat(
225 R_mat,
226 Eigen::Vector3d(t.at<double>(0, 0), t.at<double>(1, 0), t.at<double>(2, 0))
227 ));
228 optimizer.addVertex(pose);
229 
230 int index = 1;
231 for (const Point3f p : points_3d)   // landmarks
232 {
233 g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();
234 point->setId(index++);
235 point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));
236 point->setMarginalized(true); // g2o 中必須設置 marg 參見第十講內容
237 optimizer.addVertex(point);
238 }
239 
240 // parameter: camera intrinsics
241 g2o::CameraParameters* camera = new g2o::CameraParameters(
242 K.at<double>(0, 0), Eigen::Vector2d(K.at<double>(0, 2), K.at<double>(1, 2)), 0
243 );
244 camera->setId(0);
245 optimizer.addParameter(camera);
246 
247 // edges
248 index = 1;
249 for (const Point2f p : points_2d)
250 {
251 g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();
252 edge->setId(index);
253 edge->setVertex(0, dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(index)));
254 edge->setVertex(1, pose);
255 edge->setMeasurement(Eigen::Vector2d(p.x, p.y));
256 edge->setParameterId(0, 0);
257 edge->setInformation(Eigen::Matrix2d::Identity());
258 optimizer.addEdge(edge);
259 index++;
260 }
261 
262 chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
263 optimizer.setVerbose(true);
264 optimizer.initializeOptimization();
265 optimizer.optimize(100);
266 chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
267 chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> (t2 - t1);
268 cout << "optimization costs time: " << time_used.count() << " seconds." << endl;
269 
270 cout << endl << "after optimization:" << endl;
271 cout << "T=" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;
272 }
View Code

 這里我們只關心運動,不關心結構。換句話說,只要通過特征點成功求出了運動,我們就不再需要這幀的特征點了。這種做法當然會有缺陷,但是忽略掉數量龐大的特征點可以節省許多的計算量。然后,在 t 到 t + 1 時刻,我們又以 t 時刻為參考幀,考慮 t 到 t + 1 間的運動關系。如此往復,就得到了一條運動軌跡

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM