Adaptive Thresholding
: 다른 위치에 대해서 다른 thresholding을 적용하는 것
simple thresholding 을 전체적으로 다 적용하는 것은 좋은 방법이 아닐 수도 있음.
왜냐하면 위치에 따라 lightening condition이 point to point 달라질 수 있으므로 이러한 경우에는 adaptive thresholding 을 적용하는 것이 필요하다.
import cv2 as cv
import numpy as np
img = cv.imread('sudoku.png', 0)
_, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
cv.imshow('Image', img)
cv.imshow('th1', th1)
cv.waitKey(0)
cv.destroyAllWindows()
위의 코드에서 cv.thresholding을 적용하면 아래와 같은 흑백 이미지가 출력된다. 이때 이미지를 불러올 때 흑백으로 불러와야지 이후에 thresholding을 수행할 때 에러가 나지 않는다 (왜냐하면 흑백에 사용되게끔 코드가 작성이 되었기 때문이다)
위와 같은 경우에는 특정한 lightening 값 이하인 경우에는 전부 검정색으로 나타나고 그 이상에는 하얀색으로 출력된다.
위와 같이 모든 위치에 같은 임계값을 적용하는 것이 소용 없는 경우에 우리는 adaptive thresholding 기법을 사용한다.
import cv2 as cv
import numpy as np
img = cv.imread('sudoku.png', 0)
_, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
cv.imshow('Image', img)
cv.imshow('th1', th1)
cv.imshow('th2', th2)
cv.waitKey(0)
cv.destroyAllWindows()
adaptiveThresholding 함수의 인자로는
첫번째 : 이미지
두번째 : 최대 픽셀 값
세번째 : adaptive Method
네번째 : thresholding Type
다섯번째 : 블록사이즈
여섯번째 : C --> adaptive Method에 따라서 이용되는 데가 다르다.
ADAPTIVE_THRESH_MEAN_C 는
: T(x,y) 임계값 = (x,y) 블록에 인접하는 블록사이즈 * 블록사이즈의 평균 -C
the threshold value T(x,y) is a mean of the blockSize * blockSize neighborhood of (x,y) minus C
ADAPTIVE_THRESH_GAUSSIAN_C 는
: T(x,y) 임계값 = (x,y) 블록에 인접하는 블록사이즈 * 블록사이즈의 가중치 더해진 합 -C
확실히 adaptive Thresholding을 한 결과가 오리지널 이미지를 잘 threshold 해준다.
import cv2 as cv
import numpy as np
img = cv.imread('sudoku.png', 0)
_, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
th3 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
#cv.imshow('Image', img)
#cv.imshow('th1', th1)
cv.imshow('th2', th2)
cv.imshow('th3', th3)
cv.waitKey(0)
cv.destroyAllWindows()
이번에는 가우시안 thresh 방법을 이용해서 mean thresh 방법과 비교해보자. 둘의 차이가 보인다.