
% Function to filter a lake mask to remove lakes that are below a given
% size and below a given width 
% Function based on Pope's (2016) script. 
% Output is a mask that has been filtered to remove lakes that meet these
% characteristics. 
% Inputs are: "lake_mask" (binary mask of lakes), "min_pixel" (specify the
% number of pixels minimum to specify a lake, e.g. if 5 is chosen, then lakes 
% must be >= 5 pixels), and "min_width" (specify the minimum width above which 
% lakes must grow (i.e. wider or taller than 1 pixel) 

% Andrew Williamson, University of Cambridge, August 2017 

function lake_mask = SGL_mask_filter(lake_mask,min_pixel,min_width)

CC = bwconncomp(lake_mask,4);

    for lake = 1:CC.NumObjects
        
        if size(CC.PixelIdxList{lake},1) < min_pixel
            
            lake_mask(CC.PixelIdxList{lake}) = 0;
            
        else % all same row or all same column
            
            [r,c] = ind2sub(size(lake_mask),CC.PixelIdxList{lake});
            r = unique(r);
            c = unique(c);
            
            if size(r,1) == min_width || size(c,1) == min_width
                
                lake_mask(CC.PixelIdxList{lake}) = 0;
                
            end
        end
    end
    
end % end of function 