13
13
import numpy as np
14
14
from nibabel .imageclasses import spatial_axes_first
15
15
16
+ def count_nonzero_voxels (img ):
17
+ """
18
+ Count number of non-zero voxels
19
+ Parameters
20
+ ----------
21
+ img : ``SpatialImage``
22
+ All voxels of the mask should be of value 1, background should have value 0.
23
+
24
+ Returns
25
+ -------
26
+ non zero voxel volume: int
27
+ Number of non-zero voxels
28
+
29
+ """
30
+ return np .count_nonzero (img .dataobj )
16
31
17
- def mask_volume (img , units = 'mm3' ):
32
+ def mask_volume (img ):
18
33
""" Compute volume of mask image.
19
34
Equivalent to "fslstats /path/file.nii -V"
20
35
@@ -23,36 +38,24 @@ def mask_volume(img, units='mm3'):
23
38
img : ``SpatialImage``
24
39
All voxels of the mask should be of value 1, background should have value 0.
25
40
26
- units : string {"mm3", "vox"}, optional
27
- Unit of the returned mask volume. Defaults to "mm3".
28
41
29
42
Returns
30
43
-------
31
- mask_volume_vx: float
32
- Volume of mask expressed in voxels.
33
-
34
- or
35
-
36
44
mask_volume_mm3: float
37
45
Volume of mask expressed in mm3.
38
46
39
47
Examples
40
48
--------
41
- >>> import nibabel as nf
42
- >>> path = 'path/to/nifti/mask.nii'
43
- >>> img = nf.load(path) # path is contains a path to an example nifti mask
44
- >>> mask_volume(img )
45
- 50.3021
49
+ >>> import nibabel as nb
50
+ >>> mask_data = np.zeros((20, 20, 20), dtype='u1')
51
+ >>> mask_data[5:15, 5:15, 5:15] = 1
52
+ >>> nb.imagestats. mask_volume(nb.Nifti1Image(mask_data, np.eye(4) )
53
+ 1000.0
46
54
"""
47
55
if not spatial_axes_first (img ):
48
56
raise ValueError ("Cannot calculate voxel volume for image with unknown spatial axes" )
49
57
voxel_volume_mm3 = np .prod (img .header .get_zooms ()[:3 ])
50
- mask_volume_vx = np . count_nonzero (img . dataobj )
58
+ mask_volume_vx = count_nonzero_voxels (img )
51
59
mask_volume_mm3 = mask_volume_vx * voxel_volume_mm3
52
60
53
- if units == 'vox' :
54
- return mask_volume_vx
55
- elif units == 'mm3' :
56
- return mask_volume_mm3
57
- else :
58
- raise ValueError (f'{ units } is not a valid unit. Choose "mm3" or "vox".' )
61
+ return mask_volume_mm3
0 commit comments