Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab fill shapes by white

Tags:

matlab

fill

As you see, I have shapes and their white boundaries. I want to fill the shapes in white color.

The input is: enter image description here

I would like to get this output: http://s12.postimage.org/z3txnlb3f/untitled33.png

Can anybody help me please with this code? it doesn't change the black ellipses to white. Thanks alot :]]

I = imread('untitled4.bmp');
Ibw = im2bw(I);
CC = bwconncomp(Ibw); %Ibw is my binary image
stats = regionprops(CC,'pixellist');

% pass all over the stats
for i=1:length(stats),
size = length(stats(i).PixelList);
% check only the relevant stats (the black ellipses)
if size >150 && size < 600 
    % fill the black pixel by white    
    x = round(mean(stats(i).PixelList(:,2)));
    y = round(mean(stats(i).PixelList(:,1)));
    Ibw = imfill(Ibw, [x, y]);
end;
end;

imshow(Ibw);
like image 500
Alon Shmiel Avatar asked Oct 08 '22 04:10

Alon Shmiel


1 Answers

Your code can be improved and simplified as follows. First, negating Ibw and using BWCONNCOMP to find 4-connected components will give you indices for each black region. Second, sorting the connected regions by the number of pixels in them and choosing all but the largest two will give you indices for all the smaller circular regions. Finally, the linear indices of these smaller regions can be collected and used to fill in the regions with white. Here's the code (quite a bit shorter and not requiring any loops):

I = imread('untitled4.bmp');
Ibw = im2bw(I);

CC = bwconncomp(~Ibw, 4);
[~, sortIndex] = sort(cellfun('prodofsize', CC.PixelIdxList));

Ifilled = Ibw;
Ifilled(vertcat(CC.PixelIdxList{sortIndex(1:end-2)})) = true;
imshow(Ifilled);

And here's the resulting image:

enter image description here

like image 191
gnovice Avatar answered Oct 12 '22 16:10

gnovice