imageNameReddi = input('Enter Image Name: ', 's');
I = load(imageNameReddi);
img = I.testima;
counts = imhist(img);
p = counts ./ sum(counts);
bins = 256;
for j=1:bins
if counts(j) ~= 0
break;
end
end
minGrayLevel = 0;
flippedCounts = flipud(counts);
for q=1:bins
if flippedCounts(q) ~= 0
break;
end
end
maxGrayLevel = 256-q;
kmax = maxGrayLevel - minGrayLevel
k1 = round(kmax/3);
k2 = round(2*kmax/3);
p = counts / sum(counts);
w0 = 0;w1=0; w2=0;
m0 =0;m1=0;m2=0;
colorCounter = 1;
C = {'k','b','r','g','y',[.5 .6 .7],[.8 .2 .6]};
hold on;
condition = true;
while condition
for k= 1:k1
w0(k) = sum(p(1:k));
m0(k) = sum(p(1:k).*(1:k)') / w0(k);
end
for l= 1:(k2-k1)
w1(l) = sum(p(k1:k2));
m1(l) = sum(p(k1:k2).*(k1:k2)') / w1(l);
end
for i= 1:(bins-k2)
w2(i) = sum(p(k2:bins));
m2(i) = sum(p(k2:bins).*(k2:bins)')/w2(i);
end
e1 = round((max(m0)+ max(m1))/2 - k1);
e2 = round((max(m1)+max(m2))/2 - k2);
plot(counts);
line([k1 k1], get(gca,'YLim'), 'Color','r');
line([k2 k2], get(gca,'YLim'), 'Color','r');
pause(1);
condition = (e1 ~= 0 || e2 ~= 0)
colorCounter= colorCounter + 1;
k1 = k1 + e1;
k2 = k2 + e2;
end
hold off;
line([k1 k1], get(gca,'YLim'), 'Color','k');
line([k2 k2], get(gca,'YLim'), 'Color','k');
figure(2), imshow(img);
for arr = 1:numel(img)
if img(arr)<k1
img(arr) = 0;
elseif img(arr)>k2
img(arr) = 255;
else
img(arr) = 127.5;
end
end
figure(3), imshow(img);