Skip to content

Cv2.adaptiveThreshold

cv2.threshold의 결과를 보면 한가지 문제점이 있습니다. 임계값을 이미지 전체에 적용하여 처리하기 때문에 하나의 이미지에 음영이 다르면 일부 영역이 모두 흰색 또는 검정색으로 보여지게 됩니다.

이런 문제를 해결하기 위해서 이미지의 작은 영역별로 thresholding을 하는 것입니다. 이때 사용하는 함수가 cv2.adaptiveThreshold() 입니다.

Synopsis

cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)

Parameters

  • src - grayscale image
  • maxValue - 임계값
  • adaptiveMethod - thresholding value를 결정하는 계산 방법
  • thresholdType - threshold type
  • blockSize - thresholding을 적용할 영역 사이즈
  • C - 평균이나 가중평균에서 차감할 값

Adaptive Method

  • cv2.ADAPTIVE_THRESH_MEAN_C - 주변영역의 평균값으로 결정
  • 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