基於opencv的C++最小二乘法擬合曲線

謝了一個簡單實用的最小二乘法擬合曲線

方法/步驟

bool fittingCurve(vector<Point> &vec,int times,float *p) //輸入點,次數,輸出曲線參數

{

float *py = new float[vec.size()];

float *px = new float[times*vec.size()];

int i = 0;

Point* P = &vec[0];

for(vector<Point>::iterator itr = vec.begin();itr!=vec.end();++itr)

{

py[i] = (*itr).y;

int j=0;

while (j<times)

{

px[times*i+j] = pow(((*itr).x),float(j));

j++;

}

i++;

}

Mat X = Mat(vec.size(),times,CV_32FC1,px);

float* Xp = &(X.at<float>(0));

Mat X_T;

transpose(X,X_T);

Mat Y = Mat(vec.size(),1,CV_32FC1,py);

Mat para = ((X_T*X).inv())*X_T*Y;

for (int s = 0; s<times;s++)

{

p[s] = para.at<float>(s);

}

delete[] px;

delete[] py;

return true;

}

本文內容整理自網絡, 文中所有觀點看法不代表淘大白的立場