FitLine函数
1、FitLine函數(shù)
函數(shù)的作用:
主要用于根據(jù)二維點集或者三維點集,進行直線的擬合
2、FitLine函數(shù)的調用形式
C++:?void?fitLine(InputArray?points, OutputArray?line, int?distType, double?param, double?reps, double?aeps)
參數(shù)詳解:
第一個參數(shù): 存儲點序列 第二個參數(shù):、 line中存儲返回值 二維空間時: line[0--3] 分別為 (vx,vy, x0,y0)其中 vx, vy 是正規(guī)化之后的斜率向量。 x0,y0 是直線經過的點。第三,distType擬合算法,其中 CV_DIST_L2 就是平常的最小二乘法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
第四,第五參數(shù)第六參數(shù):推薦值是 0, ? 0.01, ?0.01, 三維空間時: line[0--5] ?分別是 (vx, vy, vz,x0, y0,z0) 擬合代碼:
擬合程序::#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 改為 CvPoint3D32fCvSeq* 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_barfor (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
總結
- 上一篇: fitEllipse函数
- 下一篇: pointPolygonTest函数