根据一组点拟合曲线(需要opencv库)
matlab中跟据点拟合方程灰常容易,直接使用polyfit函数就行了。C++貌似没有直接拟合曲线的函数,在下不才,就用C++结合opencv的库函数写了个拟合曲线的函数。#include#include#includeusing namespace std;//函数功能:根据vec中存储的点的坐标拟合曲线;//vec为为存储点坐标的容器,index为存储拟合
matlab中跟据点拟合方程灰常容易,直接使用polyfit函数就行了。C++貌似没有直接拟合曲线的函数,在下不才,就用C++结合opencv的库函数写了个拟合曲线的函数。
#include <iostream>
#include <highgui.h>
#include <cv.h>
using namespace std;
//函数功能:根据vec中存储的点的坐标拟合曲线;
//vec为为存储点坐标的容器,index为存储拟合好曲线的数组,len既为拟合曲线的次数,也为数组index的长度;
void fittingCurve(vector<CvPoint2D64f> vec,double *index,int len)
{
double *px=new double [vec.size()];
double *py=new double [len*vec.size()];
int i=0;
for(vector<CvPoint2D64f>::iterator itr=vec.begin();itr!=vec.end();++itr)
{
px[i]=(*itr).x;
int j=0;
while (j<len)
{
py[len*i+j]=pow((*itr).y,double(j));
j++;
}
i++;
}
CvMat xMat=cvMat(vec.size(),1,CV_64FC1,px);
CvMat yMat=cvMat(vec.size(),len,CV_64FC1,py);
CvMat *yTransposedMat=cvCreateMat(yMat.cols,yMat.rows,CV_64FC1);
cvTranspose(&yMat,yTransposedMat);//求yMat的转置
double *a=new double [len*len];
for(int i=0;i<len*len;++i)
{
a[i]=0;
}
CvMat invMat1=cvMat(len,len,CV_64FC1,a);
cvGEMM(yTransposedMat,&yMat,1,NULL,0,&invMat1,0);//yMat的转置与yMat矩阵相乘
cvInvert(&invMat1,&invMat1,0);//求invMat的逆矩阵
double *b=new double [len];
for(int i=0;i<len;++i)
{
b[i]=0;
}
CvMat invMat2=cvMat(len,1,CV_64FC1,b);
cvGEMM(yTransposedMat,&xMat,1,NULL,0,&invMat2,0);//求yMat的转置矩阵与xMat矩阵相乘
cvGEMM(yTransposedMat,&xMat,1,NULL,0,&invMat2,0);//求yTransposedMat矩阵与xMat 矩阵的乘积
CvMat indexMat=cvMat(len,1,CV_64FC1,index);
cvGEMM(&invMat1,&invMat2,1,NULL,0,&indexMat,0);
cvReleaseMat(&yTransposedMat);
delete [] a;
delete [] b;
delete [] px;
delete [] py;
}
int main()
{
vector<CvPoint2D64f> vec;
int x[]={406,402,401,400,398,397,397,396,396,395,394,393,388,391,391,391};
int y[]={402,428,454,480,506,532,558,584,610,636,662,688,1078,1104,1130,1156};
for (int i=0;i<16;i++)
{
vec.push_back(cvPoint2D64f(x[i],y[i]));
}
double index[3];
fittingCurve(vec,index,3);
for (int i=0;i<3;++i)
{
cout<<index[i]<<endl;
}
return 0;
}
更多推荐
所有评论(0)