From dfa2ba7bcd2946d2377336b4f71f95fa4926b44e Mon Sep 17 00:00:00 2001 From: radioxoma Date: Sun, 29 Dec 2013 21:21:06 +0300 Subject: [PATCH] fix yen blank image bug --- skimage/filter/tests/test_thresholding.py | 16 +++++++++++++++- skimage/filter/thresholding.py | 13 +++++++------ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/skimage/filter/tests/test_thresholding.py b/skimage/filter/tests/test_thresholding.py index 0edfe4e7..d4fc36ed 100644 --- a/skimage/filter/tests/test_thresholding.py +++ b/skimage/filter/tests/test_thresholding.py @@ -43,10 +43,19 @@ class TestSimpleImage(): assert threshold_yen(image) == 127 def test_yen_binary(self): - image = np.zeros([2,256], dtype='uint8') + image = np.zeros([2,256], dtype=np.uint8) image[0] = 255 assert threshold_yen(image) < 1 + def test_yen_blank_zero(self): + image = np.zeros((5, 5), dtype=np.uint8) + assert threshold_yen(image) == 0 + + def test_yen_blank_max(self): + image = np.empty((5, 5), dtype=np.uint8) + image.fill(255) + assert threshold_yen(image) == 255 + def test_threshold_adaptive_generic(self): def func(arr): return arr.sum() / arr.shape[0] @@ -124,5 +133,10 @@ def test_yen_coins_image_as_float(): assert 0.43 < threshold_yen(coins) < 0.44 +def test_yen_camera_image(): + camera = skimage.img_as_ubyte(data.camera()) + assert 197 < threshold_yen(camera) < 199 + + if __name__ == '__main__': np.testing.run_module_suite() diff --git a/skimage/filter/thresholding.py b/skimage/filter/thresholding.py index 2ce8a3e1..c5c060e1 100644 --- a/skimage/filter/thresholding.py +++ b/skimage/filter/thresholding.py @@ -172,15 +172,16 @@ def threshold_yen(image, nbins=256): >>> binary = image <= thresh """ hist, bin_centers = histogram(image, nbins) - norm_histo = hist.astype(float) / hist.sum() # Probability mass function - P1 = np.cumsum(norm_histo) # Cumulative normalized histogram + if bin_centers.size == 1: + return bin_centers[0] + + norm_histo = hist.astype(float) / hist.sum() # Probability mass function + P1 = np.cumsum(norm_histo) # Cumulative normalized histogram P1_sq = np.cumsum(norm_histo ** 2) # Get cumsum calculated from end of squared array: P2_sq = np.cumsum(norm_histo[::-1] ** 2)[::-1] # P2_sq indexes is shifted +1. I assume, with P1[:-1] it's help avoid '-inf' # in crit. ImageJ Yen implementation replaces those values by zero. - crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) * \ + crit = np.log(((P1_sq[:-1] * P2_sq[1:]) ** -1) * (P1[:-1] * (1.0 - P1[:-1])) ** 2) - max_crit = np.argmax(crit) - threshold = bin_centers[:-1][max_crit] - return threshold + return bin_centers[crit.argmax()]