迭代的(最优的)阈值选择

迭代法阈值选择算法是对双峰法的改进,他首先选择一个近似的阈值T,将图像分割成两个部分,R1和R2,计算出区域R1和R2的均值u1和u2,再选择新的

阈值T=(u1+u2)/2;

重复上面的过程,直到u1和u2不在变化为止,

迭代的(最优的)阈值选择

实现前后对比:

迭代的(最优的)阈值选择迭代的(最优的)阈值选择

实现代码:

import numpy as np
import cv2

img = cv2.imread('./0.jpg', 0)
#print(img[2, 4])
max_value = np.max(img)
min_value = np.min(img)
average_value = (max_value+min_value)/2

h, w = img.shape

while True:
    fnum = 0
    bnum = 0
    fvalue = 0
    bvalue = 0
    faverage = 0
    baverage = 0
    b = 0
    
    for i in range(h):
        for j in range(w):
            if img[i, j] > average_value:
                fnum += 1
                fvalue += img[i, j]
            else:
                bnum += 1
                bvalue += img[i, j]
                
    faverage = fvalue/fnum
    baverage = bvalue/bnum
    new_average = int((faverage + baverage)/2)
    if new_average == int(average_value):
        break
    else:
        average_value = new_average
        print(new_average)

img = cv2.threshold(img, new_average, 255, cv2.THRESH_BINARY)[1]
cv2.imshow('img', img)
cv2.imwrite('9.jpg', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

上一篇:MySQL:411M行的慢速平均查询


下一篇:吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用指数衰减的学习率