MATLAB: Clarification of idx in Planar Object Measuring tutorial

boxesComputer Vision Toolboxidxindex exceeds matrix dimensions

Under the "Detect Coins" paragraph in the "Measuring Planar Objects using a calibrated camera" example, the lines:
[areas, boxes] = step(blobAnalysis, imCoin);
% Sort connected components in descending order by area
[~, idx] = sort(areas, 'Descend');
% Get the two largest components.
boxes = double(boxes(idx(1:2), :));
% Adjust for coordinate system shift caused by undistortImage
boxes(:, 1:2) = bsxfun(@plus, boxes(:, 1:2), newOrigin);
I am uncertain of what the brackets, after the second occurrence of idx, are trying to define. I am trying to apply this to my own image and it gives me an error which states: Index exceeds matrix dimensions. Could someone please clarify this for me?

Best Answer

  • After the sort idx contains the indices of the areas vector sorted in descending order.
    The following, idx(1:2), which could also have been written as idx([1 2]), just take the first two indices. This is used to get the two rows of boxes that correspond to the two greatest area. The obvious reason why you'd get an index exceeds matrix dimension error would be because there are less than two areas because only one object (or none) was detected.
    The next line just add newOrigin to columns 1 and 2 of the two selected boxes.