Skip to content

Instantly share code, notes, and snippets.

@ofgulban
Last active September 24, 2020 18:17
Show Gist options
  • Save ofgulban/264fc958b19b8be8997016e1fa8d6375 to your computer and use it in GitHub Desktop.
Save ofgulban/264fc958b19b8be8997016e1fa8d6375 to your computer and use it in GitHub Desktop.
Compute volume of non-zero voxels in a nifti image.
"""Compute volume of non-zero voxels in a nifti image."""
import numpy as np
import nibabel as nb
INPUT = "/path/to/image.nii.gz"
# Load data
nii = nb.load(INPUT)
img = nii.get_fdata()
# Get voxel dimensions
voxel_dims = (nii.header["pixdim"])[1:4]
print("Voxel dimensions:")
print(" x = {} mm".format(voxel_dims[0]))
print(" y = {} mm".format(voxel_dims[1]))
print(" z = {} mm".format(voxel_dims[2]))
# Compute volume
nonzero_voxel_count = np.sum(img != 0)
voxel_volume = np.prod(voxel_dims)
nonzero_voxel_volume = nonzero_voxel_count * voxel_volume
print("Number of non-zero voxels = {}".format(nonzero_voxel_count))
print("Volume of non-zero voxels = {} mm^3".format(nonzero_voxel_volume))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment