Getting the 5 points used by RANSAC in findHomography (OpenCV for Android)

George C picture George C · Apr 8, 2012 · Viewed 8.7k times · Source

In OpenCV for Android, the function org.opencv.Calib3d.findHomography(..) returns the homogeneous transformation matrix. For example, this only returns the homography:

Mat homography = Calib3d.findHomography(points1, points2, Calib3d.RANSAC, 0.5);

Is there a way to return the points that RANSAC actually uses from the Android OpenCV API?

Answer

Sam picture Sam · Apr 8, 2012

Update

I am not sure whether it's a new addition to OpenCV or I've just missed it, but the findHomography() function actually can give you the inliers (OpenCV 2.4.2). The last parameter, mask, which is empty by default, will be filled with ones (or 255) at the indexes of the inliers foound by RANSAC.

Mat findHomography(InputArray srcPoints, InputArray dstPoints, 
     int method=0, double ransacReprojThreshold=3, OutputArray mask=noArray() )
//                                                               ^
//                                                               |

Old answer

The points used by RANSAC to estimate the homography (called inliers in technical docs) cannot be extracted directly. They are computed internally, but then the list is deleted.

A way to extract them is to modify the findHomography function (and the corresponding RANSAC functions). But this is ugly.

Another, cleaner way is to test what point pairs in the input match th homography:

use the projectPoints(points1, homography, points1_dest) (i hope this is the function name) to apply homography to points1.

The correct function name and input arguments order is: void perspectiveTransform(InputArray src, OutputArray dst, InputArray m), in this case cv::perspectiveTransform(points1, points1_dest, homography) OpenCV Perspective Transform

use cv::distance(points1_dest, points2)

The correct function name and input arguments order is: double norm(InputArray src1, int normType=NORM_L2, InputArray mask=noArray())

possible implementation:

std::array<cv::Point2f, 1> pt1;
pt1[0] = points1_dest;
std::array<cv::Point2f, 1> pt2;
pt2[0] = points2;
distance = cv::norm(pt1,  pt2));

OpenCV norm function

Distance between two points can be also calculated using Pythagorean theorem

to see which of them are close enough to their pair in points2. The distance should be smaller or equal to min_distance^2. In your case, 0.5*0.5 = 0.25.