%function connect_8(img)

%x=imread(img);


x=[     1     1     0     0     0     1     0     1     1     1     0
        0     0     0     1     0     1     0     0     0     1     1
        0     0     0     1     0     1     1     0     1     1     1]

[s1,s2]=size(x);

y=zeros(s1+2,s2+2);
y(2:s1+1,2:s2+1)=x;
y=double(y);

obj_label=0;

offset=[-1 -1 0 -1;-1 0 -1 1];
tmp_label=[];

for i=2:s1+1
    for j=2:s2+1
        if y(i,j)==1
            tmp=size(find([y(i-1,j-1) y(i-1,j) y(i,j-1) y(i-1,j+1)]~=0),2);
           switch tmp
           case 0
               obj_label=obj_label+1;
               y(i,j)= obj_label;
               %           case 1
               %y(i,j)= y(i+offset(1,find([y(i-1,j-1) y(i-1,j) y(i,j-1) y(i+1,j-1)]~=0)),j+offset(2,find([y(i-1,j-1) y(i-1,j) y(i,j-1) y(i+1,j-1)]~=0)));
           otherwise
               tmp2=find([y(i-1,j-1) y(i-1,j) y(i,j-1) y(i-1,j+1)]~=0);
               for k=1:size(tmp2)
                   tmp_label=[tmp_label y(i+offset(1,tmp2(k)),j+offset(2,tmp2(k)))];
               end
               y(i,j)= min(tmp_label);
               for k=1:size(tmp2,2)
                   y(find(y==y(i+offset(1,tmp2(k)),j+offset(2,tmp2(k)))))=y(i,j);
               end
               tmp_label=[];    
           end
       end 
    end
end

y

