How can the objects touching the boundary of the ROI polygon in an image be removed in Matlab?

7 views (last 30 days)
Is there a way that one can define a new image boundary to concide with the boundary of the polygon obtained using roipoly. I would like to use the imclearborder function to remove objects touching the boundary of the polygon. Can such objects be removed and how in Matlab?

Answers (2)

DGM
DGM on 27 Oct 2024 at 8:48
You might want to use imclearborder(), but that's not what imclearborder() does. If you have logical masks, then:
% say you have a logical mask
workingmask = imread('cmanpolyblobs.png')>128;
imshow(workingmask)
% and pretend you created a mask
% using roipoly() or drawpolygon()
polygonmask = imread('cmantifmk.png')>128;
imshow(polygonmask)
% get rid of blobs which touch only the border of the polygon mask
L = bwlabel(workingmask);
selectedL = unique(L(bwperim(polygonmask)));
outmask = ~ismember(L,selectedL);
% visualize the three masks as a single image
% only one blob remains in outmask.
% even though it intersects with the polygon,
% it does not intersect with its border.
testpict = double(cat(3,workingmask,polygonmask,outmask));
imshow(testpict)

Image Analyst
Image Analyst on 27 Oct 2024 at 13:43
Edited: Image Analyst on 27 Oct 2024 at 13:51
"define a new image boundary to concide with the boundary of the polygon obtained using roipoly" <== To get a binary image mask from roipoly you can do
[x, y] = roipoly();
polygonMask = poly2mask(x, y, rows, columns);
This is a new, separate image.
"remove objects touching the boundary of the polygon" <== To remove other objects touching that mask, you can OR the mask into your other image
mask2 = polygonMask | yourOtherMask;
Then you can label the image and use ismember to remove all blobs with the label number of the polygon mask, as @DGM showed you.
Or you could use bwselect to find the polygon and touching blobs and remove then by indexing, something like (untested):
[r, c] = find(polygonMask); % Get all locations of blob pixels
mask2 = polygonMask | yourOtherMask; % Add polygon mask to your other blobs mask.
touchingBlobs = bwselect(mask2, r(1), c(1)); % This is only the polygon and blobs that touch it.
% Erase touching blobs from mask2:
mask2(touchingBlobs) = false; % mask2 is now the final image.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!