Skip to content

Commit e3ce370

Browse files
committed
BUG: Fix Li threshold calculator for negative image values
The histogram values are shifted by the minimum bin value to prevent taking a log of a negative number. Change-Id: I779df41f4d65e433a4c5e1613e3b9b2f40b6c95f
1 parent 8c83885 commit e3ce370

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,9 @@ LiThresholdCalculator<THistogram, TOutput>
6060
double tolerance; // threshold tolerance
6161
double temp;
6262

63+
// If there are negative values then shift the values to zero.
64+
const double bin_min = std::min(histogram->GetBinMin(0,0), 0.0);
65+
6366
tolerance = 0.5;
6467
num_pixels = histogram->GetTotalFrequency();
6568

@@ -82,6 +85,12 @@ LiThresholdCalculator<THistogram, TOutput>
8285
typename HistogramType::IndexType local_index;
8386
histogram->GetIndex(ot, local_index);
8487
histthresh = local_index[0];
88+
89+
if( histogram->IsIndexOutOfBounds(local_index) )
90+
{
91+
itkWarningMacro("Unexpected histogram index out of bounds!");
92+
break;
93+
}
8594
}
8695

8796
// Calculate the means of background and object pixels
@@ -114,6 +123,11 @@ LiThresholdCalculator<THistogram, TOutput>
114123
//
115124
//#define IS_NEG( x ) ( ( x ) < -DBL_EPSILON )
116125
//
126+
127+
// Shift the mean by the minimum to have the range start at zero,
128+
// and avoid the log of a negative value.
129+
mean_back -= bin_min;
130+
mean_obj -= bin_min;
117131
temp = ( mean_back - mean_obj ) / ( std::log ( mean_back ) - std::log ( mean_obj ) );
118132

119133
double epsilon = itk::NumericTraits<double>::epsilon();
@@ -127,6 +141,11 @@ LiThresholdCalculator<THistogram, TOutput>
127141
}
128142
// Stop the iterations when the difference between the new and old threshold
129143
// values is less than the tolerance
144+
145+
// Shift the result back.
146+
new_thresh += bin_min;
147+
148+
130149
}
131150
while ( std::abs ( new_thresh - old_thresh ) > tolerance );
132151

0 commit comments

Comments
 (0)