I suddenly got a straight line fitting problem...
Math first:
a line in slope-intercept form: y = m * x + b
and we want to find m and b. Written in matrix form:
[ m ]
[ x 1 ] * [ b ] = [ y ]
So we have the matrix:
[ x1 1 ] [ y1 ]
[ x2 1 ] [ m ] [ y2 ]
[ x3 1 ] * [ b ] = [ y3 ]
[ ... ] [ ... ]
[ xn 1 ] [ yn ]
-----------------------------
A t B
First multiply both sides for AT:
A' = AT * A;
B' = AT * B;
we get
A' * t = B'
then solve for t.
here are the codes:
public static Line FitLine(List<IntPoint> points)
{
double[,] A = new double[points.Count, 2];
double[,] B = new double[points.Count, 1];
for (int i = 0; i < points.Count; ++i)
{
A[i, 0] = points[i].X;
A[i, 1] = 1;
B[i, 0] = points[i].Y;
}
double[,] AT = A.Transpose();
double[,] Ap = AT.Multiply(A);
double[,] Bp = AT.Multiply(B);
double[,] t = Matrix.Solve(Ap, Bp, true);
double m = t[0, 0];
double b = t[1, 0];
return Line.FromSlopeIntercept((float)m, (float)b);
}
Linear Least Square Fitting is an pure mathematical approach that doesn't do so much iterations.
and it provides the SAME answer EVERY TIME... unlike RANSAC...
fitting by "LUCK"... and when u're outta karma u just get a strange line landing in the middle of nowhere......
=== cut here ===
only comparing the line finding algorithms, I think they're same methods, just different representations.
I'm not such a math genius so I'm using the method that's closer to what I learned in elementary... XD