OpenCV Python - 影像閾值化



在數字影像處理中,閾值化是一個基於畫素強度閾值建立二值影像的過程。閾值化過程將前景畫素與背景畫素分離。

OpenCV 提供了執行**簡單、自適應**和**Otsu**閾值化的函式。

在簡單閾值化中,所有值小於閾值的畫素都設定為零,其餘畫素設定為最大畫素值。這是最簡單的閾值化形式。

cv2.threshold() 函式具有以下定義。

cv2.threshold((src, thresh, maxval, type, dst)

引數

影像閾值化的引數如下:

  • Src: 輸入陣列。
  • Dst: 輸出陣列,大小相同。
  • Thresh: 閾值。
  • Maxval: 最大值。
  • Type: 閾值型別。

閾值型別

其他閾值型別列舉如下:

序號 型別 & 函式
1

cv.THRESH_BINARY

dst(x,y) = maxval if src(x,y)>thresh 0 otherwise

2

cv.THRESH_BINARY_INV

dst(x,y)=0 if src(x,y)>thresh maxval otherwise

3

cv.THRESH_TRUNC

dst(x,y)=threshold if src(x,y)>thresh src(x,y) otherwise

4

cv.THRESH_TOZERO

dst(x,y)=src(x,y) if src(x,y)>thresh 0 otherwise

5

cv.THRESH_TOZERO_INV

dst(x,y)=0 if src(x,y)>thresh src(x,y)otherwise

這些閾值型別根據以下圖表對輸入影像進行操作:

Threshold

threshold() 函式返回使用的閾值和閾值影像。

以下程式透過將閾值設定為 127,從原始影像(灰度值從 255 到 0 的漸變)生成二值影像。

示例

使用 Matplotlib 庫將原始影像和生成的閾值二值影像並排繪製。

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('gradient.png',0)
ret,img1 = cv.threshold(img,127,255,cv.THRESH_BINARY)

plt.subplot(2,3,1),plt.imshow(img,'gray',vmin=0,vmax=255)
plt.title('Original')
plt.subplot(2,3,2),plt.imshow(img1,'gray',vmin=0,vmax=255)
plt.title('Binary')
plt.show()

輸出

Threshold Binary

自適應閾值化根據畫素周圍的小區域確定畫素的閾值。因此,可以為同一影像的不同區域獲得不同的閾值。這對於照明變化的影像提供了更好的結果。

cv2.adaptiveThreshold() 方法採用以下輸入引數:

cv.adaptiveThreshold( src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst] )

adaptiveMethod 具有以下列舉值:

  • cv.ADAPTIVE_THRESH_MEAN_C - 閾值是鄰域區域的平均值減去常數 C。

  • cv.ADAPTIVE_THRESH_GAUSSIAN_C - 閾值是鄰域值的加權高斯和減去常數 C。

示例

在下面的示例中,原始影像(messi.jpg)應用了均值和高斯自適應閾值化。

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('messi.jpg',0)
img = cv.medianBlur(img,5)
th1 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
   cv.THRESH_BINARY,11,2)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
   cv.THRESH_BINARY,11,2)
titles = ['Original', 'Mean Thresholding', 'Gaussian Thresholding']
images = [img, th1, th2]
for i in range(3):
   plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
   plt.title(titles[i])
   plt.xticks([]),plt.yticks([])
plt.show()

輸出

使用 matplotlib 繪製原始影像和自適應閾值二值影像,如下所示:

Adaptive Threshold Binary

示例

OTSU 演算法從影像直方圖自動確定閾值。我們需要除了 THRESH-BINARY 標誌外,還要傳遞 cv.THRES_OTSU 標誌。

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('messi.jpg',0)
# global thresholding
ret1,img1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
# Otsu's thresholding
ret2,img2 = cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
plt.subplot(2,2,1),plt.imshow(img,'gray',vmin=0,vmax=255)
plt.title('Original')
plt.subplot(2,2,2),plt.imshow(img1,'gray')

plt.title('Binary')
plt.subplot(2,2,3),plt.imshow(img2,'gray')
plt.title('OTSU')
plt.show()

輸出

matplotlib 的繪圖結果如下:

Image Histogram
廣告

© . All rights reserved.