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ù)字圖像處理之圖像自動閾值分割示例的詳細內(nèi)容,更多關于python數(shù)字圖像自動閾值分割的資料請關注腳本之家其它相關文章!
相關文章
python中協(xié)程實現(xiàn)TCP連接的實例分析
在本篇文章中我們給大家分享了python中協(xié)程實現(xiàn)TCP連接的代碼示例內(nèi)容,有需要的朋友們可以跟著學習下。2018-10-10
pycharm調試功能如何實現(xiàn)跳到循環(huán)的某一步
這篇文章主要介紹了pycharm調試功能如何實現(xiàn)跳到循環(huán)的某一步問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
Python數(shù)據(jù)可視化圖實現(xiàn)過程詳解
這篇文章主要介紹了Python數(shù)據(jù)可視化圖實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
使用Python腳本對Linux服務器進行監(jiān)控的教程
這篇文章主要介紹了使用Python程序對Linux服務器進行監(jiān)控的教程,主要基于Python2.7的版本,需要的朋友可以參考下2015-04-04

