function [lvl T] = prah_entropy_kapur(obr);

% obr = rgb2gray(obr);
% obr = double(obr);
% obr=obr*1/max(max(obr));  
% obr = 1 - obr;
h = imhist(obr);
p = h/sum(h);

p2 = p;
% p(find (p<0.0001))=[]; 

p = p(p~=0);
tab(:,1) = 1:256;
tab(:,2) = p2;


for i = 1:length(p)
    Pf = sum(p(1:i));
    Pb = sum(p(i+1:end));
    
    Hf(i) = - sum(p(1:i)/Pf .* log10(p(1:i)/Pf));
    Hb(i) = - sum(p(i+1:end)/Pb .* log10(p(i+1:end)/Pb));
    
    T(i) = Hf(i)+Hb(i);
end
poc = 0;
for i = 1:256
    if p2(i) == 0
    else
        poc = poc + 1;
        tab(i,3) = poc;
        krit(:,poc) = [i T(poc)];
    end
end
% Topt = find(T == max(T))/256
T2 = T(round(end/2):end);
Topt = find(T2 == max(T2(T2<inf))) + floor(length(T)/2);
if length(T)<Topt
    Topt = length(T)/256;
else
    Topt = find(tab(:,3) == Topt)/256;
end

lvl = Topt;