Search code examples
matlabbounding-boximage-segmentation

Bounding Box in Matlab (regionprops)


I am writing a Matlab program to segment an image and then put a bounding box around the segmented image. My code was previously working, however I am now getting the error:

  • Error using rectangle
  • Value must be a 4 element vector

The array in question is BoundingBox created by regionprops, which should contain only four elements, however is for some reason containing more. Here is my code (the defaultSegment function returns a binary image):

function [ boundImage ] = boundSegment( input_image )
image = defaultSegment(input_image);
clear s;
s = regionprops(image, 'Area', 'BoundingBox');
numObj = numel(s);
index = 1;
for k = 1: numObj-1
    if s(k+1).Area > s(index).Area
        index = k+1;
    else
        index = index;
    end
end
figure, imshow(input_image);
rectangle('Position',s(index).BoundingBox);
boundImage = null;

(I would actually prefer if my code could could directly put the bounding box on the image instead of subplotting it, but I haven't found a way to do that without the vision toolbox)

Thanks!


Solution

  • I suspect that image has more than two dimensions. Check that using size(image). BoundingBox will have four elements only if image has two dimensions. From Matlab's regionprops help:

    'BoundingBox' — The smallest rectangle containing the region, a 1-by-Q *2 vector, where Q is the number of image dimensions: ndims(L), ndims(BW), or numel(CC.ImageSize).

    The reason an image would have a third dimension is for multiple color channels. If you want to convert to grayscale for processing, use rgb2gray.