-
Notifications
You must be signed in to change notification settings - Fork 24
/
otsu.py
125 lines (92 loc) · 2.54 KB
/
otsu.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
Created on Mon Oct 30 12:41:30 2017
@author: mohabmes
"""
import math
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
threshold_values = {}
h = [1]
def Hist(img):
row, col = img.shape
y = np.zeros(256)
for i in range(0,row):
for j in range(0,col):
y[img[i,j]] += 1
x = np.arange(0,256)
plt.bar(x, y, color='b', width=5, align='center', alpha=0.25)
plt.show()
return y
def regenerate_img(img, threshold):
row, col = img.shape
y = np.zeros((row, col))
for i in range(0,row):
for j in range(0,col):
if img[i,j] >= threshold:
y[i,j] = 255
else:
y[i,j] = 0
return y
def countPixel(h):
cnt = 0
for i in range(0, len(h)):
if h[i]>0:
cnt += h[i]
return cnt
def wieght(s, e):
w = 0
for i in range(s, e):
w += h[i]
return w
def mean(s, e):
m = 0
w = wieght(s, e)
for i in range(s, e):
m += h[i] * i
return m/float(w)
def variance(s, e):
v = 0
m = mean(s, e)
w = wieght(s, e)
for i in range(s, e):
v += ((i - m) **2) * h[i]
v /= w
return v
def threshold(h):
cnt = countPixel(h)
for i in range(1, len(h)):
vb = variance(0, i)
wb = wieght(0, i) / float(cnt)
mb = mean(0, i)
vf = variance(i, len(h))
wf = wieght(i, len(h)) / float(cnt)
mf = mean(i, len(h))
V2w = wb * (vb) + wf * (vf)
V2b = wb * wf * (mb - mf)**2
fw = open("trace.txt", "a")
fw.write('T='+ str(i) + "\n")
fw.write('Wb='+ str(wb) + "\n")
fw.write('Mb='+ str(mb) + "\n")
fw.write('Vb='+ str(vb) + "\n")
fw.write('Wf='+ str(wf) + "\n")
fw.write('Mf='+ str(mf) + "\n")
fw.write('Vf='+ str(vf) + "\n")
fw.write('within class variance='+ str(V2w) + "\n")
fw.write('between class variance=' + str(V2b) + "\n")
fw.write("\n")
if not math.isnan(V2w):
threshold_values[i] = V2w
def get_optimal_threshold():
min_V2w = min(threshold_values.itervalues())
optimal_threshold = [k for k, v in threshold_values.iteritems() if v == min_V2w]
print 'optimal threshold', optimal_threshold[0]
return optimal_threshold[0]
image = Image.open('img.jpg').convert("L")
img = np.asarray(image)
h = Hist(img)
threshold(h)
op_thres = get_optimal_threshold()
res = regenerate_img(img, op_thres)
plt.imshow(res)
plt.savefig("otsu.jpg")