I = imread('h2.jpg');
fr = I(:,:,1);
fg = I(:,:,2);
frd = double(fr);
fgd = double(fg);
frg=frd./fgd;
x=0;
y=0;
k=0;

%Step-1 Localization of hand region

for i=1:256%155
    for j=1:256%185
        if(frg(i,j)>1.05 && frg(i,j)<4.0)
            frg(i,j) = double(1); 
        else
        frg(i,j) = double(0);
    end
end
end
frg;
BW=im2bw(frg,0.2);
%imshow(BW);
tic
BW2 = double(bwmorph(BW,'open', Inf));


% Step 2 - Region based segmentation

BW3 = edge(BW2,'canny',(graythresh(frg) * 2));
BW4 = bwmorph(BW3,'close', Inf);


%Step 3 - Calculation of the center of gravity 

BW5 = BW2 - BW4;
for i=1:155
    for j=1:185
        if(BW5(i,j) == 1)
           k=k+1;
            x=x+i;
            y=y+j; 
          
       
    end
end
end
  

cx = uint8(x/k);
cy = uint8(y/k);
cxd = double(cx);
cyd = double(cy);
BW4(cx,cy) = double(1);
ct=0;


%Calculation of farthest distance from C.O.G

max=0;
for i=1:155
    for j=1:185
          z = BW4(i,j);
        if(z == 1)
           n =(sqrt(((i -cxd)^2)+((j -cyd)^2)));
            if( n > max )
                 max = n;
        end
    end
end
        
end
l=1;
temp=0;
q = int8(0.7 * max);

%Step 4 - Constructing the circle centered at C.O.G which cuts the actve
%fingers5

for i=1:155
    for j=1:185
        r = int8(sqrt(((i-cxd)^2)+((j-cyd)^2)));  
        if(r == q)
          p(l) =BW4(i,j);
BW4(i,j) =1;   
   l=l+1;
  else
    continue
end 

end
end  

%Extraction of information from the binary signal

for u=2:l-1
 
    if(p(u) == 1 && p(u-1) == 0 )
   ct =ct +1;
    end
end 
%plot(p);
count = int8(ct/2 -1)

toc
