python數(shù)字圖像處理之圖像自動閾值分割示例
引言
圖像閾值分割是一種廣泛應用的分割技術,利用圖像中要提取的目標區(qū)域與其背景在灰度特性上的差異,把圖像看作具有不同灰度級的兩類區(qū)域(目標區(qū)域和背景區(qū)域)的組合,選取一個比較合理的閾值,以確定圖像中每個像素點應該屬于目標區(qū)域還是背景區(qū)域,從而產(chǎn)生相應的二值圖像。
在skimage庫中,閾值分割的功能是放在filters模塊中。
我們可以手動指定一個閾值,從而來實現(xiàn)分割。也可以讓系統(tǒng)自動生成一個閾值,下面幾種方法就是用來自動生成閾值。
1、threshold_otsu
基于Otsu的閾值分割方法,函數(shù)調用格式:
skimage.filters.threshold_otsu(image, nbins=256)
參數(shù)image是指灰度圖像,返回一個閾值。
from skimage import data,filters
import matplotlib.pyplot as plt
image = data.camera()
thresh = filters.threshold_otsu(image) #返回一個閾值
dst =(image <= thresh)*1.0 #根據(jù)閾值進行分割
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,根據(jù)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
調用函數(shù)為:
skimage.filters.threshold_adaptive(image, block_size, method='gaussian')
block_size: 塊大小,指當前像素的相鄰區(qū)域大小,一般是奇數(shù)(如3,5,7。。。)
method: 用來確定自適應閾值的方法,有'mean', 'generic', 'gaussian' 和 'median'。
省略時默認為gaussian
該函數(shù)直接訪問一個閾值后的圖像,而不是閾值。
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')
兩種效果如下:

以上就是python數(shù)字圖像處理之圖像自動閾值分割示例的詳細內容,更多關于python數(shù)字圖像自動閾值分割的資料請關注腳本之家其它相關文章!
相關文章
Python?ConfigParser庫輕松讀寫INI文件實例探究
這篇文章主要為大家介紹了Python?ConfigParser庫輕松讀寫INI文件實例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01
Pandas中Series和DataFrame的索引實現(xiàn)
這篇文章主要介紹了Pandas中Series和DataFrame的索引實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-06-06

