# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import cv2
"""
迭代閾值圖像分割
迭代法是基於逼近的思想,其步驟如下:
1. 求出圖象的最大灰度值和最小灰度值,分別記爲ZMAX和ZMIN,令初始閾值T0=(ZMAX+ZMIN)/2;
2. 根據閾值TK將圖象分割爲前景和背景,分別求出兩者的平均灰度值ZO和ZB
3. 求出新閾值TK+1=(ZO+ZB)/2;
4. 若TK==TK+1,則所得即爲閾值;否則轉2,迭代計算。
"""
path = 'XXXX/'
img = cv2.imread(path + '0002cc93b.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_gray_array = np.array(img_gray)
zmax = int(img_gray_array.max())
zmin = int(img_gray_array.min())
t = (zmax + zmin)/2
while True:
img_zo = np.where(img_gray_array > t, 0, img_gray_array)#大於某個值的元素由0替代
img_bo = np.where(img_gray_array < t, 0, img_gray_array)#小於某個值的元素由0替代
zo = np.sum(img_zo)/np.sum(img_zo != 0)
bo = np.sum(img_bo)/np.sum(img_bo != 0)
k = (zo + bo)/2
if abs(t - k) < 0.01:
break;
else:
t = k
#根據最新的閾值進行分割
img_gray_array[img_gray_array > t] = 255
img_gray_array[img_gray_array <= t] = 0
plt.imshow(img_gray_array, cmap='gray')
plt.show()
【圖像處理1】迭代閾值分割
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.