[Csharp] using System;
Namespace Splash. Imaging
{
/// <Summary>
/// Image Processing: Calculation Method of binarization threshold of Dajin Method
/// </Summary>
Public static partial class Binarize
{
/// <Summary>
/// Threshold value calculated by Dajin Method
/// </Summary>
/// <Param name = "grayArray"> grayscale array </param>
/// <Returns> binarization threshold </returns>
Public static Int32 OtsuThreshold (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
Double SumU = 0; // Double precision to avoid data overflow in Variance Calculation
For (Int32 I = 1; I <256; I ++)
{
SumU + = I * Histogram [I]; // Total Quality moment
}
// Grayscale Interval
Int32 MinGrayLevel = Array. FindIndex (Histogram, NonZero); // minimum gray value
Int32 MaxGrayLevel = Array. FindLastIndex (Histogram, NonZero); // maximum gray value
// Calculate the maximum inter-category variance
Int32 Threshold = MinGrayLevel;
Double MaxVariance = 0.0; // initial maximum variance
Double U0 = 0; // initial target quality moment
Int32 C0 = 0; // initial target point
For (Int32 I = MinGrayLevel; I <MaxGrayLevel; I ++)
{
If (Histogram [I] = 0) continue;
// Quality moment and points of the target
U0 + = I * Histogram [I];
C0 + = Histogram [I];
// Calculate the inter-class variance between the target and the background
Double Diference = U0 * SumC-SumU * C0;
Double Variance = Diference * Diference/C0/(SumC-C0); // Variance
If (Variance> MaxVariance)
{
MaxVariance = Variance;
Threshold = I;
}
}
// Returns the maximum inter-Class Variance threshold.
Return Threshold;
}
/// <Summary>
/// Check the non-zero value
/// </Summary>
/// <Param name = "value"> value to be checked </param>
/// <Returns>
/// True: non-zero
/// False: Zero
/// </Returns>
Private static Boolean NonZero (Int32 value)
{
Return (value! = 0 )? True: false;
}
}
}
Author: Qin Jianhui