clear all
tic
I=imread('E:\modified\mdm002.jpg');
%I=rgb2gray(I);
imshow(I);
figure;
 copy=double(I);
np=40;
k=20;
;
[h,ind,population,m,mi]=initiate(I,k,np);
firstpopulation=population;
population=step2(population,np,k);
tmax=10;
cc=0;
n=1; 
oldmin=0;
for iter=1:tmax
    %population=step2(population,np,k)
    %population=step3abc(Data,population,k,np)
     [population]=step3abc_mod(h,ind,m,population,k,np);
    %TV=step3d(population,k,n,iter,tmax);
   % TV=step2(TV,np,k);
    csv=zeros(1,np);
    flag=0;
    cc=cc+1;
    minimum=inf;
    for j=1:np
        [hcp,cid]=histc(ind,population(j,:),m,h,k);
        cspop(j)=valid_cs(ind,population,hcp,h,m,1,k,j);
    end
    [best ind]=min(cspop);
    [TV,cspop]=newoffspring_TLBO1(population,np,ind,cspop,k,m,mi,h);
    TV=step2(TV,np,k);
    for j=1:np
        [hcTV,cid]=histc(ind,TV(j,:),m,h,k);
         csTV(j)=valid_cs(ind,TV,hcTV,h,m,1,k,j);
        if csTV<cspop(j)
            flag=1;
            population(j,:)=TV(j,:);
            if minimum>csTV(j)
            minimum=csTV(j);
            bestchr=j;
            end
        else
            if minimum>cspop(j)
            minimum=cspop(j);
            bestchr=j;
        end
        end
    end
    if (abs(oldmin-minimum)<0.000001)%flag==0
        break
    else
        oldmin=minimum;
    end
end
   l=bestchr;
  [hcp,cid]=histc(ind,population(l,:),m,h,k);
  s=size(copy);
mask=zeros(s);
cid=0;
for i=1:k
    if population(l,i)>0.5
        cid=cid+1;
        mu(cid)=population(l,k+i);
    end
end
for i=1:s(1),
for j=1:s(2),
  c=abs(copy(i,j)-mu);
  a=find(c==min(c));
  mask(i,j)=a(1);
  end
end

mu=mu+mi-1;   % recover real range
% FI=imshow(mask,[]);
% figure;
% mask=abs(mask-255);
imshow(mask,[]);
% figure;
% E=edge(mask,'canny');
% imshow(E);
%imshow(I)
% imshow(im)
  cid;
  toc