Search code examples
opencvtransformhomographyransac

OpenCV RANSAC returns the same transformation everytime


I am confused as to how to use the OpenCV findHomography method to compute the optimal transformation.

The way I use it is as follows:

cv::Mat h = cv::findHomography(src, dst, CV_RANSAC, 5.f);

No matter how many times I run it, I get the same transformation matrix. I thought RANSAC is supposed to randomly select a subset of points to do the fitting, so why does it return the same transformation matrix every time? Is it related to some random number initialization? How can I make this behaviour actually random?

Secondly, how can I tune the number of RANSAC iterations in this setup? Usually the number of iterations is based on inlier ratios and things like that.


Solution

  • findHomography will already give you the optimal transformation. The real question is about the meaning of optimal.

    For example, with RANSAC you'll have the model with maximum number of inliers, while with LMEDS you'll have the model with minimum median error.

    You can modify default behavior by:

    • changing the number of iteration of RANSAC by setting maxIters (max number allowed is 2000)
    • decreasing (increasing) the ransacReprojThreshold used to validate a inliers and outliers (usually between 1 and 10).

    Regarding you questions.

    No matter how many times I run it, I get the same transformation matrix.

    Probably your points are good enough that you find always the optimal model.

    I thought RANSAC is supposed to randomly select a subset of points to do the fitting

    RANSAC (RANdom SAmple Consensus) first selects a random subset, the checks if the model built with these points is good enough. If not, it selects another random subset.

    How can I make this behaviour actually random?

    I can't imagine a scenario where this would be useful, but you can randomly select 4 couples of points from src and dst, and use getPerspectiveTransform. Unless your points are perfect, you'll get a different matrix for each subset.