Skip to content

Instantly share code, notes, and snippets.

@kaczmarj
Created May 24, 2018 15:22
Show Gist options
  • Save kaczmarj/0fd1b1d11e323d5b3a449188d569009c to your computer and use it in GitHub Desktop.
Save kaczmarj/0fd1b1d11e323d5b3a449188d569009c to your computer and use it in GitHub Desktop.
"""Example of how to get volume of tumor from mask NIfTI."""
import nibabel as nb
# The mask nifti image has contains a 1 in voxels that contain
# tumor and a 0 in voxels that do not contain tumor.
mask_filepath = "/path/to/tumor_mask.nii.gz"
img = nb.load(mask_filepath)
data = img.get_fdata()
# The tumor volume is the sum of all values in the mask array,
# because tumor voxels have a value 1 and non-tumor voxels have
# value 0.
tumor_volume = data.sum()
# Tumor volume can also be found by calculating the number of
# voxels that contain the label value.
# If the tumor label is 1:
tumor_volume = (data == 1).sum()
# If the tumor label is 20:
tumor_volume = (data == 20).sum()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment