[python] 파이썬 OpenCV 4 오츠의 이진화 샘플

 파이썬과 OpenCV 4를 활용한 오츠의 이진화(Otsu's Binarization) 샘플코드입니다. 원초적인 thresholding은 threshold 상수값을 사용자가 임의로 지정해야 하지만 오츠의 이진화 방법을 사용하면 자동으로 threshold 값을 자동으로 찾아줍니다. 아래는 샘플코드입니다.


import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img = cv.imread('noisy2.png',0)

# global thresholding
ret1,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)

# 오츠 이진화
ret2,th2 = cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)

# 오츠 이진화 + 가우시안 필터
blur = cv.GaussianBlur(img,(5,5),0)
ret3,th3 = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)

# plot all the images and their histograms
images = [img, 0, th1,
          img, 0, th2,
          blur, 0, th3]
titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
          'Original Noisy Image','Histogram',"Otsu's Thresholding",
          'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]

for i in range(3):
    plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
    
plt.show()


아래는 실행결과입니다.


3번째 행에서 오츠의 이진화와 함께 노이즈 제거를 위한 가우시안 필터가 적용되어 좀 더 개선된 결과를 확인할 수 있습니다.


끝.

댓글

이 블로그의 인기 게시물

공압 속도 제어: 미터인 vs 미터아웃

[PLC] PLC 아날로그 입출력 기본

[주식] 한국거래소(KRX) 데이터 API 입문 가이드

[PLC] 절연 변압기 (Isolation Transformer)

[수학] 정규 분포란? 왜 종 모양을 띠고 있을까?

[농사] 식물의 광합성과 호흡

제너 다이오드에 저항을 연결하는 이유

[자동화] 안쓰는 안드로이드폰을 활용한 식물 성장 타임랩스 촬영

[트레이딩] 현재 주가 기준으로 기대수익률은 어떻게 계산할까?

[PLC] 래더 다이어그램과 PLC