[iavarfilter] [Up] [iahistogram] | Automatic Thresholding Techniques |
Compute the automatic thresholding level of a gray scale image based on the Otsu method.
>>> import Numeric
>>> f = iaread('cookies.pgm')
>>> iashow(f)
(174, 314) Min= 16 Max= 205 Mean=94.752 Std=57.61
>>> (t, eta) = iaotsu(f)
>>> print 'threshold at %f, goodness=%f\n' %(t, eta)
threshold at 90.000000, goodness=0.938940
>>> iashow(f > t)
(174, 314) Min= 0 Max= 1 Mean=0.527 Std=0.50
f | f > t |
def iaotsu(f): from Numeric import product, shape, arange, cumsum, nonzero, sum n = product(shape(f)) h = 1.*iahistogram(f) / n x = arange(product(shape(h))) w0 = cumsum(h) w1 = 1 - w0 eps = 1e-10 m0 = cumsum(x * h) / (w0 + eps) mt = m0[-1] m1 = (mt - m0[0:-1]*w0[0:-1]) / w1[0:-1] sB2 = w0[0:-1] * w1[0:-1] * ((m0[0:-1] - m1)**2) v = max(sB2) t = nonzero(sB2 == v)[0] st2 = sum((x-mt)**2 * h) eta = v / st2 return t, eta
[iavarfilter] [Up] [iahistogram] | |