How connect the coordinate and fill the area to create a binary mask?

8 次查看(过去 30 天)
I need to create a binary mask from the series of coordinate. My current code is like below but what it does, the edges of the mask are not smooth. I think it is not precise and I need to make sure I am connecting exact coordinate and connect them together.
Here on the left side I plotted the points (always is 42 points) and on the right side is the output of the code. As you can see the edges are not smooth.
Here is the current code and the output:
im is image with size of 112 * 112 that filled with all zero values except coordinates and inside the region filled with the 255.
function BW = mask_data(X,Y, im)
X = round(X);
Y = round(Y);
%round coordinates
X ( X < 1 ) = 1;
Y ( Y < 1 ) = 1;
BW = im > 255;
for p = 1:length(X)
BW(Y(p),X(p)) = 1;
end
BW = BW * 255;
BW = bwconvhull(BW);
BW = im2uint8(BW);
figure;
imshow(BW);
close all;
end

回答(2 个)

darova
darova 2020-6-12
  • use edge to detect edge pixels
  • use find to find all coordinates
  • use boundary to calculate correct order

Image Analyst
Image Analyst 2020-6-12
Use poly2mask():
BW = poly2mask(X, Y, size(im, 1), size(im, 2));
It will draw a straight line between each pair of points in X and Y.
If you need something even smoother, you can use splines to smooth the boundary of BW while still going through the X and Y points by creating additional points in between your knot points using cubic polynomical. See attached demos.

Community Treasure Hunt

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

Start Hunting!

Translated by