The C++ Augmented Reality Toolkit
Appendix A - Sample Otsu Thresholding C++ Code
// NOTE: Creation of histogram[256] not shown
float w = 0; // first order cumulative
float u = 0; // second order cumulative
float uT = 0; // total mean level
int k = 255; // maximum histogram index
int threshold = 0; // optimal threshold value
float histNormalized[256]; // normalized histogram values
float work1, work2; // working variables
double work3 = 0.0;
// Create normalised histogram values
// (size=image width * image height)
for (int I=1; I<=k; I++)
histNormalized[I-1] = histogram[I-1]/(float)size;
// Calculate total mean level
for (int I=1; I<=k; I++)
uT+=(I*histNormalized[I-1]);
// Find optimal threshold value
for (int I=1; I<k; I++) {
w+=histNormalized[I-1];
u+=(I*histNormalized[I-1]);
work1 = (uT * w - u);
work2 = (work1 * work1) / ( w * (1.0f-w) );
if (work2>work3) work3=work2;
}
// Convert the final value to an integer
threshold = (int)sqrt(work3);