Skip to content

Instantly share code, notes, and snippets.

@ofgulban
Created November 2, 2022 15:54
Show Gist options
  • Save ofgulban/a5d9f65f5da7cc2f2d25bc1dd0bc3732 to your computer and use it in GitHub Desktop.
Save ofgulban/a5d9f65f5da7cc2f2d25bc1dd0bc3732 to your computer and use it in GitHub Desktop.
Maximum intensity projection on nifti image
"""Maximum intensity projection over one dimension for a window."""
import os
import numpy as np
from nibabel import load, Nifti1Image, save
nii = load('/path/to/file.nii.gz')
w = 10 # window, total width is double of this number
data = (nii.get_fdata()).astype("int")
dims = data.shape
# -----------------------------------------------------------------------------
suffix = 'maip_{}_x'.format(w)
temp = np.zeros(dims)
for i in range(w, dims[0]-w):
temp[i, :, :] = np.max(data[i-w:i+w, :, :], axis=0)
print('Saving x...')
img = Nifti1Image(temp, affine=nii.affine)
temp = None
basename, ext = nii.get_filename().split(os.extsep, 1)
out_name = '{}_{}.{}'.format(basename, suffix, ext)
save(img, out_name)
# -----------------------------------------------------------------------------
suffix = 'maip_{}_y'.format(w)
temp = np.zeros(dims)
for i in range(w, dims[1]-w):
temp[:, i, :] = np.max(data[:, i-w:i+w, :], axis=1)
print('Saving y...')
img = Nifti1Image(temp, affine=nii.affine)
temp = None
basename, ext = nii.get_filename().split(os.extsep, 1)
out_name = '{}_{}.{}'.format(basename, suffix, ext)
save(img, out_name)
# -----------------------------------------------------------------------------
suffix = 'maip_{}_z'.format(w)
temp = np.zeros(dims)
for i in range(w, dims[2]-w):
temp[:, :, i] = np.max(data[:, :, i-w:i+w], axis=2)
print('Saving z...')
img = Nifti1Image(temp, affine=nii.affine)
temp = None
basename, ext = nii.get_filename().split(os.extsep, 1)
out_name = '{}_{}.{}'.format(basename, suffix, ext)
save(img, out_name)
print('Finished.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment