function [D] = regionGrowing4(I, x, y, t, Var)
%regionGrowing   Perform region growing
%
%	Usage: [D] = regionGrowing(I, x, y, t)
%
%		I = input image (must be the class of double)
%		x = row of seed location
%       y = column of seed location
%           (Note: This notations conflict with conventional notations.
%                  I just don't want to modify this code too much by
%                  x -> row and y -> col.) 
%       t = ??? (It could be non-integer value, such as 6.5)
%
%       D = binary output (0 and 1)
%
% Author:	Unknown
%
% Created:  November 22, 2002
% Modified: November 26, 2002

tic;
 
 % Region Growing
 [m n] = size(I);
 D = logical(zeros(m, n,'uint8')); 
 
  
 position = [x y];
 
 Dx = [ 0 -1 1  0];
 Dy = [ 1  0 0 -1];
 
 Values = [];
 D(x, y) = 1;
 while ( not( isempty( position ) ) )
          
   [d s] = size(position);
   [p] = position(1:2);
  
   if (s == 2)
      position = [];
   else
      position = position(3:s);
   end
    
    x = p(1);
    y = p(2);
    
    Values = [ Values; I(x,y) ];
    
    %
    % calculate mean
    %
    Mr = mean(Values);
    if(size(Values,1)>10)
        Var = std(Values);
    end
    
    
    
      
    for i=1:4,
        
        %Borde no se procesa
         if ( (Dx(i)+x < 2) | (y +Dy(i)< 2) | (Dx(i)+x > m-1) | ( y +Dy(i)> n-1))
               continue;
        end
        
         % Centroid Method
         if ( (abs(I(x+Dx(i), y+Dy(i))- Mr ) < Var*t) & (D(x+Dx(i),y+Dy(i)) == 0)  ) 
        
         % Region 
         %if (  (abs(I(x+Dx(i), y+Dy(i))-I(x,y) ) < t) & (D(x+Dx(i),y+Dy(i)) ~= 0)) 
        
         %Seed Value
         %if ( (abs(I(x+Dx(i), y+Dy(i))- rI) < t) & (D(x+Dx(i),y+Dy(i)) ~= 0))
          
                D( x+Dx(i), y+Dy(i) ) = 1;
                position = [position x+Dx(i) y+Dy(i)];
         end
    end
    imshow(D);
    
               
   end % while
       
toc
return 
