Skip to content

Commit

Permalink
PERF: Use binary search for threshold in ThresholdLabelerImageFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
Leengit committed Jan 12, 2022
1 parent 007970e commit 340f6f4
Showing 1 changed file with 18 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,25 +78,28 @@ class ITK_TEMPLATE_EXPORT ThresholdLabeler
inline TOutput
operator()(const TInput & A) const
{
size_t size = m_Thresholds.size();

if (size == 0)
{
return m_LabelOffset;
}
if (A <= m_Thresholds[0])
// When there are N thresholds, they divide values into N+1 buckets, which we number
// 0, ..., N. Each bucket represents a half-open interval of values (A, B]. The
// variables low, mid, and high refer to buckets. The inclusive range [low, high]
// are the buckets that are not yet ruled out. We repeatedly bisect this range
// using the variable `mid`. In the case of ties, this method returns the lowest
// bucket index for which `A` is less than or equal to the bucket's upper limit.
size_t low = 0;
size_t high = m_Thresholds.size();
while (low < high)
{
return m_LabelOffset;
}
for (size_t i = 0; i < size - 1; ++i)
{
/* Value is in this class if it equals the upper bound. */
if (m_Thresholds[i] < A && A <= m_Thresholds[i + 1])
const size_t mid = (low + high) / 2;
if (A <= m_Thresholds[mid])
{
high = mid;
}
else
{
return static_cast<TOutput>(i + 1) + m_LabelOffset;
low = mid + 1;
}
}
return static_cast<TOutput>(size) + m_LabelOffset;
// The computed bucket index is relative to m_LabelOffset.
return static_cast<TOutput>(low) + m_LabelOffset;
}

private:
Expand Down

0 comments on commit 340f6f4

Please sign in to comment.