function createSpaceNetImageMasks(spaceNetVegasDir,maskDir)
% Write bigimage masks and label images for images in the directory
% vegasRGBImageDir. The building polygons are specified in the CSV files in
% the directory 'summaryData' within spaceNetVegasDataDir. The masks are
% written to disk at the specified location, maskDir. The building label
% images are written to disk at the specified location, buildingLabelDir
% and building label images are written to disk at the specified location,
% distanceLabelDir
%
% The building masks are obtained using L*a*b color segmentation. They 
% 
% The label images are obtained by using the pixel-coordinates of building polygons in CSV files. The polygons are used to
% create label images of the same spatial dimensions as the RGB images. The
% label images are written to disk as explained earlier.

% Copyright 2020 The MathWorks, Inc.

vegasRGBImageDir = fullfile(spaceNetVegasDir, 'RGB-PanSharpen');

buildingCSVFile = fullfile(spaceNetVegasDir,'summaryData','AOI_2_Vegas_Train_Building_Solutions.csv');
csvds = datastore(buildingCSVFile);
buildingPolygons = readall(csvds);

extension = '.tif';
imds = imageDatastore(vegasRGBImageDir,'FileExtensions',{extension});
imgIndices = 1:length(imds.Files);

for idx = 1:numel(imgIndices)
    [~,fileName] = fileparts(imds.Files{imgIndices(idx)});
    
    maskImageDirName = strcat(fileName,'_mask');
    if ~exist(fullfile(maskDir,[maskImageDirName  extension]),'file')
        Iin = imread(imds.Files{imgIndices(idx)});
        Irescale = rescale(Iin);
        
        fileNameInJSON = fileName(strfind(fileName,'AOI'):end);
        bIdx = ismember(buildingPolygons.ImageId,fileNameInJSON);
        buildingPtsStr = buildingPolygons.PolygonWKT_Pix(bIdx);
        if isempty(buildingPtsStr) || strcmpi(buildingPtsStr{1},'POLYGON EMPTY')
            continue;
        end
        
        %% Mask Images
        % Images can have dark border regions that contain no information. This
        % is due to the satellite data collection artifact. Remove these
        % regions using a mask.
        Ilab = rgb2lab(Irescale);
        A = Ilab(:,:,2);
        
        AScaled = rescale(A);
        AThreshold = imbinarize(AScaled);
        
        se = strel('disk',100);
        validMaskImage = ~imopen(AThreshold,se);
        
        % Make a bigimage out of the image mask
        if ~exist(fullfile(maskDir,[maskImageDirName extension]),'file')
            maskImageDirPathName = fullfile(maskDir,maskImageDirName);
            imwrite(validMaskImage,[maskImageDirPathName extension],'TIFF');
        end
    end    
end
end
