[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 미터아웃

NPN, PNP 트랜지스터 차이점

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

[PLC] 센서 NPN, PNP 출력 타입별 결선방법 (OMRON E2E-X 시리즈 3선식 배선)

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

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

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

사각형의 넓이 공식의 증명

[PLC] 서보 모터 브레이크 결선, 왜 릴레이 터미널을 써야 할까?

[PLC] 릴레이 자기유지 (Realy Latch or Sealing)