Fitting a line - MatLab disagrees with OpenCV

ios, matlab, opencv

Solution

MATLAB is trying to minimise the error in `y` for an given input `x` (i.e. as if `x` is your independent and `y` your dependant variable).

In this case, the line that goes through the points (10,10) and (20,20) is probably the best bet. A near vertical line that goes close to all three points with `x=20` would have a very large error if you tried to calculate a value for `y` given `x=10`.

Although I don't recognise the OpenCV syntax, I'd guess that `CV_DIST_L2` is a distance metric that means you're trying to minimise overall distance between the line and each point in the x-y plane. In that case a more vertical line which passes through the middle of the point set would be the closest.

Which is "correct" depends on what your points represent.

Problem

Take sample points (10,10), (20,0), (20,40), (20,20). In Matlab polyfit returns slope 1, but for the same data openCV fitline returns slope 10.7. From hand calculations the near vertical line (slope 10.7) is a much better least squares fit. How come we’re getting different lines from the two libraries? OpenCV code - (on iOS) ``` vector<cv::Point> vTestPoints; vTestPoints.push_back(cv::Point( 10, 10 )); vTestPoints.push_back(cv::Point( 20, 0 )); vTestPoints.push_back(cv::Point( 20, 40 )); vTestPoints.push_back(cv::Point( 20, 20 )); Mat cvTest = Mat(vTestPoints); cv::Vec4f testWeight; fitLine( cvTest, testWeight, CV_DIST_L2, 0, 0.01, 0.01); NSLog(@"Slope: %.2f",testWeight[1]/testWeight[0]); ``` xcode Log shows ``` 2014-02-12 16:14:28.109 Application[3801:70b] Slope: 10.76 ``` Matlab code ``` >> px px =  10 20 20 20 >> py py = 10 0 20 40 >> polyfit(px,py,1) ans = 1.0000e+000 -2.7733e-014 ```

Original source