function th = enthropy(im)
% Selects a threshold for image usinq Kapur's enthropy method
% Usage: [threshold]= enthropy(image)
%

[h bins] = imhist(im);

L=length(h); 

Pi = h ./ sum(h) ;  % normalized histogram, representing probabilities between 0 and 1 

Psi = zeros(size(h));

for (s = 2:L-1)
    Ps = sum(Pi(1:s));
    dA = Pi(1:s)/Ps;
    dB = (Pi(s+1: L))/(1 - Ps);
    logdA = log(dA);
    for (a = 1:s) 
        if (isinf(logdA(a))) % replace -Inf with 0
            logdA(a) = 0.0 ;
        end
    end
    HA = -sum(dA.*logdA);
    
    logdB = log(dB);
    for (b = 1:L-s) 
        if (isinf(logdB(b))) % replace -Inf with 0
            logdB(b) = 0.0 ;
        end
    end
    HB = -sum(dB.*logdB);
    
    Psi(s) = HA + HB ;
end

[maxPsi, th] = max(Psi);





