/*-----------------------------------------------------------------------------------------

  File        : nlmeans.h

  Description : CImg plugin that implements the non-local mean filter, as described in :

    [1] Buades, A.; Coll, B.; Morel, J.-M.: A non-local algorithm for image denoising
        IEEE Computer Society Conference on Computer Vision and Pattern Recognition, 2005. CVPR 2005.
        Volume 2,  20-25 June 2005 Page(s):60 - 65 vol. 2

    [2] Buades, A. Coll, B. and Morel, J.: A review of image denoising algorithms, with a new one.
        Multiscale Modeling and Simulation: A SIAM Interdisciplinary Journal 4 (2004) 490-530

    [3] Gasser, T. Sroka,L. Jennen Steinmetz,C. Residual variance and residual pattern nonlinear regression.
        Biometrika 73 (1986) 625-659

  Copyright   : Jerome Boulanger - http://www.irisa.fr/vista/Equipe/People/Jerome.Boulanger.html
  
  This software is governed by the CeCILL  license under French law and
  abiding by the rules of distribution of free software.  You can  use, 
  modify and/ or redistribute the software under the terms of the CeCILL
  license as circulated by CEA, CNRS and INRIA at the following URL
  "http://www.cecill.info". 
  
  As a counterpart to the access to the source code and  rights to copy,
  modify and redistribute granted by the license, users are provided only
  with a limited warranty  and the software's author,  the holder of the
  economic rights,  and the successive licensors  have only  limited
  liability. 
  
  In this respect, the user's attention is drawn to the risks associated
  with loading,  using,  modifying and/or developing or reproducing the
  software by the user in light of its specific status of free software,
  that may mean  that it is complicated to manipulate,  and  that  also
  therefore means  that it is reserved for developers  and  experienced
  professionals having in-depth computer knowledge. Users are therefore
  encouraged to load and test the software's suitability as regards their
  requirements in conditions enabling the security of their systems and/or 
  data to be ensured and,  more generally, to use and operate it in the 
  same conditions as regards security. 
  
  The fact that you are presently reading this means that you have had
  knowledge of the CeCILL license and that you accept its terms.
  
------------------------------------------------------------------------------------------*/

#ifndef CIMG_PLUGIN_NLMEANS_H
#define CIMG_PLUGIN_NLMEANS_H

//! Estimate the variance of the image using robust method
/*
  \param method = 0 : Least Median of Square,
                  1 : Least Trimmed of Square,
	          2 : Least Mean of Square.
   The variance is the square of the standard deviation.
*/
double variance_estimation(const int method=1){
  CImg<T> buf = (*this);
  int n = size();
  switch(method){
  case 0:{ // Least Median of Squares
    buf.sort();
    double med_i = buf[(int)(.5*(float)n)];
    for (int j=0;j<n;j++)
      buf[j] = fabs(buf[j]-med_i);
    buf.sort();
    double sig = 1.4828 * buf[(int)(.5*(float)n)];
    return sig*sig;
  }
  case 1:{ // Least trimmed of Squares
    for (int k=0;k<n;k++)
      buf[k] = buf[k]*buf[k];
    buf.sort();
    double a=0;
    for (int j=0;j<(int)(.5*n);j++)
      a += buf[j];
    double sig = 2.6477 * std::sqrt(a/(int)(.5*n));
    return sig*sig;
  }
  default:{ // Least mean square
    double a=0, b=0;
    for (int k=0;k<n;k++){
      a += buf[k];
      b += buf[k]*buf[k];
    }
    a /= (double) n;
    b /= (double) n;
    b -= a*a;
    return b;
  }
  }
}

//! Estimate the noise variance
/*
  \param method = 0 : Least Median of Square,
                  1 : Least Trimmed of Square,
	          2 : Least Mean of Square.
   Robustly estimatate the variance of a the noise using some pseudo-residuals.
   \see variance_estimation()
*/
double noise_variance(){
  CImg<float> residu(dimx(),dimy(),dimz(),dim);
  if (!is_empty()){
    cimg_mapXYZV(*this,x,y,z,v){
      double t2=0;
      if (x==0) t2 += (*this)(x+1,y,z,v);
      else t2 += (*this)(x-1,y,z,v);
      if ((unsigned int)x==(unsigned int)(dimx()-1)) t2 += (*this)(x-1,y,z,v);
      else t2 +=(*this)(x+1,y,z,v);
      if (y==0) t2 += (*this)(x,y+1,z,v);
      else t2 += (*this)(x,y-1,z,v);
      if ((unsigned int)y==(unsigned int)(dimy()-1)) t2 += (*this)(x,y-1,z,v);
      else t2 += (*this)(x,y+1,z,v);
      residu(x,y,z,v)=(float)
	(0.223606798*(4.*(double)(*this)(x,y,z,v)-t2));
    }
  }
  return residu.variance_estimation();
}


