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


끝.

댓글

이 블로그의 인기 게시물

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

전력(kW) 계산하기 (직류, 교류 단상, 교류 삼상)

커패시터에 저장된 에너지 계산

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

[아두이노] 74HC595 시프트 레지스터 연동

3상 모터 전력에서 전류 계산하기 (How to Convert Three-Phase Power to Amps)

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

[아두이노] LED에 220옴 저항을 사용하는 이유

3선 결선식 센서의 타입 PNP, NPN

[아두이노] 가변저항(Potential Divider)과 전압분배(Voltage Divider)