Created
June 25, 2018 09:57
-
-
Save Lait-au-Cafe/b3983730606a0740bba6a8cbded0e4b0 to your computer and use it in GitHub Desktop.
Binarization with Otsu Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int getThresh() | |
{ | |
int th = 0; //ループ用の閾値 | |
double num1, num2; //画素数 | |
double sum1, sum2; //和 | |
double m1, m2; //平均 | |
double va_b; //クラス間分散の二乗 | |
double max = 0; //va_bの最大値を保存しておく変数 | |
//ヒストグラムを生成していなければ弾く | |
if (hist == null) return -1; | |
//(th=0)の処理 | |
num1 = hist[0]; | |
sum1 = hist[0] * 0; | |
m1 = num1 != 0 ? sum1 / num1 : 0; | |
num2 = 0; | |
sum2 = 0; | |
m2 = 0; | |
for (int i = 1; i < 256; i++) | |
{ | |
num2 += hist[i]; | |
sum2 += hist[i] * i; | |
} | |
m2 = num2 != 0 ? sum2 / num2 : 0; | |
va_b = (num1 * num2 * (m1 - m2) * (m1 - m2)); | |
max = va_b; | |
//Debug.Log("0:"+va_b); | |
//(th=1)以降の処理 | |
for (th = 1; th < 255; th++) | |
{ | |
num1 += hist[th]; | |
num2 -= hist[th]; | |
sum1 += hist[th] * th; | |
sum2 -= hist[th] * th; | |
m1 = num1 != 0 ? sum1 / num1 : 0; | |
m2 = num2 != 0 ? sum2 / num2 : 0; | |
va_b = (num1 * num2 * (m1 - m2) * (m1 - m2)); | |
//Debug.Log(th+":"+va_b); | |
if (max < va_b) | |
{ | |
thresh = th; | |
max = va_b; | |
} | |
} | |
return thresh; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment