: 2가지 값을 갖는 영상으로 변환
import cv2 as cv
import numpy as np
src = cv.imread("coin.bmp", cv.IMREAD_GRAYSCALE)
H,W = src.shape[:]
output = np.zeros((H, W), src.dtype)
hist = np.zeros(256, int)
p = np.zeros(256, float)
q1 = np.zeros(256, float)
q2 = np.zeros(256, float)
mu1 = np.zeros(256, float)
mu2 = np.zeros(256, float)
sig1 = np.zeros(256, float)
sig2 = np.zeros(256, float)
sigw = np.zeros(256, float)
#1. 히스토그램 획득
for y in range(H):
for x in range(W):
k = src[y, x]
hist[k] = hist[k] + 1
#2. P 획득
for i in range(256):
p[i] = hist[i] / (H*W)
#3. Otsu algorithm
min = 21470000000
for t in range(256):
for i in range(0, t):
q1[t] = q1[t] + p[i]
for i in range(t+1, 256):
q2[t] = q2[t] + p[i]
for i in range(0, t):
mu1[t] = mu1[t] + i * (p[i] / q1[t])
for i in range(t+1, 256):
mu2[t] = mu2[t] + i * (p[i] / q2[t])
for i in range(0, t):
sig1[t] = sig1[t] + (i - mu1[t])**2 * (p[i] / q1[t])
for i in range(t+1, 256):
sig2[t] = sig2[t] + (i - mu2[t])**2 * (p[i] / q2[t])
#4. sigmaw[t] 획득
sigw[t] = (q1[t] * sig1[t])**2 + (q2[t] * sig2[t])**2
#5. 최소로 만드는 t값 계산
if(sigw[t] < min):
min = sigw[t]
mint = t
#6. 획득된 t 값을 이용해서 이진화
for y in range(H):
for x in range(W):
k = src[y, x]
if(k >= mint): output[y, x] = 255
else: output[y, x] = 0
cv.imshow("input", src)
cv.imshow("output", output)
cv.waitKey(0)