function [croppedObjectsTemp, croppedObjectsThreshTemp] = watershedObjectSplitter(imgGP, imgThresh, nObjs)            

% Initialize vars
croppedObjectsTemp = cell(nObjs,1);
croppedObjectsThreshTemp = cell(nObjs,1);

% Generate a binary mask from the input image
bw = imgGP;
bw(~isnan(bw)) = 1;
bw(isnan(bw)) = 0;

% Fill holes
bw = imfill(bw,'holes');

% Remove small objects
bw = bwareaopen(bw, 20);

% Compute the distance transform of the complement of the binary image
D = bwdist(~bw);

% Complement the distance transform, and force pixels that don't belong to the objects to be at -Inf
D = -D;
D(~bw) = -Inf;

% Find the optimum threshold level for suppressing shallow minima in the 
% distance transform complement such that the watershed transform labels
% nObjs objects for segmentation
for level=0:100
    D2 = imhmin(D,level); 
    L = watershed(D2);
    if max(L(:))-1 <= nObjs
        if max(L(:))-1 < nObjs
            nObjs = max(L(:))-1; % Auto-segmentation was not entirely successful. Continue and prevent error by segmenting less objects than planned.
        end
        break
    end
end

for i=1:nObjs
    % Apply segmentation to GP map
    mask = zeros(size(L));
    mask(L == i+1) = 1;
    objectExtents = regionprops(mask, 'BoundingBox');
    imgTemp = imgGP;
    imgTemp(~mask) = nan;
    croppedObjectsTemp{i}  = imcrop(imgTemp, objectExtents(1).BoundingBox);
    
    % NaN padding to prevent object from touching border 
    croppedObjectsTemp{i} = padarray(croppedObjectsTemp{i}, [1,1]);
    croppedObjectsTemp{i}(1,:) = nan;
    croppedObjectsTemp{i}(end,:) = nan;
    croppedObjectsTemp{i}(:,1) = nan;
    croppedObjectsTemp{i}(:,end) = nan;
    
    % Apply segmentation to pre-processed images
    for c=1:length(imgThresh) % for each wavelength in c-stack
        imgTemp = imgThresh{c}; 
        imgTemp(~mask) = nan; % apply mask
        croppedObjectsThreshTemp{i}{c} = imcrop(imgTemp, objectExtents(1).BoundingBox);
        croppedObjectsThreshTemp{i}{c} = padarray(croppedObjectsThreshTemp{i}{c}, [1,1]);
    end
end
end