Created
October 1, 2014 13:51
-
-
Save SimoneErcoli/f543b8c21e9241175230 to your computer and use it in GitHub Desktop.
Ransac Method implemented in CPP for robust keypoints estimation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cv::Mat ransacTest( | |
const std::vector<std::vector<cv::DMatch> > &matches, // Matches between two set of keypoints | |
const std::vector<cv::KeyPoint>& keypoints1, | |
const std::vector<cv::KeyPoint>& keypoints2, | |
std::vector<std::vector<cv::DMatch> > &outMatches) { | |
// Convert keypoints into Point2f | |
std::vector<cv::Point2f> points1, points2; | |
for (std::vector<std::vector<cv::DMatch> >:: | |
const_iterator it= matches.begin(); it!= matches.end(); ++it) { | |
// Get the position of left keypoints | |
float x= keypoints1[(*it)[0].queryIdx].pt.x; | |
float y= keypoints1[(*it)[0].queryIdx].pt.y; | |
points1.push_back(cv::Point2f(x,y)); | |
// Get the position of right keypoints | |
x= keypoints2[(*it)[0].trainIdx].pt.x; | |
y= keypoints2[(*it)[0].trainIdx].pt.y; | |
points2.push_back(cv::Point2f(x,y)); | |
} | |
// Compute F matrix using RANSAC | |
std::vector<uchar> inliers(points1.size(),0); | |
cv::Mat fundemental= cv::findFundamentalMat( | |
cv::Mat(points1),cv::Mat(points2), // matching points | |
inliers, // match status (inlier or outlier) | |
CV_FM_RANSAC, // RANSAC method | |
3.0, // distance to epipolar line | |
0.99); // confidence probability | |
// // extract the surviving (inliers) matches | |
std::vector<uchar>::const_iterator itIn= inliers.begin(); | |
std::vector<std::vector<cv::DMatch> >:: const_iterator itM= matches.begin(); | |
// for all matches | |
for ( ;itIn!= inliers.end(); ++itIn, ++itM) { | |
if (*itIn) { // it is a valid match | |
outMatches.push_back(*itM); | |
} | |
} | |
bool refineF = true; | |
if (refineF) { // The F matrix will be recomputed with // all accepted matches | |
// Convert keypoints into Point2f // for final F computation | |
points1.clear(); | |
points2.clear(); | |
for (std::vector<std::vector<cv::DMatch> >:: const_iterator it= outMatches.begin(); | |
it!= outMatches.end(); ++it) { | |
// Get the position of left keypoints | |
float x= keypoints1[(*it)[0].queryIdx].pt.x; | |
float y= keypoints1[(*it)[0].queryIdx].pt.y; | |
points1.push_back(cv::Point2f(x,y)); | |
// Get the position of right keypoints | |
x= keypoints2[(*it)[0].trainIdx].pt.x; | |
y= keypoints2[(*it)[0].trainIdx].pt.y; | |
points2.push_back(cv::Point2f(x,y)); | |
} | |
// Compute 8-point F from all accepted matches | |
fundemental= cv::findFundamentalMat( | |
cv::Mat(points1),cv::Mat(points2), // matches | |
CV_FM_8POINT); // 8-point method | |
} | |
return fundemental; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment