MATLAB: I traced region of a binary image using bwboundaries. Now I want to set all objects to 0 in binary image except selected on for say 2nd boundary. How can it be done

bwboundariesimage processingImage Processing Toolbox

using code
[B,~]=bwboundaries(I, 'noholes');
I got the list of boundaries in B. now by some criteria, I have selected B(2). So, now I want to delete all the objects in the image from B(1) to B(n) except B(2). How it can be done?

Best Answer

If I is your segmented, binary image, then I believe the second object identified by bwboundaries is the same as the second one that would be identified by bwlabel. So use ismember():
[labeledImage, numBlobs] = bwlabel(I);
secondBlob = ismember(labeledImage, 2); % Extract blob #2 only.
An alternate way is to use the boundary and pass it into poly2mask():
[rows, columns] = size(I);
[B, numBlobs] = bwboundaries(I, 'noholes');
secondBoundary = B{2};
x = secondBoundary(:, 2); % Columns
y = secondBoundary(:, 1); % Rows
secondBlob = poly2mask(x, y, rows, columns);
Related Question