- Algorithm steps:
1. Generate a histogram, i.e., count the number of pixels of each gray level.
2. The histogram is normalized, i.e., the total calculated for each pixel of pixel gray level scale.
3. Iterative gradation from 0 to 255 gray scale, each iteration ratio w0 foreground pixels (pixel gradation 0 to gradation current iteration), and calculates the foreground pixel average gradation value U0;
Proportional calculation background pixel (gradation current iteration to gradation 255 pixels) and an average gradation w1 of U1;
4. Each iteration foreground and background pixels is calculated variance g = w0 * w1 * (u0-u1) ^ 2;
5. Compare each iteration of the variance, that the iteration taking the maximum gradation variance binarization threshold.
- Algorithm works:
Referred to the number of foreground pixels n0, the ratio of w0, and gradation of s0, U0 is the average gray; the number of pixels of the background is n1, the ratio of w1, and gradation of s1, the average gray level U1;
The total number of pixels of the image is n, and the gradation is s, average gray u. The between-class variance g.
It has the following formula:
w0 = n0 / n; w1 = n 1 / n; n0 + n1 = n; w0 + w1 = 1;
u0=s0/n0; u1=s1/n1; u=s/n u=u0*w0+u1*w1;
g=w0*(u0-u)^2+w1(u1-u)^2;
Eventually get g = w0 * w1 * (u0-u1) ^ 2;
For image histogram has two peaks, large law threshold approximates the required trough between two peaks, it can be used to divide two values.
- Algorithm:
In order to reduce the depth of iterations, using the formula u = u0 * w0 + u1 * w1 of to g = w0 * w1 * (u0-u1) ^ 2 in u1, to give the formula:
g=w0/(1-w0)*(u0-u)^2
Code is implemented as follows:
unsigned char Ostu ( int size, unsigned char * Image) { int I; unsigned char threshold = 0 ; // threshold a float variance = 0 ; // variance between two classes a float maxvariance = 0 ; // Maximum Variance a float Gray = 0 ; / / foreground grayscale a float W0 = 0 ; // foreground pixel ratio a float U0 = 0 ; // foreground mean gray a float U = 0 ; // total average gray level, i = foreground can be seen as gray scale at 255 a float Histogram [ 256 ] = { 0 }; // histogram for (I = 0 ; I <size; I ++ ) { histogram [ * (Image + I)] ++; // pixel histogram } for (I = 0 ; I < 256 ; I ++ ) { histogram [ i]/ = size; // ratio histogram U + = Histogram [I] I *; // Get Prospects i = 255 gray scale, i.e., the total average gray } for (i = 0 ; I < 256 ; I ++ ) { W0 + = Histogram [I]; // foreground pixel ratio gray Histogram + = I * [I]; // foreground gray scale U0 = gray / W0; // foreground foreground = gray scale average gray / gray pixel ratio = degree and / pixel and variance = W0 / ( . 1 -w0) * (U-U0) * (U-U0); // find variance IF (variance> maxvariance) { maxvariance = variance; threshold = i; // maximum value g i as the corresponding global threshold image } } return threshold; }