4

I am using skimage to fill holes a binary input image (left side). This is my code

enter image description here

from skimage import ndimage
img_fill_holes=ndimage.binary_fill_holes(binary).astype(int)

However, the result of the above code cannot completely fill holes to the binary image. It means the output still remains the holes inside the circle. How can I completely fill all holes inside the circle?

KimHee
  • 728
  • 2
  • 12
  • 22

2 Answers2

6

you were probably tried to apply binary_fill_holes on an RGB image (a 3D matrix, do binary.shape[2] == 3 to check that).

try:

img_fill_holes = ndimage.binary_fill_holes(binary[:,:,0]).astype(int)

or any other "rgb2gray" approach and you should get the expected output

user2999345
  • 4,195
  • 1
  • 13
  • 20
  • I have an array which is (301, 512,512) ,can i perform a similar operation on my array? – Ryan Apr 07 '18 at 10:31
  • 2
    I just tried this and there doesn't seem to be a `ndimage` subpackage in `skimage`. I tried importing `skimage.ndimage` and it said there was no such package. I did however find it in SciPy: https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.morphology.binary_fill_holes.html and the inputs and outputs are the same. – rayryeng Jul 03 '18 at 04:34
  • this will ony slice the first rows of the 3d array ,please explain how to process the whole 3d nparry – Hari Feb 24 '20 at 10:22
0

if you have the 3D array, just change the structure to a 3d array.

for example: enter image description here

import SimpleITK as sitk
from scipy import ndimage
brain_mask_raw = sitk.ReadImage('/PATH/TO/brain_mask.nii.gz')
brain_mask_array = sitk.GetArrayFromImage(brain_mask_raw)
brain_mask_array_filled = ndimage.binary_fill_holes(brain_mask_array, structure=np.ones((3,3,3))).astype(int)
brain_mask_filled = sitk.GetImageFromArray(brain_mask_array_filled.astype(brain_mask_array.dtype)).CopyInformation(brain_mask_raw)
sitk.WriteImage(brain_mask_filled, '/RESULT/PATH/brain_mask_filled.nii.gz')

enter image description here

ref:scipy doc for binary fill holes

Ningrong Ye
  • 1,117
  • 11
  • 10