unsigned char Transform::threshold( vector<unsigned int>& histogram ){

  const unsigned int bits = histogram.size();

  // Calculate sum
  float sum = 0.0, sumb = 0.0;
  unsigned int np = 0;
  for( unsigned int n=0; n<bits; n++ ){
    np += histogram[n];
    sum += (float)n * histogram[n];
  }

  // Calculate threshold
  float wb = 0.0, wf = 0.0, mb = 0.0, mf = 0.0, max = 0.0;
  unsigned char otsu = 0;
  for( unsigned int n=0; n<bits; n++ ){
    wb += histogram[n];
    if( wb == 0.0 ) continue;

    wf = np - wb;
    if( wf == 0.0 ) break;

    sumb += (float) n * histogram[n];
    mb = sumb / wb;
    mf = (sum-sumb) / wf;
    float diff = wb * wf * (mb-mf) * (mb-mf);

    if( diff > max ){
      otsu = (unsigned char) n;
      max = diff;
    }
  }
  return otsu;
}
unsigned char Transform::threshold( vector<unsigned int>& histogram ){

  const unsigned int bits = histogram.size();

   
  float sum = 0.0, sumb = 0.0;
  unsigned int np = 0;
  for( unsigned int n=0; n<bits; n++ ){
    np += histogram[n];
    sum += (float)n * histogram[n];
  }

   
  float wb = 0.0, wf = 0.0, mb = 0.0, mf = 0.0, max = 0.0;
  unsigned char otsu = 0;
  for( unsigned int n=0; n<bits; n++ ){
    wb += histogram[n];
    if( wb == 0.0 ) continue;

    wf = np - wb;
    if( wf == 0.0 ) break;

    sumb += (float) n * histogram[n];
    mb = sumb / wb;
    mf = (sum-sumb) / wf;
    float diff = wb * wf * (mb-mf) * (mb-mf);

    if( diff > max ){
      otsu = (unsigned char) n;
      max = diff;
    }
  }
  return otsu;
}