圖像閾值分割是一種廣泛應用的分割技術,利用圖像中要提取的目標區域與其背景在灰度特性上的差異,把圖像看作具有不同灰度級的兩類區域(目標區域和背景區域)的組合,選取一個比較合理的閾值,以確定圖像中每個像素點應該屬於目標區域還是背景區域,從而產生相應的二值圖像。在skimage庫中,閾值分割的功能是放在filters模塊中。我們可以手動指定一個閾值,從而來實現分割。也可以讓系統自動生成一個閾值,下面幾種方法就是用來自動生成閾值。
一 threshold_otsu
基於Otsu的閾值分割方法,函數調用格式:
skimage.filters.threshold_otsu(image, nbins=256)
參數image是指灰度圖像,返回一個閾值。
from skimage import data,filters import matplotlib.pyplot as plt image = data.camera() thresh = filters.threshold_otsu(image) #返回一個閾值
dst =(image <= thresh)*1.0 #根據閾值進行分割
plt.figure('thresh',figsize=(8,8)) plt.subplot(121) plt.title('original image') plt.imshow(image,plt.cm.gray) plt.subplot(122) plt.title('binary image') plt.imshow(dst,plt.cm.gray) plt.show()
結果如下圖所示:
二 threshold_yen
使用方法同上:
from skimage import data,filters
import matplotlib.pyplot as plt
image = data.camera()
thresh = filters.threshold_yen(image) #返回一個閾值
dst =(image <= thresh)*1.0 #根據閾值進行分割
plt.figure('thresh',figsize=(8,8))
plt.subplot(121)
plt.title('original image')
plt.imshow(image,plt.cm.gray)
plt.subplot(122)
plt.title('binary image')
plt.imshow(dst,plt.cm.gray)
plt.show()
結果如下圖所示:
三 threshold_li
使用方法同上:
from skimage import data,filters import matplotlib.pyplot as plt image = data.camera() thresh = filters.threshold_li(image) #返回一個閾值
dst =(image <= thresh)*1.0 #根據閾值進行分割
plt.figure('thresh',figsize=(8,8)) plt.subplot(121) plt.title('original image') plt.imshow(image,plt.cm.gray) plt.subplot(122) plt.title('binary image') plt.imshow(dst,plt.cm.gray) plt.show()
結果如下圖所示:
四 threshold_isodata
閾值計算方法:threshold = (image[image <= threshold].mean() +image[image > threshold].mean()) / 2.0
使用方法同上:
from skimage import data,filters import matplotlib.pyplot as plt image = data.camera() thresh = filters.threshold_isodata(image) #返回一個閾值
dst =(image <= thresh)*1.0 #根據閾值進行分割
plt.figure('thresh',figsize=(8,8)) plt.subplot(121) plt.title('original image') plt.imshow(image,plt.cm.gray) plt.subplot(122) plt.title('binary image') plt.imshow(dst,plt.cm.gray) plt.show()
結果如下圖所示:
五 threshold_adaptive
調用函數為:
skimage.filters.threshold_adaptive(image, block_size, method='gaussian')
block_size: 塊大小,指當前像素的相鄰區域大小,一般是奇數(如3,5,7。。。)
method: 用來確定自適應閾值的方法,有'mean', 'generic', 'gaussian' 和 'median'。省略時默認為gaussian
該函數直接訪問一個閾值后的圖像,而不是閾值。
from skimage import data,filters import matplotlib.pyplot as plt image = data.camera() dst = filters.threshold_adaptive(image, 15) #返回一個閾值圖像
dst1 = filters.threshold_adaptive(image, 31,'mean') #返回一個閾值圖像
dst2 = filters.threshold_adaptive(image,5,'median') #返回一個閾值圖像
plt.figure('thresh',figsize=(8,8)) plt.subplot(221) plt.title('original image') plt.imshow(image,plt.cm.gray) plt.subplot(222) plt.title('binary image 15') plt.imshow(dst,plt.cm.gray) plt.subplot(223) plt.title('binary image 31') plt.imshow(dst1,plt.cm.gray) plt.subplot(224) plt.title('binary image 5') plt.imshow(dst,plt.cm.gray) plt.show()
結果如下圖所示: