In the application of computer vision, it is often used to extract a straight line of the exact position of such work. It is necessary to use a straight line fitting method.
Here, I also put a code that calculates the best fit line using the least squares method.
This code I used to learn "machine vision algorithm and application (bilingual edition)" [German] Stig (Steger C), Yang Shaolong and other translation of the book when written. All formula derivation is 3.8.1 in the book, it is more useful.
Difference from a unary linear regression algorithm: The unary linear regression algorithm assumes that X is error-free and only Y has errors. This algorithm assumes that the X Y-coordinate error of each point is normally distributed according to the 0-mean value. Therefore, in the application of computer vision is better than the normal one-element linear regression fitting results.
#include <QVector> #include <QPoint> #include <math.h>///This code is used for Qvector and Qpoint in Qt5. However, it can be easily changed to another array type. /** * Least squares linear fitting (not a common linear regression algorithm) * Fitting a discrete point to a x + b y + c = 0 Straight line * Assuming that the x Y coordinate error of each point is normally distributed according to the 0 mean. * Difference from a unary linear regression algorithm: The unary linear regression algorithm assumes that X is error-free and only Y has errors. */BOOL Linefit (ConstQvector<qpoint> &points,Double&a,Double&b,Double&C) {intSize = Points.size ();if(Size <2) {a =0; b =0; c =0;return false; }DoubleX_mean =0;DoubleY_mean =0; for(inti =0; i < size; i++) {X_mean + = points[i].x (); Y_mean + = Points[i].y (); } x_mean/= size; Y_mean/= size;///To this point, the mean value of x y is calculated DoubleDxx =0, Dxy =0, Dyy =0; for(inti =0; i < size; i++) {Dxx + = (points[i].x ()-X_mean) * (points[i].x ()-X_mean); Dxy + = (points[i].x ()-X_mean) * (Points[i].y ()-Y_mean); Dyy + = (points[i].y ()-Y_mean) * (Points[i].y ()-Y_mean); }DoubleLambda = ((Dxx + dyy)-sqrt ((DXX-DYY) * (DXX-DYY) +4* Dxy * Dxy))/2.0;DoubleDen = sqrt (Dxy * Dxy + (lambda-dxx) * (LAMBDA-DXX)); A = Dxy/den; b = (lambda-dxx)/den; c =-A * x_mean-b * y_mean;return true;}
Straight Line Fitting algorithm