def ostu(im):
a = im.shape[0]
b = im.shape[1]
total = a * b # 总像素数
histogram = [0 for i in range(256)] # 灰度直方图
for i in range(a):
for j in range(b):
histogram[im[i][j]] += 1
sum1 = 0
for i in range(256):
sum1 += i * histogram[i]
wB = 0
sumB = 0
max_var = 0
threshold = 0
for i in range(256):
wB += histogram[i]
if wB == 0:
continue
wF = total - wB
if wF == 0:
break
sumB += i * histogram[i]
mB = sumB / wB
mF = (sum1 - sumB) / wF
var1 = wB * wF * (mB - mF) ** 2
if var1 >= max_var:
threshold = i
max_var = var1
return threshold
具体算法描述参见大津算法 - 万维百科
|