OpenCV Python入門教程5 閾值分割

2022-04-11 15:26:04 字數 2480 閱讀 5936

灰度圖讀入

#閾值分割

ret, th = cv2.threshold(img, 127, 255, cv2.thresh_binary)

cv2.imshow(

'thresh

', th)

cv2.waitkey(0)

cv2.threshold()用來實現閾值分割,有4個引數:

理解這5種閾值方式:

#

應用5種不同的閾值方法

ret, th1 = cv2.threshold(img, 127, 255, cv2.thresh_binary)

ret, th2 = cv2.threshold(img, 127, 255, cv2.thresh_binary_inv)

ret, th3 = cv2.threshold(img, 127, 255, cv2.thresh_trunc)

ret, th4 = cv2.threshold(img, 127, 255, cv2.thresh_tozero)

ret, th5 = cv2.threshold(img, 127, 255, cv2.thresh_tozero_inv)

titles = ['

original

', '

binary

', '

binary_inv

', '

trunc

', '

tozero

', '

tozero_inv']

images =[img, th1, th2, th3, th4, th5]

#使用matplotlib顯示

#兩行三列圖

for i in range(6):

plt.subplot(2, 3, i + 1)

plt.imshow(images[i],

'gray')

plt.title(titles[i], fontsize=8)

plt.xticks(), plt.yticks()

#隱藏座標軸

plt.show()

固定閾值將整幅分成兩類值,它並不適用於明暗分布不均的。而cv2.adaptivethreshold()自適應閾值會每次取的一小部分計算閾值。這樣不同區域的閾值就不盡相同。

#

自適應閾值對比固定閾值

#固定閾值

ret, th1 = cv2.threshold(img, 127, 255, cv2.thresh_binary)

#自適應閾值

th2 =cv2.adaptivethreshold(

img, 255, cv2.adaptive_thresh_mean_c, cv2.thresh_binary, 11, 4)

th3 =cv2.adaptivethreshold(

img, 255, cv2.adaptive_thresh_gaussian_c, cv2.thresh_binary, 17, 6)

titles = ['

original

', '

global(v = 127)

', '

adaptive mean

', '

adaptve gaussian']

images =[img, th1, th2, th3]

for i in range(4):

plt.subplot(2, 2, i + 1), plt.imshow(images[i], '

gray')

plt.title(titles[i], fontsize=8)

plt.xticks(), plt.yticks()

#隱藏座標軸

cv2.adaptivethreshold()的6個引數:

adaptive_thresh_mean_c:小區域內取均值

adaptive_thresh_gaussian_c:小區域內加權求和,權重是高斯核

cv2.threshold()用來進行固定閾值分割,固定閾值分割不適用於光線不均勻的,所以用cv2.adaptivethreshold()進行自適應閾值分割。當然,對於不同可以採用的不同的閾值分割方法。

BussinessSkinForm 入門教程

bussinessskinform 入門教程 by 劉家君 qufo 工作單位 福建省 泉州鷺燕醫藥 職務 網路管理員 網名 qufo 可任意 自由發布 但不要抹去我的名字及修改其中重要內容 序 言bussinessskinform是almdev公司 出品的一套 控制項,可以方便地美化程式介面,支援...

杜教篩入門

以下主要的話都用無序列表表示。有什麼好講的?問乙個積性函式的字首和,項數到1e10。線性篩,積性函式。欽定你已經可以再 o sqrt 的複雜度內求出 sum n rfloor sum n rfloor 對於第乙個,先列舉小於 sqrt n 的i,得出這段的值 又因為 i 在一段區間內 lfloor ...

opencv python入門之二(畫素操作)

我們有時會對影象重某乙個畫素進行操作,一種方法是用opencv進行操作,另一種方法是用python中的numpy庫進行操作。首先要分享的是用opencv中的方法進行操作 讀取獲取某一點畫素值 重新設定畫素值 pix img 100,200,0 獲取 100,200 處b通道的畫素值 注意img後是中...