Skip to content

Commit d7c7069

Browse files
authored
Added a volume computation function
Compute volume of mask image. Equivalent to "fslstats /path/file.nii -V"
1 parent e65b865 commit d7c7069

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

nibabel/funcs.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,34 @@ def _aff_is_diag(aff):
215215
""" Utility function returning True if affine is nearly diagonal """
216216
rzs_aff = aff[:3, :3]
217217
return np.allclose(rzs_aff, np.diag(np.diag(rzs_aff)))
218+
219+
220+
def mask_volume(img):
221+
""" Compute volume of mask image.
222+
Equivalent to "fslstats /path/file.nii -V"
223+
224+
Parameters
225+
----------
226+
img : ``SpatialImage``
227+
All voxels of the mask should be of value 1, background should have value 0.
228+
229+
Returns
230+
-------
231+
mask_volume_mm3: float
232+
Volume of mask expressed in mm3.
233+
234+
Examples
235+
--------
236+
>>> import nibabel as nf
237+
>>> img = nf.load(path) # path is contains a path to an example nifti mask
238+
>>> mask_volume(img)
239+
50.3021
240+
"""
241+
header = img.header
242+
_, vx, vy, vz, _, _, _, _ = header['pixdim']
243+
voxel_volume_mm3 = vx * vy * vz
244+
mask = img.get_fdata()
245+
mask_volume_vx = np.sum(mask)
246+
mask_volume_mm3 = mask_volume_vx * voxel_volume_mm3
247+
248+
return mask_volume_mm3

0 commit comments

Comments
 (0)