enh: add a binary subtraction interface
# https://www.nipreps.org/community/licensing/
#
"""Mathematical morphology operations as nipype interfaces."""
+from pathlib import Path
+import numpy as np
+import nibabel as nb
from nipype.interfaces.base import (
traits,
@@ -32,7 +35,7 @@ from nipype.interfaces.base import (
class _BinaryDilationInputSpec(BaseInterfaceInputSpec):
- in_mask = File(exists=True, mandatory=True, position=1, desc="input mask")
+ in_mask = File(exists=True, mandatory=True, desc="input mask")
radius = traits.Int(2, usedefault=True, desc="Radius of dilation")
@@ -47,10 +50,6 @@ class BinaryDilation(SimpleInterface):
output_spec = _BinaryDilationOutputSpec
def _run_interface(self, runtime):
- import nibabel as nb
- import numpy as np
- from pathlib import Path
-
# Open files
mask_img = nb.load(self.inputs.in_mask)
maskdata = np.bool_(mask_img.dataobj)
@@ -68,6 +67,39 @@ class BinaryDilation(SimpleInterface):
return runtime
+class _BinarySubtractInputSpec(BaseInterfaceInputSpec):
+ in_base = File(exists=True, mandatory=True, desc="input base mask")
+ in_subtract = File(exists=True, mandatory=True, desc="input subtract mask")
+
+
+class _BinarySubtractionOutputSpec(TraitedSpec):
+ out_mask = File(exists=False, desc="subtracted mask")
+
+
+class BinarySubtraction(SimpleInterface):
+ """Binary dilation of a mask."""
+
+ input_spec = _BinarySubtractInputSpec
+ output_spec = _BinarySubtractionOutputSpec
+
+ def _run_interface(self, runtime):
+ # Subtract mask from base
+ base_img = nb.load(self.inputs.in_base)
+ data = np.bool_(base_img.dataobj)
+ data[np.bool_(nb.load(self.inputs.in_subtract).dataobj)] = False
+
+ out_file = str((Path(runtime.cwd) / "dilated_mask.nii.gz").absolute())
+ out_img = base_img.__class__(
+ data,
+ base_img.affine,
+ base_img.header
+ )
+ out_img.set_data_dtype("uint8")
+ out_img.to_filename(out_file)
+ self._results["out_mask"] = out_file
+ return runtime
+
+
def image_binary_dilation(in_mask, radius=2):
"""
Dilate the input binary mask.
