diff --git a/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx b/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx index 2777f22158d..1a64520becd 100644 --- a/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx +++ b/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx @@ -60,6 +60,9 @@ LiThresholdCalculator double tolerance; // threshold tolerance double temp; + // If there are negative values then shift the values to zero. + const double bin_min = std::min(histogram->GetBinMin(0,0), 0.0); + tolerance = 0.5; num_pixels = histogram->GetTotalFrequency(); @@ -82,6 +85,12 @@ LiThresholdCalculator typename HistogramType::IndexType local_index; histogram->GetIndex(ot, local_index); histthresh = local_index[0]; + + if( histogram->IsIndexOutOfBounds(local_index) ) + { + itkWarningMacro("Unexpected histogram index out of bounds!"); + break; + } } // Calculate the means of background and object pixels @@ -114,6 +123,11 @@ LiThresholdCalculator // //#define IS_NEG( x ) ( ( x ) < -DBL_EPSILON ) // + + // Shift the mean by the minimum to have the range start at zero, + // and avoid the log of a negative value. + mean_back -= bin_min; + mean_obj -= bin_min; temp = ( mean_back - mean_obj ) / ( std::log ( mean_back ) - std::log ( mean_obj ) ); double epsilon = itk::NumericTraits::epsilon(); @@ -127,6 +141,11 @@ LiThresholdCalculator } // Stop the iterations when the difference between the new and old threshold // values is less than the tolerance + + // Shift the result back. + new_thresh += bin_min; + + } while ( std::abs ( new_thresh - old_thresh ) > tolerance );