//! NL-Means denoising algorithm.
/**
   This is the in-place version of get_nlmean().
**/
CImg<T>& nlmeans(int patch_size=1, double lambda=15, double alpha=3, double sigma=-1, int sampling=1){
  if (!is_empty()){
    if (sigma<0){
      sigma=std::sqrt(noise_variance());
#if cimg_debug==1
      fprintf(stderr,"Size of the patch                                 : %dx%d \n",
	      2*patch_size+1,2*patch_size+1);
      fprintf(stderr,"Size of window where similar patch are looked for : %dx%d \n",
	      (int)round(alpha*(2*patch_size+1)),(int)round(alpha*(2*patch_size+1)));
      fprintf(stderr,"Bandwidth of the kernel                           : %fx%f^2 \n",
	      lambda,sigma);
      fprintf(stderr,"Noise standard deviation estimated to             : %f \n",
	      sigma);
#endif
    }
    CImg<T> dest(dimx(),dimy(),dimz(),dimv(),0);
    double * uhat = new double[dimv()];
    double h2=-1./(lambda*sigma*sigma); // [Buades] notations
    //double h2=-1./(.5*lambda*lambda*sigma*sigma); // [Kervrann] notation
    if (dimz()!=1){// 3D case
      int patch_size_z=0;
      int pxi=(int)(alpha*patch_size),
	pyi=(int)(alpha*patch_size),
	pzi=2;//Define the size of the neighborhood in z
      for (int zi=0;zi<dimz();zi++){
#if cimg_debug==1
	fprintf(stderr,"\rProcessing : %3d %%",(int)((float)zi/(float)dimz()*100.));fflush(stdout);
#endif
	for (int yi=0;yi<dimy();yi++)
	  for (int xi=0;xi<dimx();xi++){
	    for (int v=0;v<dimv();v++) uhat[v] = 0;
	    float sw=0,wmax=-1;
	    for (int zj=cimg::max(0,zi-pzi);zj<cimg::min(dimz(),zi+pzi+1);zj++)
	      for (int yj=cimg::max(0,yi-pyi);yj<cimg::min(dimy(),yi+pyi+1);yj++)
		for (int xj=cimg::max(0,xi-pxi);xj<cimg::min(dimx(),xi+pxi+1);xj++){
		  double d = 0;
		  int n = 0;
		  if (xi!=xj && yi!=yj && zi!=zj){
		    for (int kz=-patch_size_z;kz<patch_size_z+1;kz+=sampling){
		      int zj_ = zj+kz;
		      int zi_ = zi+kz;
		      if (zj_>=0 && zj_<dimz() && zi_>=0 && zi_<dimz())
			for (int ky=-patch_size;ky<=patch_size;ky+=sampling){
			  int yj_ = yj+ky;
			  int yi_ = yi+ky;
			  if (yj_>=0 && yj_<dimy() && yi_>=0 && yi_<dimy())
			    for (int kx=-patch_size;kx<=patch_size;kx+=sampling){
			      int xj_ = xj+kx;
			      int xi_ = xi+kx;
			      if (xj_>=0 && xj_<dimx() && xi_>=0 && xi_<dimx()){
				for (int v=0;v<dimv();v++){
				  double d1 = (*this)(xj_,yj_,zj_,v)-(*this)(xi_,yi_,zi_,v);
				  d += d1*d1;
				  n++;
				}
			      }
			    }
			}
		    }
		    double w = exp(d*h2);
		    wmax = w>wmax?w:wmax;
		    for (int v=0;v<dimv();v++) uhat[v] += w*(*this)(xj,yj,zj,v);
		    sw += w;
		  }
		}
	    // add the central pixel
	    for (int v=0;v<dimv();v++) uhat[v] += wmax*(*this)(xi,yi,zi,v);
	    sw += wmax;
	    for (int v=0;v<dimv();v++) dest(xi,yi,zi,v)= (T) (uhat[v] /= sw);
	  }
      }
    }
    else{ // 2D case
      int pxi=(int)(alpha*patch_size),pyi=(int)(alpha*patch_size);//Define the size of the neighborhood
      for (int yi=0;yi<dimy();yi++){
#if cimg_debug==1
	fprintf(stderr,"\rProcessing : %3d %%",(int)((float)yi/(float)dimy()*100.));fflush(stdout);
#endif
	for (int xi=0;xi<dimx();xi++){
	for (int v=0;v<dimv();v++) uhat[v] = 0;
	float sw=0,wmax=-1;
	for (int yj=cimg::max(0,yi-pyi);yj<cimg::min(dimy(),yi+pyi+1);yj++){
	  for (int xj=cimg::max(0,xi-pxi);xj<cimg::min(dimx(),xi+pxi+1);xj++){
	    double d = 0;
	    int n = 0;
	    if (!(xi==xj && yi==yj)){
	      for (int ky=-patch_size;ky<patch_size+1;ky+=sampling){
		int yj_ = yj+ky;
		int yi_ = yi+ky;
		if (yj_>=0 && yj_<dimy() && yi_>=0 && yi_<dimy())
		  for (int kx=-patch_size;kx<patch_size+1;kx+=sampling){
		    int xj_ = xj+kx;
		    int xi_ = xi+kx;
		    if (xj_>=0 && xj_<dimx() && xi_>=0 && xi_<dimx()){
		      for (int v=0;v<dimv();v++){
			double d1 = (*this)(xj_,yj_,v)-(*this)(xi_,yi_,v);
			d += d1*d1;
			n++;
		      }
		    }
		  }
	      }
	    }
	    double w=exp(d*h2);
	    for (int v=0;v<dimv();v++) uhat[v] += w*(*this)(xj,yj,v);
	    wmax = w>wmax?w:wmax; // Store the maximum of the weights
	    sw += w; // Compute the sum of the weights
	  }
	}
	// add the central pixel with the maximum weight
	for (int v=0;v<dimv();v++) uhat[v] += wmax*(*this)(xi,yi,v);
	sw += wmax;
	// Compute the estimate for the current pixel
	for (int v=0;v<dimv();v++) dest(xi,yi,v)= (T) (uhat[v] /= sw);
      }
    }// main loop
    }// 2d
    delete [] uhat;
    *this=dest;
#if cimg_debug==1
    fprintf(stderr,"\n"); // make a new line
#endif
  }// is empty
  return *this;
}


