00001 // This is gel/vdgl/vdgl_fit_line.cxx 00002 #ifdef VCL_NEEDS_PRAGMA_INTERFACE 00003 #pragma implementation 00004 #endif 00005 00006 #include "vdgl_fit_line.h" 00007 #include <vnl/vnl_vector.h> 00008 #include <vsol/vsol_point_2d.h> 00009 #include <vsol/vsol_line_2d.h> 00010 #include <vdgl/vdgl_edgel.h> 00011 #include <vdgl/vdgl_edgel_chain.h> 00012 00013 00014 // This function fits a line to the points in the edgel_chain in the least-squares sense. 00015 00016 vsol_line_2d_sptr vdgl_fit_line(vdgl_edgel_chain &chain) 00017 { 00018 int SIZE = chain.size(); 00019 vdgl_edgel ed; 00020 vdgl_edgel ed1; 00021 vdgl_edgel ed2; 00022 vnl_vector<double> x(SIZE); 00023 vnl_vector<double> y(SIZE); 00024 00025 for (int i=0;i<SIZE;i++) 00026 { 00027 ed = chain.edgel(i); 00028 x(i) = ed.get_x(); 00029 y(i) = ed.get_y(); 00030 } 00031 00032 // Denoting S_xx = sum( x(0)*x(0) + x(1) * x(1) + ......) 00033 // S_xy = sum( x(0)*y(0) + x(1) * y(1) + ......) and so on 00034 00035 double S_x,S_y,S_xx,S_yy,S_xy; 00036 00037 S_x=S_y=S_xx=S_yy=S_xy=0; 00038 00039 for (int i=0;i<SIZE;i++) 00040 { 00041 S_x = S_x + x(i) ; 00042 S_y = S_y + y(i) ; 00043 S_xy = S_xy + x(i) * y(i); 00044 S_xx = S_xx + x(i) * x(i); 00045 S_yy = S_yy + y(i) * y(i); 00046 } 00047 00048 // Solving the for the coefficients m,c 00049 00050 double m = (S_x * S_y - SIZE * S_xy) / (S_x * S_x - S_xx) ; 00051 double c = ( S_xx * S_y - S_xy * S_x) / ( SIZE * S_xx - S_x * S_x) ; 00052 00053 ed1 = chain.edgel(0); 00054 ed2 = chain.edgel(SIZE-1); 00055 00056 vsol_point_2d *x1; 00057 vsol_point_2d *x2; 00058 00059 x1 = new vsol_point_2d(ed1.get_x(), m * ed1.get_x() + c); 00060 x2 = new vsol_point_2d(ed2.get_x(), m * ed2.get_x() + c); 00061 00062 vsol_line_2d *line; 00063 00064 line = new vsol_line_2d(x1,x2); 00065 00066 vsol_line_2d_sptr myline(line); 00067 return myline; 00068 }