1、FitLine函数
函数的作用:
主要用于根据二维点集或者三维点集,进行直线的拟合
2、FitLine函数的调用形式
C++: void fitLine(InputArray points, OutputArray line, int distType, double param, double reps, double aeps)
参数详解:
第一个参数: 存储点序列 第二个参数:、
拟合代码:line中存储返回值 二维空间时: line[0--3] 分别为 (vx,vy, x0,y0)其中 vx, vy 是正规化之后的斜率向量。 x0,y0 是直线经过的点。第三,distType拟合算法,其中 CV_DIST_L2 就是平常的最小二乘法第四,第五参数第六参数:推荐值是 0, 0.01, 0.01, 三维空间时: line[0--5] 分别是 (vx, vy, vz,x0, y0,z0)dist_type=CV_DIST_L2 (L2): ρ(r)=r2/2 (最简单和最快的最小二乘法)
dist_type=CV_DIST_L1 (L1): ρ(r)=r
dist_type=CV_DIST_L12 (L1-L2): ρ(r)=2•[sqrt(1+r2/2) - 1]
dist_type=CV_DIST_FAIR (Fair): ρ(r)=C2•[r/C - log(1 + r/C)], C=1.3998
dist_type=CV_DIST_WELSCH (Welsch): ρ(r)=C2/2•[1 - exp(-(r/C)2)], C=2.9846
dist_type=CV_DIST_HUBER (Huber): ρ(r)= r2/2, if r < C C•(r-C/2), otherwise; C=1.345
拟合程序:: #include <cv.h> #include <stdio.h> #include <math.h> float myLinearity(CvSeq *); int main(void) { int i; double fx[] = {0.0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1.0}; double fy[] = {3.874, 3.202, 2.781, 2.49, 2.274, 2.156, 1.934, 1.74, 1.653, 1.662}; float *line = new float[4]; float linearity=0.0f; //Sequence的容器 CvMemStorage* storage = cvCreateMemStorage(0); //三维空间的话,把CV_32FC2改为CV_32FC3、 把CvPoint2D32f 改为 CvPoint3D32f CvSeq* point_seq = cvCreateSeq( CV_32FC2, sizeof(CvSeq), sizeof(CvPoint2D32f), storage ); for (i=0; i<10; i++){ //向Sequence中追加元素 cvSeqPush(point_seq, &cvPoint2D32f(fx[i],fy[i])); } linearity = myLinearity(point_seq); cvFitLine(point_seq,CV_DIST_L2,0,0.01,0.01,line); fprintf(stdout,"v=(%f,%f),vy/vx=%f,(x,y)=(%f,%f), Linearity=%f/n",line[0],line[1],line[1]/line[0],line[2],line[3],linearity); cvClearSeq(point_seq); cvReleaseMemStorage(&storage); return 0; } //计算直线拟合度 float myLinearity(CvSeq *seq) { int i; CvPoint2D32f *p; float *x = new float[seq->total]; float *y = new float[seq->total]; float x_bar=0.0, y_bar=0.0; float u11=0.0, u20=0.0, u02=0.0; float linearity=0.0; for (i=0; i < seq->total; i++){ p=(CvPoint2D32f*)cvGetSeqElem(seq,i); x[i]=p->x; y[i]=p->y; } //x_bar, y_bar for (i=0; i < seq->total; i++){ x_bar+=x[i]; y_bar+=y[i]; } x_bar/=seq->total; y_bar/=seq->total; for (i=0; i < seq->total; i++){ u11+=((x[i]-x_bar)*(y[i]-y_bar)); u20+=pow(x[i]-x_bar,2.0f); u02+=pow(y[i]-y_bar,2.0f); } u11/=seq->total; u20/=seq->total; u02/=seq->total; //计算直线度 linearity = sqrt(4*pow(u11,2.0f)+pow(u20-u02,2.0f))/(u20+u02); return linearity; } **运行结果 v=(0.399377,-0.916787),vy/vx=-2.295543,(x,y)=(0.655900,2.376600), Linearity=0.999105