2
votes

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!

2
Have you checked the value of s(index).BoundingBox to ensure its a 4 element vector?slayton
Maybe I wasn't clear. s(index).BoundingBox is NOT giving a 4 element vector, but I cannot figure out why this is the case.Joseph
see this link on how to get the size of the segment and set the bounding box mathworks.com/matlabcentral/fileexchange/25157 you will have to download a matlab fileRachel Gallen
That link was not helpful.Joseph

2 Answers

2
votes

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.

0
votes

Continuing @shoelzer's answer regarding image with three channels, I suspect you get color image because of your segmentation algorithm (defaultSegment) that paints each segment in a different color. try rgb2ind to convert image to a segmentation label 2D matrix