This is a module for the Insight Toolkit (ITK). The module includes a filter called FixTopologyCarveOutside
which works like morphological closing, except that in the "erode" phase topological constraints are enforced to avoid re-opening holes. It is able to close holes in thin layers (e.g. skull) with a minimal thickness.
import itk
skull_mask = itk.imread('path/to/skull_with_holes.mha').astype(itk.US)
ImageType = type(skull_mask)
MaskType = itk.Image[itk.UC, 3]
top_control = itk.FixTopologyCarveOutside[ImageType, ImageType, MaskType].New()
top_control.SetInput(skull_mask)
top_control.SetRadius(5)
top_control.Update()
skull_mask_closed = top_control.GetOutput()
itk.imwrite(skull_mask_closed, 'skull_mask_closed.mha')
Or using a custom mask (e.g. a sphere around a hole):
import itk
custom_mask = itk.imread('path/to/custom_mask.mha').astype(itk.UC)
skull_mask = itk.imread('path/to/skull_with_holes.mha').astype(itk.US)
skull_mask_closed = itk.fix_topology_carve_outside(skull_mask, MaskImage=custom_mask, Radius=5)
itk.imwrite(skull_mask_closed, 'skull_mask_closed.mha')
To install the binary Python packages:
python -m pip install itk-topologycontrol