function [cleanMask] = RemoveNoise(mask)
% RemoveNoise Create index of all connected voxel objects. Remove all but the
% largest object
% =========================================================================
% AUTHOR       Zachary Ip
% CONTACT      ipzach@uw.edu
% INSTITUTION  University of Washington
% DATE        25th November 2019
% 
% INPUTS mask - 3D logical - binary mask to be cleaned
%   
% OUTPUTS cleanMask - 3D double - cleaned mask
% =========================================================================
% Create connected component object of the mask
maskObjects = bwconncomp(mask);

% From each object, get individual voxel indices 
maskPixelList = cellfun(@numel,maskObjects.PixelIdxList);

% Keep only the largest object
maskIdx = maskPixelList == max(maskPixelList(:));

% Set values of all smaller objects to 0
for i = 1:maskObjects.NumObjects
    if maskIdx(i) ==0
        mask(maskObjects.PixelIdxList{i}) = 0;
    end % if
end % i
cleanMask = mask;
end % function