[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 아날로그 입출력 기본

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

공압회로 기호

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

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

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

[스마트팜] DIY 소형 에어컨 만들기 아이디어

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

Industrial Control with Relay: 파워릴레이와 범용릴레이