1 /*
2  #
3  #  File        : gaussian_fit1d.cpp
4  #                ( C++ source file )
5  #
6  #  Description : Fit a gaussian function on a set of sample points,
7  #                using the Levenberg-Marquardt algorithm.
8  #                This file is a part of the CImg Library project.
9  #                ( http://cimg.eu )
10  #
11  #  Copyright   : David Tschumperlé
12  #                ( http://tschumperle.users.greyc.fr/ )
13  #
14  #  License     : CeCILL v2.0
15  #                ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
16  #
17  #  This software is governed by the CeCILL  license under French law and
18  #  abiding by the rules of distribution of free software.  You can  use,
19  #  modify and/ or redistribute the software under the terms of the CeCILL
20  #  license as circulated by CEA, CNRS and INRIA at the following URL
21  #  "http://www.cecill.info".
22  #
23  #  As a counterpart to the access to the source code and  rights to copy,
24  #  modify and redistribute granted by the license, users are provided only
25  #  with a limited warranty  and the software's author,  the holder of the
26  #  economic rights,  and the successive licensors  have only  limited
27  #  liability.
28  #
29  #  In this respect, the user's attention is drawn to the risks associated
30  #  with loading,  using,  modifying and/or developing or reproducing the
31  #  software by the user in light of its specific status of free software,
32  #  that may mean  that it is complicated to manipulate,  and  that  also
33  #  therefore means  that it is reserved for developers  and  experienced
34  #  professionals having in-depth computer knowledge. Users are therefore
35  #  encouraged to load and test the software's suitability as regards their
36  #  requirements in conditions enabling the security of their systems and/or
37  #  data to be ensured and,  more generally, to use and operate it in the
38  #  same conditions as regards security.
39  #
40  #  The fact that you are presently reading this means that you have had
41  #  knowledge of the CeCILL license and that you accept its terms.
42  #
43 */
44 
45 #ifndef cimg_plugin
46 #define cimg_plugin "examples/gaussian_fit1d.cpp"
47 #include "CImg.h"
48 using namespace cimg_library;
49 #undef min
50 #undef max
51 
52 // Main procedure
53 //----------------
main(int argc,char ** argv)54 int main(int argc,char **argv) {
55   cimg_usage("Fit gaussian function on sample points, using Levenberg-Marquardt algorithm.");
56 
57   // Read command line arguments.
58   const char *s_params = cimg_option("-p","10,3,4","Amplitude, Mean and Std of the ground truth");
59   const unsigned int s_nb = cimg_option("-N",40,"Number of sample points");
60   const float s_noise = cimg_option("-n",10.0f,"Pourcentage of noise on the samples points");
61   const char *s_xrange = cimg_option("-x","-10,10","X-range allowed for the sample points");
62   const char *f_params = cimg_option("-p0",(char*)0,"Amplitude, Mean and Std of the first estimate");
63   const float f_lambda0 = cimg_option("-l",100.0f,"Initial damping factor");
64   const float f_dlambda = cimg_option("-dl",0.9f,"Damping attenuation");
65   float s_xmin = -10, s_xmax = 10, s_amp = 1, s_mean = 1, s_std = 1;
66   std::sscanf(s_xrange,"%f%*c%f",&s_xmin,&s_xmax);
67   std::sscanf(s_params,"%f%*c%f%*c%f",&s_amp,&s_mean,&s_std);
68 
69   // Create noisy samples of a Gaussian function.
70   const float s_std2 = 2*s_std*s_std, s_fact = s_amp/((float)std::sqrt(2*cimg::PI)*s_std);
71   CImg<> samples(s_nb,2);
72   cimg_forX(samples,i) {
73     const float
74       x = (float)(s_xmin + (s_xmax - s_xmin)*cimg::rand()),
75       y = s_fact*(float)(1 + s_noise*cimg::grand()/100)*std::exp(-cimg::sqr(x - s_mean)/s_std2);
76     samples(i,0) = x;
77     samples(i,1) = y;
78   }
79 
80   // Fit Gaussian function on the sample points and display curve iterations.
81   CImgDisplay disp(640,480,"Levenberg-Marquardt Gaussian Fitting",0);
82   float f_amp = 1, f_mean = 1, f_std = 1, f_lambda = f_lambda0;
83   if (f_params) std::sscanf(f_params,"%f%*c%f%*c%f",&f_amp,&f_mean,&f_std);
84   else {
85     const float& vmax = samples.get_shared_row(1).max();
86     float cmax = 0; samples.contains(vmax,cmax);
87     f_mean = samples((int)cmax,0);
88     f_std = (s_xmax - s_xmin)/10;
89     f_amp = vmax*(float)std::sqrt(2*cimg::PI)*f_std;
90   }
91   CImg<> beta = CImg<>::vector(f_amp,f_mean,f_std);
92   for (unsigned int iter = 0; !disp.is_closed() && !disp.is_keyQ() && !disp.is_keyESC(); ++iter) {
93 
94     // Do one iteration of the Levenberg-Marquardt algorithm.
95     CImg<> YmF(1,s_nb), J(beta.height(),s_nb);
96     const float
97       _f_amp = beta(0), _f_mean = beta(1), _f_std = beta(2),
98       _f_std2 = 2*_f_std*_f_std, _f_fact = (float)std::sqrt(2*cimg::PI)*_f_std;
99     float _f_error = 0;
100     cimg_forY(J,i) {
101       const float
102         x = samples(i,0),
103         _f_exp = std::exp(-cimg::sqr(x - _f_mean)/_f_std2),
104         delta = samples(i,1) - _f_amp*_f_exp/_f_fact;
105       YmF(i) = delta;
106       J(0,i) = _f_exp/_f_fact;
107       J(1,i) = _f_amp*_f_exp/_f_fact*(x - _f_mean)*2/_f_std2;
108       J(2,i) = _f_amp*_f_exp/_f_fact*(cimg::sqr(x - _f_mean)/(_f_std*_f_std*_f_std));
109       _f_error+=cimg::sqr(delta);
110     }
111 
112     CImg<> Jt = J.get_transpose(), M = Jt*J;
113     cimg_forX(M,x) M(x,x)*=1 + f_lambda;
114     beta+=M.get_invert()*Jt*YmF;
115     if (beta(0)<=0) beta(0) = 0.1f;
116     if (beta(2)<=0) beta(2) = 0.1f;
117     f_lambda*=f_dlambda;
118 
119     // Display fitting curves.
120     const unsigned char black[] = { 0,0,0 }, gray[] = { 228,228,228 };
121     CImg<unsigned char>(disp.width(),disp.height(),1,3,255).
122       draw_gaussfit(samples,beta(0),beta(1),beta(2),s_amp,s_mean,s_std).
123       draw_rectangle(5,7,150,100,gray,0.9f).draw_rectangle(5,7,150,100,black,1,~0U).
124       draw_text(10,10,"Iteration : %d",black,0,1,13,iter).
125       draw_text(10,25,"Amplitude : %.4g (%.4g)",black,0,1,13,beta(0),s_amp).
126       draw_text(10,40,"Mean : %.4g (%.4g)",black,0,1,13,beta(1),s_mean).
127       draw_text(10,55,"Std : %.4g (%.4g)",black,0,1,13,beta(2),s_std).
128       draw_text(10,70,"Error : %.4g",black,0,1,13,std::sqrt(_f_error)).
129       draw_text(10,85,"Lambda : %.4g",black,0,1,13,f_lambda).
130       display(disp.resize(false).wait(20));
131   }
132 
133   return 0;
134 }
135 
136 #else
137 
138 // Draw sample points, ideal and fitted gaussian curves on the instance image.
139 // (defined as a CImg plug-in function).
140 template<typename t>
draw_gaussfit(const CImg<t> & samples,const float f_amp,const float f_mean,const float f_std,const float i_amp,const float i_mean,const float i_std)141 CImg<T>& draw_gaussfit(const CImg<t>& samples,
142                        const float f_amp, const float f_mean, const float f_std,
143                        const float i_amp, const float i_mean, const float i_std) {
144   if (is_empty()) return *this;
145   const unsigned char black[] = { 0,0,0 }, green[] = { 10,155,20 }, orange[] = { 155,20,0 }, purple[] = { 200,10,200 };
146   float
147     xmin, xmax = samples.get_shared_row(0).max_min(xmin), deltax = xmax - xmin,
148     ymin, ymax = samples.get_shared_row(1).max_min(ymin), deltay = ymax - ymin;
149   xmin-=0.2f*deltax; xmax+=0.2f*deltax; ymin-=0.2f*deltay; ymax+=0.2f*deltay;
150   deltax = xmax - xmin; deltay = ymax - ymin;
151   draw_grid(64,64,0,0,false,false,black,0.3f,0x55555555,0x55555555).draw_axes(xmin,xmax,ymax,ymin,black,0.8f);
152   CImg<> nsamples(samples);
153   (nsamples.get_shared_row(0)-=xmin)*=width()/deltax;
154   (nsamples.get_shared_row(1)-=ymax)*=-height()/deltay;
155   cimg_forX(nsamples,i) draw_circle((int)nsamples(i,0),(int)nsamples(i,1),3,orange,1,~0U);
156   CImg<int> truth(width(),2), fit(width(),2);
157   const float
158     i_std2 = 2*i_std*i_std, i_fact = i_amp/((float)std::sqrt(2*cimg::PI)*i_std),
159     f_std2 = 2*f_std*f_std, f_fact = f_amp/((float)std::sqrt(2*cimg::PI)*f_std);
160   cimg_forX(*this,x) {
161     const float
162       x0 = xmin + x*deltax/width(),
163       ys0 = i_fact*std::exp(-cimg::sqr(x0 - i_mean)/i_std2),
164       yf0 = f_fact*std::exp(-cimg::sqr(x0 - f_mean)/f_std2);
165     fit(x,0) = truth(x,0) = x;
166     truth(x,1) = (int)((ymax - ys0)*height()/deltay);
167     fit(x,1) = (int)((ymax - yf0)*height()/deltay);
168   }
169   return draw_line(truth,green,0.7f,0xCCCCCCCC).draw_line(fit,purple);
170 }
171 
172 #endif
173