Mario.Tapilouw

Thursday, April 21, 2011

Linear Least Square calculation using OpenCV

Least Square method is an important tool for fitting either a plane or surface.This article will explain briefly on how we can use OpenCV for performing Linear Least Square for solving simultaneous equation. This technique can be applied for line or surface fitting.

As an example, an equation: Z = alpha * X + beta + h * delta, which has three unknown variables alpha, beta and h. The known variables are Z, X, and delta.
We have to create a matrix for the known variables according to the number of available data.
CvMat * matZ = cvCreateMat((dataLength), 1, CV_32FC1);
CvMat * matX = cvCreateMat((dataLength), 3, CV_32FC1);
CvMat * matRes = cvCreateMat(3, 1, CV_32FC1);
Then the data can be put into the matrix, assume that the data for Z are obtained from an array data:
//fill data
for(int i=0;i<dataLength;i++)
{
cvmSet(matZ, i, 0, data[i]);
cvmSet(matX, i, 0, (i*OBJSCALE));
cvmSet(matX, i, 1, 1);
cvmSet(matX, i, 2, 1);
}
after that, call the least square solver using CvSolve and if nothing is wrong with the data, the result can be directly accessed by accessing the matRes matrix
cvSolve(matX, matZ, matRes, CV_SVD);
double h = cvmGet(matRes, 2, 0);
double beta = cvmGet(matRes, 1, 0);
double alpha = cvmGet(matRes, 0, 0);
Finally, clean the memory of the matrices:
cvReleaseMat(&matZ);
cvReleaseMat(&matX);
cvReleaseMat(&matRes);
That's it. Hope it helps :)

(the source code is formatted using http://formatmysourcecode.blogspot.com/, nice stuff!)