Cv2.adaptiveThreshold
lastmod 2023-01-09created 2023-01-053 edits
The results of cv2.threshold have one problem. Because the threshold is applied to the entire image, if shading varies within a single image, some regions end up appearing entirely white or entirely black.
To solve this problem, thresholding is done separately for each small region of the image. The function used for this is cv2.adaptiveThreshold().
Synopsis
Parameters
-
src- grayscale image -
maxValue- threshold value -
adaptiveMethod- method for calculating the thresholding value -
thresholdType- threshold type -
blockSize- size of the region to apply thresholding to -
C- value subtracted from the mean or weighted mean
Adaptive Method
- cv2.ADAPTIVE_THRESH_MEAN_C - determined by the mean value of the neighborhood
- cv2.ADAPTIVE_THRESH_GAUSSIAN_C
Example
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('images/dave.png',0)
# img = cv2.medianBlur(img,5)
ret, th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
cv2.THRESH_BINARY,15,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
cv2.THRESH_BINARY,15,2)
titles = ['Original','Global','Mean','Gaussian']
images = [img,th1,th2,th3]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
Cv2.adaptiveThreshold_-_sample.jpg
See also
Favorite site
Pages that link here