Kittler二值化方法,是一种经典的基于直方图的二值化方法。由Kittler在1986年在论文“Minimum Error Thresholding”提出。
参考了ImageShop提供的C#版本(http://www.cnblogs.com/Imageshop/p/3307308.html),做了简单修改得到了C++版本的,代码如下:
/*灰度图像的二值化方法*/
class CxThreshold { public: static int CalcKittlerMinError(int* HistGram) { int X, Y; int MinValue, MaxValue; int Threshold ; long PixelBack, PixelFore; double OmegaBack, OmegaFore, MinSigma, Sigma, SigmaBack, SigmaFore; for (MinValue = 0; MinValue < 256 && HistGram[MinValue] == 0; MinValue++) ; for (MaxValue = 255; MaxValue > MinValue && HistGram[MinValue] == 0; MaxValue--) ; if (MaxValue == MinValue) return MaxValue; // 图像中只有一个颜色 if (MinValue + 1 == MaxValue) return MinValue; // 图像中只有二个颜色 Threshold = -1; MinSigma = 1E+20; for (Y = MinValue; Y < MaxValue; Y++){ PixelBack = 0; PixelFore = 0; OmegaBack = 0; OmegaFore = 0; for (X = MinValue; X <= Y; X++){ PixelBack += HistGram[X]; OmegaBack = OmegaBack + X * HistGram[X]; } for (X = Y + 1; X <= MaxValue; X++){ PixelFore += HistGram[X]; OmegaFore = OmegaFore + X * HistGram[X]; } OmegaBack = OmegaBack / PixelBack; OmegaFore = OmegaFore / PixelFore; SigmaBack = 0; SigmaFore = 0; for (X = MinValue; X <= Y; X++) SigmaBack = SigmaBack + (X - OmegaBack) * (X - OmegaBack) * HistGram[X]; for (X = Y + 1; X <= MaxValue; X++) SigmaFore = SigmaFore + (X - OmegaFore) * (X - OmegaFore) * HistGram[X]; if (SigmaBack == 0 || SigmaFore == 0){ if (Threshold == -1)Threshold = Y; } else{ SigmaBack = sqrt(SigmaBack / PixelBack); SigmaFore = sqrt(SigmaFore / PixelFore); Sigma = 1 + 2 * (PixelBack * log(SigmaBack / PixelBack) + PixelFore * log(SigmaFore / PixelFore)); if (Sigma < MinSigma){ MinSigma = Sigma; Threshold = Y; } } } return Threshold; } };
时间: 2024-11-08 21:52:31