/* ImLib3D
 * Copyright (c) 2001, ULP-IPB Strasbourg.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
/*! \file Threshold.hxx */
#ifndef _Threshold_hxx
#define _Threshold_hxx

#include<ImLib3D/ImageStats.hpp>


template <class ImageType>
void
IP3D::OtsuThresholds(const ImageType& src, Mask3D& res,int nbClasses,vector<double> *pthresholds,int nbBins)
{
	res.Resize(src.Size());
	// inplace
	
	vector<float> values;
	typename ImageType::const_iteratorFast p;
	for(p=src.begin();p!=src.end();++p){values.push_back((float)*p);}

	ProbabilityDistribution dist;
	dist.SetWithSamples(values,nbBins);

	vector<double> thresholds;
	dist.OtsuThreshholds(nbClasses,thresholds);

	mprintf("OtsuThreshholds::Apply: thresholds:\n");
	for(uint i=0;i<thresholds.size();i++)
	{
		mprintf("   thresholds:%d:%f\n",i,thresholds[i]);
	}

	Mask3D::iteratorFast rp;
	for(p=src.begin(),rp=res.begin();rp!=res.end();p++,rp++)
	{
		*rp=0;
		for(uint i=0;i<thresholds.size();i++){if(*p>=thresholds[i]){*rp=i+1;}}
	}
	if(pthresholds){*pthresholds=thresholds;}
}




#endif // _Threshold_hxx
