float MeanFromHistogram( UInt *histogram, Int from, Int to )
{
float mean;
Int i, sum;
mean = 0;
sum = 0;
for( i=from; i<=to; i++ ) {
mean += i*histogram[i];
sum += histogram[i];
}
if( sum == 0 ) return 0; /* do not return errotic value when sum =0 */
mean /= (float)sum;
return mean;
}
Bool TwoMeansThresholding( UInt *histogram, Int *threshold, Int precision )
{
float m1, m2;
Int t, oldt;
Int counter;
/* initial guide */
oldt = 0;
/* if the gray scale values distribute in the whole range of possible values
t = 128 should be a good guess.
but if the image only contains very dark pixels with gray scale values lower
than 128 or if the image only contains very bright pixels with gray scale values
upper than 128, then 128 is a bad guess */
Int lower, upper;
counter = 0;
while( 1 ) {
/* compute mean of the two groups */
m1 = MeanFromHistogram( histogram, 0, t );
m2 = MeanFromHistogram( histogram, t+1, 255 );