a b/Code/ostu.m
1
function ostu_img=ostu(B);
2
3
%Image contains 2 classes of pixels, foreground and background pixels.
4
%Calculate optimal threshold such that inter-class variance is maximum
5
B = imresize(B, [256, 256]);
6
[r,c] = size(B);
7
  
8
 % Calculation of the normalized histogram
9
    n = 256;
10
    h = hist(B(:), n);        
11
    h = h/(length(B(:))+1);
12
    
13
    % Calculation of the cumulated histogram and the mean values
14
    cumSum = cumsum(h);
15
    mu = zeros(n, 1); 
16
    mu(1) = h(1);
17
    for i=2:n
18
        mu(i) = mu(i-1) + i*h(i);
19
    end    
20
         
21
    % Initialisation of the values used for the threshold calculation
22
    w0 = cumSum(1);
23
    w1 = 1-w0;
24
    mu0 = mu(1)/w0;
25
    mu1 = (mu(end)-mu(1))/w1;
26
    max = w0*w1*(mu1-mu0)*(mu1-mu0);
27
    lev = 1;
28
    
29
    for i = 2:n
30
        w0 = cumSum(i);
31
        w1 = 1-w0;
32
        mu0 = mu(i)/w0;
33
        mu1 = (mu(end)-mu(i))/w1;
34
        s = w0*w1*(mu1-mu0)*(mu1-mu0);
35
        if (s > max)
36
            max = s;
37
            lev = i;
38
        end
39
    end
40
    
41
    % Normalisation of the threshold        
42
    lev = lev/n;
43
    ostu_img = imbinarize(uint8(B),lev);