Fill the area between two connected components in MATLAB

I have a binary image that represents a number in MATLAB:

image description

I would like to fill out all the numbers. Desired Result:

enter image description here

The only thing I found was the imfill function, but it was not very useful, since I lost my internal data (for example, 9 inner circles).

+7
source share
3 answers

The problem is how to distinguish holes from numbers. A possible ad hoc solution filters them by the area of ​​the pixels inside.

 function SolveSoProblem() I = imread('http://i.stack.imgur.com/SUvif.png'); %Fill all the holes F = imfill(I,'holes'); %Find all the small ones,and mark their edges in the image bw = bwlabel(I); rp = regionprops(bw,'FilledArea','PixelIdxList'); indexesOfHoles = [rp.FilledArea]<150; pixelsNotToFill = vertcat(rp(indexesOfHoles).PixelIdxList); F(pixelsNotToFill) = 0; figure;imshow(F); %Remove the inner area bw1 = bwlabel(F,4); rp = regionprops(bw1,'FilledArea','PixelIdxList'); indexesOfHoles1 = [rp.FilledArea]<150; pixelListToRemove = vertcat(rp(indexesOfHoles1).PixelIdxList); F(pixelListToRemove) = 0; figure;imshow(F); end 

After step (1) :

enter image description here

After step (2) :

enter image description here

+4
source

Another possibility is to use the BWBOUNDARIES function, which:

monitors the external borders of objects, as well as the boundaries of the hole inside these objects

This information is contained in the fourth issue of A , an adjacency matrix that represents dependencies on parent and child holes.

 %# read binary image bw = imread('SUvif.png'); %# find all boundaries [B,L,N,A] = bwboundaries(bw, 8, 'holes'); %# exclude inner holes [r,~] = find(A(:,N+1:end)); %# find inner boundaries that enclose stuff [rr,~] = find(A(:,r)); %# stuff they enclose idx = setdiff(1:numel(B), [r(:);rr(:)]); %# exclude both bw2 = ismember(L,idx); %# filled image %# compare results subplot(311), imshow(bw), title('original') subplot(312), imshow( imfill(bw,'holes') ), title('imfill') subplot(313), imshow(bw2), title('bwboundaries') 

enter image description here

+6
source

Assuming the top left pixel is always outside the filled areas:

Work on the top line, copying pixels to the output image.

When you hit a white pixel followed by a black pixel in the input image, start adjusting the white pixels in the output image until you reach the black pixel followed by a white pixel.

0
source

All Articles