Hi Simeon,
To solve the problem of drawing circles that sometimes extend outside the polygons, we can use a modified approach to ensure that the circles are drawn within the polygon boundaries. The solution involves calculating the maximum inscribed circle for each polygon, which guarantees that the circle will fit inside the polygon.
You can follow these steps:
1. First, identify the boundaries of each polygon in the image using “bwboundaries” and then create a binary mask that isolates the polygon from the rest of the image.
[B, ~] = bwboundaries(bw2,'noholes');
plot(boundary(:,2), boundary(:,1), 'b', 'LineWidth', 2)
objMask = poly2mask(boundary(:,2), boundary(:,1), size(bw2,1), size(bw2,2));
2. Then, apply distance transformation on each binary mask using “bwdist” which calculates the distance from each pixel to the nearest boundary pixel, effectively identifying the center and radius of the maximum inscribed circle.
[MaxDist, idx] = max(D(:));
[cy, cx] = ind2sub(size(D), idx);
3. Finally, draw the circles using the identified centers and radii for each polygon, ensuring they fit perfectly inside the polygon boundaries.
viscircles([cx, cy], radius, 'EdgeColor', 'r');
You can refer the output below for better understanding:
For more information on the “bwboundaries”,” bwdist” and “viscircles” functions in MATLAB, you can go through the following documentations:
- https://www.mathworks.com/help/images/ref/bwboundaries.html
- https://www.mathworks.com/help/images/ref/bwdist.html
- https://www.mathworks.com/help/images/ref/viscircles.html
Hope this helps!