clear, close, clc
a=imread('tekst1.jpg');

hist = imhist(a,256);
nhist = hist / sum(hist);
w0 = cumsum(nhist);
mt = cumsum(nhist .* (1:256)');
mT = mt(end);

sigma_b_kvadrat = (mT * w0 - mt).^2 ./ (w0 .* (1 - w0));
maksimum = max(sigma_b_kvadrat);
if isfinite(maksimum)
    prag = mean(find(sigma_b_kvadrat == maksimum))
end

subplot(121), imshow(a)
binarna=im2bw(a, prag/256);
subplot(122), imshow(binarna)

se = strel('square',2);
e=imerode(binarna, se);
figure, subplot(122), imshow(e), title('Erodirana slika');
subplot(121), imshow(binarna), title('Segmentirana slika');