-
Notifications
You must be signed in to change notification settings - Fork 0
/
max_entropy_threshold.py
46 lines (37 loc) · 1.8 KB
/
max_entropy_threshold.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import numpy as np
def max_entropy_threshold(histogram):
"""
Implements Kapur-Sahoo-Wong (Maximum Entropy) thresholding method
Kapur J.N., Sahoo P.K., and Wong A.K.C. (1985) "A New Method for Gray-Level Picture Thresholding Using the Entropy
of the Histogram", Graphical Models and Image Processing, 29(3): 273-285
M. Emre Celebi
06.15.2007
Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines
2016-04-28: Adapted for Python 2.7 by Robert Metchev from Java source of MaxEntropy() in the Autothresholder plugin
http://rsb.info.nih.gov/ij/plugins/download/AutoThresholder.java
Licensed under GNU GPLv3
:param histogram: Sequence representing the histogram of the image
:return threshold: Resulting maximum entropy threshold
"""
# calculate CDF (cumulative density function)
cdf = histogram.astype(np.float).cumsum()
# find histogram's nonzero area
valid_idx = np.nonzero(histogram)[0]
first_bin = valid_idx[0]
last_bin = valid_idx[-1]
# initialize search for maximum
max_ent, threshold = 0, 0
for it in range(first_bin, last_bin + 1):
# Background (dark)
hist_range = histogram[:it + 1]
hist_range = hist_range[hist_range != 0] / cdf[it] # normalize within selected range & remove all 0 elements
tot_ent = -np.sum(hist_range * np.log(hist_range)) # background entropy
# Foreground/Object (bright)
hist_range = histogram[it + 1:]
# normalize within selected range & remove all 0 elements
hist_range = hist_range[hist_range != 0] / (cdf[last_bin] - cdf[it])
tot_ent -= np.sum(hist_range * np.log(hist_range)) # accumulate object entropy
# find max
if tot_ent > max_ent:
max_ent, threshold = tot_ent, it
return threshold