[python] 파이썬 OpenCV 4 Thresholding 샘플코드

 파이썬과 OpenCV 4를 활용하여 Thresholding 기본 개념을 알아 봅니다. 픽셀의 값은, 특정 threshold 값보다 작으면 0으로, 크면 최대값으로 변환되며 cv.threshold 함수를 이용합니다. 함수의 첫번째 매개변수는 원본 이미지이며 grayscale 형태입니다. 두번째 매개변수는 threshold 값입니다. 원본이미지의 픽셀이 threshold 값을 초과한 경우 어떤 값으로 변경할지는 세번째 매개변수를 통해 설정합니다. 네번째 매개변수는 Thresholding 타입을 의미합니다. 아래는 샘플코드입니다.


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

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

ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
ret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)
ret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC)
ret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO)
ret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV)

titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]

for i in range(6):
    plt.subplot(2,3,i+1)
    plt.imshow(images[i],'gray',vmin=0,vmax=255)
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])

plt.show()


아래는 결과입니다.


끝.

댓글

이 블로그의 인기 게시물

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

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

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

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

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

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

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

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

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

[스마트팜] 아쿠아포닉스에서 pH 제어를 자동화해보자! (Python 활용)