圖像閾值處理是實現圖像分割的一種方法,常用的閾值分割方法有簡單閾值,自適應閾值,Otsu's二值化等。
cv2.threshold()可以用來進行圖像閾值處理,cv2.threshold(src, thresh, maxval, type) 第一個參數是原圖像,第二個參數是對像素值進行分類的閾值,第三個參數是當像素值高於(小於)閾值時,應該被賦予的新的像素值,第四個參數是閾值方法。函數有兩個返回值,一個為retVal, 一個閾值化處理之后的圖像。
常用的閾值方法有:
全局閾值:
自適應閾值
當同一幅圖像不同部分具有不同的亮度時,全局閾值並不適用,此時我們會采用自適應閾值,自適應閾值會在圖像上每一個小區域計算與其對應的閾值。可以使用cv2.adaptiveThreshold()要傳入三個參數:閾值計算方法,鄰域大小,常數C, 閾值等於平均值或者加權平均值減去這個常數。
import numpy as np import cv2 from matplotlib import pyplot as plt img = cv2.imread('/home/vincent/Pictures/work/uy_gnix_iac.jpg') ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV) ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC) ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO) ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV) images = [img, thresh1, thresh2, thresh3, thresh4, thresh5] for i in range(6): plt.subplot(2,3, i+1) plt.imshow(images[i]) plt.suptitle('fixed threshold') img = cv2.imread('/home/vincent/Pictures/work/barbara.png', 0) print(img.shape) thresh6 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2) thresh7 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) ret, thresh8 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) images2 = [img, thresh6, thresh7, thresh8] plt.figure(2) for i in range(4): plt.subplot(1,4,i+1) plt.imshow(images2[i],'gray') plt.suptitle('adaptive threshold') plt.show()