[참고]

  • 파이썬과 OpenCV를 이용한 컴퓨터 비전 학습 / 에이콘 출판 / 알렉세이 스피퀘보이, 알렉산드르 류브니코프 저 / T4 역
  • OpenCV Python 강좌 - 영상 이진화 (티스토리 멈춤보단 천천히라도) : https://webnautes.tistory.com/1254

1.Otsu 알고리즘을 사용한 이미지 이진화

  • 입력된 이미지(or 영상)를 GRAY로 변환해야 Otsu 알고리즘 적용 가능
import cv2
import numpy as np 
import matplotlib.pyplot as plt

img = cv2.VideoCapture(0)

ret, frame = img.read()

gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
       
otsu_thr, otsu_mask = cv2.threshold(gray_img, -1, 1, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
print('Estimated threshold (Otsu): ', otsu_thr)
    
plt.figure()
plt.subplot(121)
plt.axis('off')
plt.title('original')
plt.imshow(frame, cmap='gray')
plt.subplot(122)
plt.axis('off')
plt.title('Otsu threshold')
plt.imshow(otsu_mask, cmap = 'gray')
plt.tight_layout()
plt.show()

[결과]

 

2. Otsu + 가우시안 필터 

import cv2
import numpy as np 

img = cv2.VideoCapture(0)

while True:
    ret, frame = img.read()

    gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    ret, img_result1 = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)
    ret, img_result2 = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    
    img_blur = cv2.GaussianBlur(gray_img, (5,5), 0)
    ret, img_result3 = cv2.threshold(img_blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    
    k = cv2.waitKey(3) & 0xFF

    if k == 27:
        break
    
    cv2.imshow('BINARY', img_result1)
    cv2.imshow('THRESH_OTSU', img_result2)
    cv2.imshow('THRESH_OTSU + Gaussian filtering', img_result3)

img.release()
cv2.destroyAllWindows()

[결과]

 

+ Recent posts