Crop bounding boxes



bboxB = bboxcrop(bboxA,window) crops bounding boxes from a set of input bounding boxes, bboxA, located in the cropping window.

[bboxB,indices] = bboxcrop(bboxA,window) additionally returns a vector of indices that indicate which bounding boxes in bboxA are within the cropping window, window.

[___] = bboxcrop(___,'OverlapThreshold',threshold) additionally sets an overlap threshold.


collapse all

Read an image.

I = imread('peppers.png');

Define bounding boxes and labels.

bboxA = [
    410 230 100 90
    186 78  80  60
bboxA = 2×4

   410   230   100    90
   186    78    80    60

labelsA = [

Create a center cropping window.

targetSize = [256 256];
win = centerCropWindow2d(size(I),targetSize);

Center crop the image.

[r,c] = deal(win.YLimits(1):win.YLimits(2),win.XLimits(1):win.XLimits(2));
J = I(r,c,:);

Center crop boxes and labels. Boxes outside the cropping window are removed.

[bboxB,indices] = bboxcrop(bboxA,win);
labelsB = labelsA(indices);

Display the results.

I = insertObjectAnnotation(I,'Rectangle',bboxA,labelsA);
J = insertObjectAnnotation(J,'Rectangle',bboxB,labelsB);

Input Arguments

collapse all

Bounding boxes, specified as an M-by-4 matrix of M bounding boxes. Each row, M, of the matrix defines a bounding box as a four-element vector [x,y,width,height] in pixel coordinates.

Crop window, specified as a four-element vector [x,y,width,height], an image, or an images.spatialref.Rectangle object.

Overlap threshold, specified positive scalar less than or equal to 1. The amount of overlap between transformed boxes and the area defined by the output view is defined as:

area(bbox intersect bounding rectangle) / area(bbox)

  • bounding rectangle — Defined by the input spatial reference object, ref.

  • bbox — Result of transforming boxes in bboxA.

If the computed overlap value is greater than the value of the threshold property, then the transformed boxes are clipped to the bounding rectangle border. Otherwise, the boxes are discarded. Lowering the threshold can result in parts of the object getting discarded.

Output Arguments

collapse all

Cropped bounding boxes, returned as an N-by-4 matrix of N bounding boxes. The number of bounding boxes returned is less than the number of bounding boxes in the input. Each row, N, of the matrix defines one bounding box in pixel coordinates, as a four-element vector [x,y,width,height]. The location of the output bounding boxes are relative to the cropping window.

Indices, returned as a vector of integers. The indices indicate which bounding boxes in the input, bboxA, are within the cropping window.

Introduced in R2019b