Created
January 27, 2014 16:25
-
-
Save shonenada/8651783 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
def binary(filename): | |
image = Image.open(filename) | |
# Convert to Gray mode | |
image = image.convert('L') | |
maxBetween = 0.0 | |
size = image.size | |
width = size[0] | |
height = size[1] | |
n = width * height | |
out = Image.new('L', size) | |
put_data = out.load() | |
data = image.load() | |
for t in xrange(256): | |
n1, n2, s1, s2 = 0, 0, 0, 0 | |
for i in xrange(width): | |
for j in xrange(height): | |
if data[i, j] < t: | |
n1 = n1 + 1 | |
s1 = s1 + data[i, j] | |
else: | |
n2 = n2 + 1 | |
s2 = s2 + data[i, j] | |
if n1 == 0 or n2 == 0: | |
continue | |
w1 = 1.0 * n1 / n | |
w2 = 1.0 * n2 / n | |
u1 = 1.0 * s1 / n1 | |
u2 = 1.0 * s2 / n2 | |
between = w1 * w2 * (u1 - u2) ** 2 | |
if n1 > 0 and n2 > 0 and maxBetween < between: | |
maxBetween = between | |
threshold = t | |
for i in xrange(width): | |
for j in xrange(height): | |
put_data[i, j] = 255 if data[i, j] > threshold else 0 | |
out.save('out.jpg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment