本節介紹數字圖像處理中的迭代法閾值分割,針對灰度圖進行自動尋找閾值。收斂證明目前未找到相關資料。
1. 迭代法閾值分割步驟
(1) 選取初始分割閾值,通常可選圖像灰度平均值 \(T\)。
(2) 根據閾值 \(T\) 將圖像像素分割為背景和前景,分別求出兩者的平均灰度 \(T_0\) 和 \(T_1\)。
(3) 計算新的閾值 \(T' = \frac{T_0 + T_1}{2}\)。
(4) 若 \(T == T'\),則迭代結束,\(T\) 即為最終閾值。否則令 \(T = T'\),轉第 (2) 步。
2. 效果

3. Python實現
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
def show(img):
if img.ndim == 2:
plt.imshow(img, cmap='gray', vmin=0, vmax=255)
else:
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()
img = cv.imread('pic/eagle500x500.jpg', 0)
T = img.mean()
while True:
t0 = img[img < T].mean()
t1 = img[img >= T].mean()
t = (t0 + t1) / 2
if abs(T - t) < 1:
break
T = t
T = int(T)
print(f"Best threshold = {T}")
th, img_bin = cv.threshold(img, T, 255, 0)
show(img_bin)
說明:
- 未經許可,謝絕轉載。
- 本教程為《數字圖像處理Python OpenCV實戰》的配套代碼相關內容。
免費視頻教程為0-6章(標題號≤6),可在此處點擊觀看。
所有課件及源代碼可在此處下載:
鏈接:https://pan.baidu.com/s/198PySe_vebO3e06idHSQ6g
提取碼:11o4
有問題可在QQ群(1079300899)指出,進群答案:數字圖像處理。在本文評論指出可能導致回復很晚。