function validIndices = getValidSpaceNetIndices(imds,trainMaskDir,numIndices)

% Copyright 2020 The MathWorks, Inc.

validIndices = zeros(numIndices,1);
imdsIdx = 0;
validIndicesIdx = 0;

while hasdata(imds) && (validIndicesIdx < numIndices)
    
    imdsIdx = imdsIdx+1;

    [~,meta] = read(imds);
    [~,name] = fileparts(meta.Filename);
    
    maskImageFileName = strcat(name,'_mask'); 
    if ~exist(fullfile(trainMaskDir,[maskImageFileName '.tif']),'file')
        continue
    end
    
    validIndicesIdx = validIndicesIdx+1;
    validIndices(validIndicesIdx) = imdsIdx;
end