[Csharp]
Using System;
Namespace Splash. Imaging
{
/// <Summary>
// Image Processing: Iteration Method of binarization threshold Calculation
/// </Summary>
Public static partial class Binarize
{
/// <Summary>
/// Calculate the threshold using iterative method
/// </Summary>
/// <Param name = "grayArray"> grayscale array </param>
/// <Returns> binarization threshold </returns>
Public static Int32 IterativeThreshold (Byte [,] grayArray)
{// Create a statistical histogram
Int32 [] Histogram = new Int32 [1, 256];
Array. Clear (Histogram, 0,256); // Initialization
Foreach (Byte B in grayArray)
{
Histogram [B] ++; // statistical Histogram
}
// Total Quality moment and number of image points
Int32 SumC = grayArray. Length; // total number of image points
Int32 SumU = 0;
For (Int32 I = 1; I <256; I ++)
{
SumU + = I * Histogram [I]; // Total Quality moment
}
// Determine the initial threshold value www.2cto.com
Int32 MinGrayLevel = Array. FindIndex (Histogram, NonZero); // minimum gray value
Int32 MaxGrayLevel = Array. FindLastIndex (Histogram, NonZero); // maximum gray value
Int32 T0 = (MinGrayLevel + MaxGrayLevel)> 1;
If (MinGrayLevel! = MaxGrayLevel)
{
For (Int32 Iteration = 0; Iteration <100; Iteration ++)
{// Calculate the target's quality moment and number of points
Int32 U0 = 0;
Int32 C0 = 0;
For (Int32 I = MinGrayLevel; I <= T0; I ++)
{// Quality moment and points of the target
U0 + = I * Histogram [I];
C0 + = Histogram [I];
}
// Center value of the average gray scale value of the target and the average gray scale value of the background
Int32 T1 = (U0/C0 + (SumU-U0)/(SumC-C0)> 1;
If (T0 = T1) break; else T0 = T1;
}
}
// Return the Optimal Threshold
Return T0;
}
}
}
Author Qin Jianhui