FIll contour of a binary matrix

3 views (last 30 days)
Francesca Pittoni
Francesca Pittoni on 21 Nov 2021
Answered: Image Analyst on 21 Nov 2021
Hi everyone.
I have a binary matrix M (512x512) of 0 and 1, which represents the outline of an object, obtained from an image.
I would like to fill the whole object with ones, however I can't do it, because there are some points (pixels) that belong to the outline which are zeroes; so the outline is not complete ..
(If the outline was complete, I would have used this code to fill the object:
X = M>0;
M(X | cumsum(X)==1) = 1;
I leave you an image of the 512x512 binary matrix M.
Could anyone tell me how to complete the outline and then fill the object with ones?

Accepted Answer

DGM on 21 Nov 2021
You could do this by finding neighboring points and drawing lines between each pair like this example:
Or you can try a quick and dirty approach like this if it is sufficient.
S = load('M.mat');
M = S.M;
st = mat2gray(fspecial('disk',3));
M = imdilate(M,st);
M = bwmorph(M,'thin',inf);
M = imfill(M,'holes');
Mcomp = M*0.3 + S.M*0.7; % show both original and result
Mcomp = imcrop(Mcomp,[178 113 116 107]); % easier to see
This method is easy, but does not necessarily include all of the original dots on the resultant edge. The selection of the filter size depends on the dot spacing.

More Answers (1)

Image Analyst
Image Analyst on 21 Nov 2021
How did you get that image? If you have the original (x,y) points of the dots used to create the image then you can just use poly2mask
mask = poly2mask(x, y, rows, columns);

Community Treasure Hunt

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

Start Hunting!

Translated by