Skip to content

Instantly share code, notes, and snippets.

@ysl2
Forked from ofgulban/dilate_erode_MRI_data.py
Created January 26, 2022 02:49
Show Gist options
  • Save ysl2/c30383abd4b0c4ac4cd5587acc543f82 to your computer and use it in GitHub Desktop.
Save ysl2/c30383abd4b0c4ac4cd5587acc543f82 to your computer and use it in GitHub Desktop.
Simple morphological operations on MRI data (nifti).
"""Dilation, erosion, opening, closing operations on binary nifti files."""
import os
import numpy as np
from scipy.ndimage import morphology
from nibabel import load, save, Nifti1Image
# Load data
nii = load('/path/to/your/file.nii.gz')
basename = nii.get_filename().split(os.extsep, 1)[0]
dirname = os.path.dirname(nii.get_filename())
data = np.asarray(nii.dataobj)
# Perform closing
data = morphology.binary_dilation(data, iterations=1)
data = morphology.binary_erosion(data, iterations=1)
# Perform opening
data = morphology.binary_erosion(data, iterations=1)
data = morphology.binary_dilation(data, iterations=1)
# Save as nifti
out = Nifti1Image(data, header=nii.header, affine=nii.affine)
save(out, basename + "_opening_closing.nii.gz")
print 'Finished.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment