Skip to content

Instantly share code, notes, and snippets.

@al42and
Created January 19, 2016 16:07
Show Gist options
  • Save al42and/c2d66f6704e024266108 to your computer and use it in GitHub Desktop.
Save al42and/c2d66f6704e024266108 to your computer and use it in GitHub Desktop.
Kittler-Illingworth Thresholding
import numpy as np
def Kittler(im, out):
"""
The reimplementation of Kittler-Illingworth Thresholding algorithm by Bob Pepin
Works on 8-bit images only
Original Matlab code: https://www.mathworks.com/matlabcentral/fileexchange/45685-kittler-illingworth-thresholding
Paper: Kittler, J. & Illingworth, J. Minimum error thresholding. Pattern Recognit. 19, 41–47 (1986).
"""
h,g = np.histogram(im.ravel(),256,[0,256])
h = h.astype(np.float)
g = g.astype(np.float)
g = g[:-1]
c = np.cumsum(h)
m = np.cumsum(h * g)
s = np.cumsum(h * g**2)
sigma_f = np.sqrt(s/c - (m/c)**2)
cb = c[-1] - c
mb = m[-1] - m
sb = s[-1] - s
sigma_b = np.sqrt(sb/cb - (mb/cb)**2)
p = c / c[-1]
v = p * np.log(sigma_f) + (1-p)*np.log(sigma_b) - p*np.log(p) - (1-p)*np.log(1-p)
v[~np.isfinite(v)] = np.inf
idx = np.argmin(v)
t = g[idx]
out[:,:] = 0
out[im >= t] = 255
@al42and
Copy link
Author

al42and commented Feb 18, 2020

Can you please let know what to pass in the "out" argument to the function?

An empty array of the same size and type as im. So, you can call it like:

img = <your grayscale input image as integer 2D array>
img_thresholded = np.empty_like(img)
Kittler(img, img_thresholded)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment