Skip to content

Instantly share code, notes, and snippets.

@ofgulban
Last active June 1, 2023 23:03
Show Gist options
  • Save ofgulban/21f9b257de849c546f34863aa26f3dd3 to your computer and use it in GitHub Desktop.
Save ofgulban/21f9b257de849c546f34863aa26f3dd3 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