function [gt_crop] = get_gt_box(gt_label, params)
% Crop the image to reduce the amount of background

if size(gt_label, 3) > 1
    gt_label = any(gt_label > 0, 3);
else
    gt_label = (gt_label > 0);
end

[lab_y, lab_x] = find(gt_label);

if ~isempty(lab_y)
    % Find the smallest box containing all foreground labels
    top =    min(lab_y) - params.gt_box_border;
    bottom = max(lab_y) + params.gt_box_border;
    left =   min(lab_x) - params.gt_box_border;
    right =  max(lab_x) + params.gt_box_border;
else
    % Take the minimum size bounding box around the center
    top =   floor(size(gt_label, 1)/2) - ceil(params.gt_box_min/2);
    bottom = ceil(size(gt_label, 1)/2) + ceil(params.gt_box_min/2);
    left =  floor(size(gt_label, 2)/2) - ceil(params.gt_box_min/2);
    right =  ceil(size(gt_label, 2)/2) + ceil(params.gt_box_min/2);
end

% Make sure the cropped box satisfies a minimum size
if (bottom - top) < params.gt_box_min
    extra_border = ceil((params.gt_box_min - (bottom - top))/2);
    top = top - extra_border;
    bottom = bottom + extra_border;
end

if (right - left) < params.gt_box_min
    extra_border = ceil((params.gt_box_min - (right - left))/2);
    left = left - extra_border;
    right = right + extra_border;
end

% Make sure the box is still in bounds
top = max(top, 1);
bottom = min(bottom, size(gt_label, 1));
left = max(left, 1);
right = min(right, size(gt_label, 2));

gt_crop = [top bottom left right];
end
