fix yen blank image bug

This commit is contained in:
radioxoma
2013-12-29 21:21:06 +03:00
parent 7fec88fc82
commit dfa2ba7bcd
2 changed files with 22 additions and 7 deletions
+15 -1
View File
@@ -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()
+7 -6
View File
@@ -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()]