How can fill holes in 3D binary matrix?

I have a huge 3D binary matrix. To process it, I need to fill some holes but imfill(BW,'holes') does not work on 3D binary matrix and I just use it for one element in the matrix. I want to fill holes in all elements of the matrix not element by element. Can some one help me?

2 Comments

What do you mean by "I just use it for one element"? How are you using it? If you pass in the whole array, it will fill the whole array - all holes that are there, even for a 3D or higher dimension array.
Thanks for clearing up your non-standard terminology. What you call an "element" is what everyone else in the world calls a "slice", or sometimes "plane". An element is just one voxel - one single value of the 3D array.

Sign in to comment.

 Accepted Answer

Matt J
Matt J on 15 Aug 2014
Edited: Matt J on 15 Aug 2014
What version of MATLAB are you using? IN R2013b, using imfill(BW,'holes') for 3D BW works fine for me, e.g.,
>> BW=ones(3,3,3); BW(2,2,2)=0; BW=imfill(BW,'holes')
BW(:,:,1) =
1 1 1
1 1 1
1 1 1
BW(:,:,2) =
1 1 1
1 1 1
1 1 1
BW(:,:,3) =
1 1 1
1 1 1
1 1 1

6 Comments

I use version R2012b. I describe my program on top comment.
Matt J
Matt J on 15 Aug 2014
Edited: Matt J on 15 Aug 2014
but when I use this code in k matrix as filledImage = imfill(k,'holes'); and then I imshow( k(:,:,26)), the result is like first image without any filling holes. I don't know how can use imfill in k matrix??
Maybe those are not holes in 3D. Maybe they are cross-sections of 3D tunnels leading outside the head. Try using imclose with a strel of an appropriate size to close off gaps that should be holes. Then apply imfill again.
Image Analyst
Image Analyst on 16 Aug 2014
Edited: Image Analyst on 16 Aug 2014
I agree with Matt. You probably think it should be filled but it's actually not completely enclosed and there is a path or tunnel leading from those black pixels to the outside world in planes/slices that are above or below the plane/slice you are looking at.
Thanks Matt J, I used imclose.
OK, just as long as you know that imclose is not guaranteed to fill all holes, and it changes the shape of the region by smoothing it out. It can do some hole filling but it's not the same as imfill.
Matt J
Matt J on 16 Aug 2014
Edited: Matt J on 16 Aug 2014
To be clear, my idea was to use imclose to plug small tunnels that might be false gaps in the segmentation map. Then follow up by doing a imfill.

Sign in to comment.

More Answers (1)

Matt J
Matt J on 16 Aug 2014
Edited: Matt J on 16 Aug 2014
If you want 2D holes within each slice filled, even if they don't belong to 3D holes, simply apply imfill in a loop:
for i=size(mine,3):-1:1
filledImage(:,:,i) = imfill(mine(:,:,i),'holes');
end

Asked:

on 15 Aug 2014

Edited:

on 16 Aug 2014

Community Treasure Hunt

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

Start Hunting!