From aabf2de96a549ea232c1eecddfe963ba1007a86d Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Sun, 25 Oct 2015 15:26:59 -0500 Subject: [PATCH] Prevent infinite loop in adapthist for low clip_limit Prevent infinite loop in adapthist Add a test that exposed the infinite loop Use better check to prevent endless loop --- skimage/exposure/_adapthist.py | 6 ++++++ skimage/exposure/tests/test_exposure.py | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/skimage/exposure/_adapthist.py b/skimage/exposure/_adapthist.py index 757dafff..62ce2ecd 100644 --- a/skimage/exposure/_adapthist.py +++ b/skimage/exposure/_adapthist.py @@ -244,6 +244,8 @@ def clip_histogram(hist, clip_limit): n_excess -= mid.size * clip_limit - mid.sum() hist[mid_mask] = clip_limit + prev_n_excess = n_excess + while n_excess > 0: # Redistribute remaining excess index = 0 while n_excess > 0 and index < hist.size: @@ -256,6 +258,10 @@ def clip_histogram(hist, clip_limit): hist[under_mask] += 1 n_excess -= under_mask.sum() index += 1 + # bail if we have not distributed any excess + if prev_n_excess == n_excess: + break + prev_n_excess = n_excess return hist diff --git a/skimage/exposure/tests/test_exposure.py b/skimage/exposure/tests/test_exposure.py index 1b9c778a..4b88b67f 100644 --- a/skimage/exposure/tests/test_exposure.py +++ b/skimage/exposure/tests/test_exposure.py @@ -213,7 +213,7 @@ def test_adapthist_grayscale(): img = np.dstack((img, img, img)) with expected_warnings(['precision loss|non-contiguous input', 'deprecated']): - adapted_old = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.01, + adapted_old = exposure.equalize_adapthist(img, 10, 9, clip_limit=0.001, nbins=128) adapted = exposure.equalize_adapthist(img, kernel_size=(57, 51), clip_limit=0.01, nbins=128) assert img.shape == adapted.shape