1. 程式人生 > >python數字影象處理(11):影象自動閾值分割

python數字影象處理(11):影象自動閾值分割

影象閾值分割是一種廣泛應用的分割技術,利用影象中要提取的目標區域與其背景在灰度特性上的差異,把影象看作具有不同灰度級的兩類區域(目標區域和背景區域)的組合,選取一個比較合理的閾值,以確定影象中每個畫素點應該屬於目標區域還是背景區域,從而產生相應的二值影象。

在skimage庫中,閾值分割的功能是放在filters模組中。

我們可以手動指定一個閾值,從而來實現分割。也可以讓系統自動生成一個閾值,下面幾種方法就是用來自動生成閾值。

1、threshold_otsu

基於Otsu的閾值分割方法,函式呼叫格式:

skimage.filters.threshold_otsu(imagenbins=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()
複製程式碼

返回閾值為87,根據87進行分割得下圖:

2、threshold_yen

使用方法同上:

thresh = filters.threshold_yen(image) 

返回閾值為198,分割如下圖:

3、threshold_li

使用方法同上:

thresh = filters.threshold_li(image)

返回閾值64.5,分割如下圖:

4、threshold_isodata

閾值計算方法:

threshold = (image[image <= threshold].mean() +

image[image > threshold].mean()) / 2.0

使用方法同上:

thresh = filters.threshold_isodata(image)

返回閾值為87,因此分割效果和threshold_otsu一樣。

5、threshold_adaptive

呼叫函式為:

skimage.filters.threshold_adaptive(imageblock_sizemethod='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) #返回一個閾值影象

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()
複製程式碼

大家可以修改block_size的大小和method值來檢視更多的效果。如:

dst1 =filters.threshold_adaptive(image,31,'mean') 
dst2 =filters.threshold_adaptive(image,5,'median')

兩種效果如下: