Favicon

Thresholding (Binarization)

Peponi2/27/20255m

C#
NugetPackageOpenCvSharp4

1. Introduction

Thresholding은 이미지 프로세싱의 주요 단계 중 하나로, 객체 인식, 노이즈 제거 등에 활용된다. 주로 grayscale 이미지를 이용하여 이진화 (Binarization) 를 함으로써 특정 임계값을 기준으로 픽셀을 두 개의 그룹으로 나눈다.

OpenCV에는 thresholding을 위한 여러 방법이 준비되어 있어 상황에 맞게 thresholding을 수행할 수 있다. 이 문서에서는 OpenCvSharp4의 Cv2.Threshold(), Cv2.AdaptiveThreshold(), CvXImgProc.NiblackThreshold()를 사용하여 thresholding을 하는 방법을 간략하게 알아본다.

실습에 사용할 이미지는 다음과 같다.

Image by Gordon Johnson from Pixabay

2. Thresholding

binaryBinary
binaryInvBinaryInv
truncTrunc
tozeroTozero
tozeroInvTozeroInv
maskMask
otsuOtsu
triangleTriangle

Thresholding은 이미지 전역에 걸쳐 적용되며, 수행 가능한 타입에 대한 정보는 다음 표를 참조한다.

ThresholdTypeDescription
ThresholdTypes.Binarydst(x,y)={maxvalifsrc(x,y)>thresh0otherwise\texttt{dst} (x,y) = \begin{cases}maxval &if\enspace src(x,y) > thresh \\ 0 &otherwise\end{cases}
ThresholdTypes.BinaryInvdst(x,y)={0ifsrc(x,y)>threshmaxvalotherwise\texttt{dst} (x,y) = \begin{cases}0 &if\enspace src(x,y) > thresh \\ maxval &otherwise\end{cases}
ThresholdTypes.Truncdst(x,y)={thresholdifsrc(x,y)>threshsrc(x,y)otherwise\texttt{dst} (x,y) = \begin{cases}threshold &if\enspace src(x,y) > thresh \\ src(x,y) &otherwise\end{cases}
ThresholdTypes.Tozerodst(x,y)={src(x,y)ifsrc(x,y)>thresh0otherwise\texttt{dst} (x,y) = \begin{cases}src(x,y) &if\enspace src(x,y) > thresh \\ 0 &otherwise\end{cases}
ThresholdTypes.TozeroInvdst(x,y)={0ifsrc(x,y)>threshsrc(x,y)otherwise\texttt{dst} (x,y) = \begin{cases}0 &if\enspace src(x,y) > thresh \\ src(x,y) &otherwise\end{cases}
ThresholdTypes.Maskdst(x,y)=0\texttt{dst} (x,y) = 0
ThresholdTypes.OtsuOtsu's method 적용
ThresholdTypes.TriangleAutomatic Measurement of Sister Chromatid Exchange Frequency 논문에서 시작된 알고리즘 적용
private void Thresholding(Mat image)
{
    // Mat.Threshold(threshold, maxval, thresholdType)
    using var binary = image.Threshold(127, 255, ThresholdTypes.Binary);
    using var binaryInv = image.Threshold(127, 255, ThresholdTypes.BinaryInv);
 
    // 이하는 maxval을 설정할 필요 없음 (구동 상 의미 없는 파라미터)
    using var trunc = image.Threshold(127, 0, ThresholdTypes.Trunc);
    using var toZero = image.Threshold(127, 0, ThresholdTypes.Tozero);
    using var toZeroInv = image.Threshold(127, 0, ThresholdTypes.TozeroInv);
 
    // Mask는 모든 픽셀의 값을 0으로 만든다
    using var mask = image.Threshold(0, 0, ThresholdTypes.Mask);
 
    // Otsu, Triangle thresholding은 8bit 단일 채널 image에 대해서만 가능
    using var grayscale = image.CvtColor(ColorConversionCodes.BGR2GRAY);
 
    // Otsu, Triangle 사용 시 threshold 넣어줄 필요 없음 (최적값 자동으로 찾아줌)
    using var otsu = grayscale.Threshold(0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
    using var triangle = grayscale.Threshold(0, 255, ThresholdTypes.Binary | ThresholdTypes.Triangle);
}

3. Adaptive Thresholding

meancMeanC
gaussiancGaussianC

앞서 소개한 전역 thresholding과는 달리, Adaptive thresholding은 이미지에 대해 지역 thresholding을 적용한다.

AdaptiveThresholdTypesDescription
AdaptiveThresholdTypes.MeanCThe threshold value T(x,y)T(x,y) is a mean of the blockSize×blockSizeblockSize \times blockSize neighborhood of (x,y)C(x,y) - C
AdaptiveThresholdTypes.GaussianCThe threshold value T(x,y)T(x,y) is a weighted sum (cross-correlation with a Gaussian window) of the blockSize×blockSizeblockSize \times blockSize neighborhood of (x,y)C(x,y) - C. The default sigma (standard deviation) is used for the specified blockSize
private void AdaptiveThresholding(Mat image)
{
    // AdaptiveThresholding은 grayscale image에 대해서만 가능
    using var grayscale = image.CvtColor(ColorConversionCodes.BGR2GRAY);
 
    // Mat.AdaptiveThreshold(maxval, adaptiveThresholdType, thresholdType, blockSize, constantToSubtract)
    // ThresholdTypes는 Binary, BinaryInv만 지원
    using var meanC = grayscale.AdaptiveThreshold(255, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 5, 1);
    using var gaussianC = grayscale.AdaptiveThreshold(255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 5, 1);
}

4. Niblack thresholding

niblackNiblack
sauvolaSauvola
wolfWolf
nickNick

OpenCvSharp.XImgProcusing 선언하는 경우 CvXImgProc.NiblackThreshold() 메서드를 이용할 수 있다. 이 메서드는 Niblack의 알고리즘 또는 파생 알고리즘을 이용한 thresholding을 지원하며 OCR, 의료 이미지 등에 사용된다.

LocalBinarizationMethodsReference
LocalBinarizationMethods.NiblackThresholding algorithms: Niblack (local)
LocalBinarizationMethods.SauvolaAdaptive Document Binarization
LocalBinarizationMethods.WolfExtraction and recognition of artificial text in multimedia documents
LocalBinarizationMethods.NickComparison of niblack inspired binarization methods for ancient documents
private void NiblackThresholding(Mat image)
{
    // Grayscale image에 대해서만 가능
    using var grayscale = image.CvtColor(ColorConversionCodes.BGR2GRAY);
 
    using var niblack = new Mat();
    using var sauvola = new Mat();
    using var wolf = new Mat();
    using var nick = new Mat();
 
    // ThresholdTypes는 Binary, BinaryInv만 지원
    CvXImgProc.NiblackThreshold(grayscale, niblack, 255, ThresholdTypes.Binary, 5, 0.3);
    CvXImgProc.NiblackThreshold(grayscale, sauvola, 255, ThresholdTypes.Binary, 5, 0.3, LocalBinarizationMethods.Sauvola);
    CvXImgProc.NiblackThreshold(grayscale, wolf, 255, ThresholdTypes.Binary, 5, 0.3, LocalBinarizationMethods.Wolf);
    CvXImgProc.NiblackThreshold(grayscale, nick, 255, ThresholdTypes.Binary, 5, 0.3, LocalBinarizationMethods.Nick);
}

5. 참조 자료