//! Get the result of the NL-Means denoising algorithm.
    /**
       \param patch_size = radius of the patch (1=3x3 by default)
       \param lambda = bandwidth ( 12 by default)
       \param alpha  = size of the region where similar patch are searched (3 x patch_size = 9x9 by default)
       \param sigma = noise standard deviation (-1 = estimation)
       \param sampling = sampling of the patch (1 = uses all point, 2 = uses one point on 4, etc)
       If the image has three dimensions then the patch is only in  2D.
       If the image has several channel (color images), the distance between the two patch is computed using
       all the channels.
       The greater the patch is the best is the result. Lambda is function of the size of the patch and of the size
       alpha of the region where similar path are looked for. (e.g. : p = 1, alpha=3=>lambda=15; p=2, alpha=3=>lambda=17)

       This very basic version of the Non-Local Means algorithm provides an output image which contains
       some residual noise with a relatively small variance (\f$\sigma<5$\f).

       [ A non-local algorithm for image denoising
         Buades, A.; Coll, B.; Morel, J.-M.;
         Computer Vision and Pattern Recognition, 2005. CVPR 2005. IEEE Computer Society Conference on
         Volume 2,  20-25 June 2005 Page(s):60 - 65 vol. 2 ]
    **/
CImg<T> get_nlmeans( int patch_size=1,  double lambda=15, double alpha=3 ,double sigma=-1, int sampling=1)   {
  return CImg<T>(*this).nlmeans(patch_size,lambda,alpha,sigma,sampling);
}

#endif
