Last active
August 29, 2015 14:09
-
-
Save ArGxento/a0bb9fa13311dd1fa9a9 to your computer and use it in GitHub Desktop.
Binarization by Ohtsu's discriminant analysis method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PIL import Image | |
import sys | |
import os | |
def binarize_try(hist, t): | |
blist = hist[:t] | |
wlist = hist[t:] | |
if len(blist) == 0 or len(blist) == 0: | |
return 0 | |
w1 = sum(blist) | |
w2 = sum(wlist) | |
m1 = w1 / len(blist) | |
m2 = w2 / len(wlist) | |
return (w1 * w2 * (m1 - m2) ** 2) / (w1 + w2) ** 2 | |
def binarize(img): | |
hist = img.histogram() | |
t_conds = [binarize_try(hist, i) for i in xrange(0, 256)] | |
t_max = 0 | |
t_max_idx = 0 | |
for i, t in enumerate(t_conds): | |
if t > t_max: | |
t_max_idx = i | |
t_max = t | |
print("t = {0}".format(t_max_idx)) | |
(img_w, img_h) = img.size | |
pix = img.load() | |
for x in xrange(0, img_w): | |
for y in xrange(0, img_h): | |
if pix[x, y] < t_max_idx: | |
pix[x, y] = 0 | |
else: | |
pix[x, y] = 255 | |
return img | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: | |
print("usage: python binarize.py image_file") | |
exit() | |
img = Image.open(sys.argv[1]) | |
img = img.convert('L') | |
img = binarize(img) | |
img.save("{0}_bin.png".format(os.path.splitext(sys.argv[1])[0]), "png") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment