MATLAB: How to determine the number of closed regions in an edge image

boundaryimage processingImage Processing Toolbox

Given an edge image as shown in the figure, how can I find the number of closed regions (4 in the figure) in it?

Best Answer

Trivial - just 3, or even 2, lines of code. Just try this:
% Invert the image to form black curves on a white background
binaryImage = ~binaryImage;
% Get rid of huge background that touches the border
binaryImage = imclearborder(binaryImage);
% Count the objects remaining
[~, numberOfClosedRegions] = bwlabel(binaryImage);