-
Notifications
You must be signed in to change notification settings - Fork 262
NF: volume computation function for nifti masks #952
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d7c7069
Added a volume computation function
JulianKlug 73bff0f
Added commandline and tests for imagestats volume computation
JulianKlug 57f7723
Fix style errors
JulianKlug e15bb8d
Apply suggestions from code review: Removing unused code
JulianKlug 7412ba9
Apply suggestions from code review: Use header.get_zooms instead of h…
JulianKlug d357eae
Split Mask_volume into a function for voxels and a function for volum…
JulianKlug 93532de
Fix failing docstring
JulianKlug 2331e9d
Apply suggestions from code review
JulianKlug 35beaba
Style issues, use capsys
JulianKlug File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
#!python | ||
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- | ||
# vi: set ft=python sts=4 ts=4 sw=4 et: | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
# | ||
# See COPYING file distributed along with the NiBabel package for the | ||
# copyright and license terms. | ||
# | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
""" | ||
Compute image statistics | ||
""" | ||
|
||
import argparse | ||
from nibabel.loadsave import load | ||
from nibabel.imagestats import mask_volume, count_nonzero_voxels | ||
|
||
|
||
def _get_parser(): | ||
"""Return command-line argument parser.""" | ||
p = argparse.ArgumentParser(description=__doc__) | ||
p.add_argument("infile", | ||
help="Neuroimaging volume to compute statistics on.") | ||
p.add_argument("-V", "--Volume", action="store_true", required=False, | ||
help="Compute mask volume of a given mask image.") | ||
p.add_argument("--units", default="mm3", required=False, | ||
choices=("mm3", "vox"), help="Preferred output units") | ||
return p | ||
|
||
|
||
def main(args=None): | ||
"""Main program function.""" | ||
parser = _get_parser() | ||
opts = parser.parse_args(args) | ||
from_img = load(opts.infile) | ||
|
||
if opts.Volume: | ||
if opts.units == 'mm3': | ||
computed_volume = mask_volume(from_img) | ||
elif opts.units == 'vox': | ||
computed_volume = count_nonzero_voxels(from_img) | ||
else: | ||
raise ValueError(f'{opts.units} is not a valid unit. Choose "mm3" or "vox".') | ||
print(computed_volume) | ||
return 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
#!python | ||
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- | ||
# vi: set ft=python sts=4 ts=4 sw=4 et: | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
# | ||
# See COPYING file distributed along with the NiBabel package for the | ||
# copyright and license terms. | ||
# | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
|
||
from io import StringIO | ||
import sys | ||
import numpy as np | ||
|
||
from nibabel.loadsave import save | ||
from nibabel.cmdline.stats import main | ||
from nibabel import Nifti1Image | ||
|
||
|
||
def test_volume(tmpdir, capsys): | ||
mask_data = np.zeros((20, 20, 20), dtype='u1') | ||
mask_data[5:15, 5:15, 5:15] = 1 | ||
img = Nifti1Image(mask_data, np.eye(4)) | ||
|
||
infile = tmpdir / "input.nii" | ||
save(img, infile) | ||
|
||
args = (f"{infile} --Volume") | ||
main(args.split()) | ||
vol_mm3 = capsys.readouterr() | ||
args = (f"{infile} --Volume --units vox") | ||
main(args.split()) | ||
vol_vox = capsys.readouterr() | ||
|
||
assert float(vol_mm3[0]) == 1000.0 | ||
assert int(vol_vox[0]) == 1000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- | ||
# vi: set ft=python sts=4 ts=4 sw=4 et: | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
# | ||
# See COPYING file distributed along with the NiBabel package for the | ||
# copyright and license terms. | ||
# | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
""" | ||
Functions for computing image statistics | ||
""" | ||
|
||
import numpy as np | ||
from nibabel.imageclasses import spatial_axes_first | ||
|
||
|
||
def count_nonzero_voxels(img): | ||
""" | ||
Count number of non-zero voxels | ||
JulianKlug marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Parameters | ||
---------- | ||
img : ``SpatialImage`` | ||
All voxels of the mask should be of value 1, background should have value 0. | ||
|
||
Returns | ||
------- | ||
count : int | ||
Number of non-zero voxels | ||
|
||
""" | ||
return np.count_nonzero(img.dataobj) | ||
|
||
|
||
def mask_volume(img): | ||
""" Compute volume of mask image. | ||
JulianKlug marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Equivalent to "fslstats /path/file.nii -V" | ||
|
||
Parameters | ||
---------- | ||
img : ``SpatialImage`` | ||
All voxels of the mask should be of value 1, background should have value 0. | ||
|
||
|
||
Returns | ||
------- | ||
volume : float | ||
Volume of mask expressed in mm3. | ||
|
||
Examples | ||
-------- | ||
>>> import numpy as np | ||
>>> import nibabel as nb | ||
>>> mask_data = np.zeros((20, 20, 20), dtype='u1') | ||
>>> mask_data[5:15, 5:15, 5:15] = 1 | ||
>>> nb.imagestats.mask_volume(nb.Nifti1Image(mask_data, np.eye(4))) | ||
1000.0 | ||
""" | ||
if not spatial_axes_first(img): | ||
raise ValueError("Cannot calculate voxel volume for image with unknown spatial axes") | ||
voxel_volume_mm3 = np.prod(img.header.get_zooms()[:3]) | ||
mask_volume_vx = count_nonzero_voxels(img) | ||
mask_volume_mm3 = mask_volume_vx * voxel_volume_mm3 | ||
|
||
return mask_volume_mm3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- | ||
# vi: set ft=python sts=4 ts=4 sw=4 et: | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
# | ||
# See COPYING file distributed along with the NiBabel package for the | ||
# copyright and license terms. | ||
# | ||
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## | ||
""" Tests for image statistics """ | ||
|
||
import numpy as np | ||
|
||
from .. import imagestats | ||
from .. import Nifti1Image | ||
|
||
|
||
def test_mask_volume(): | ||
# Test mask volume computation | ||
|
||
mask_data = np.zeros((20, 20, 20), dtype='u1') | ||
mask_data[5:15, 5:15, 5:15] = 1 | ||
img = Nifti1Image(mask_data, np.eye(4)) | ||
|
||
vol_mm3 = imagestats.mask_volume(img) | ||
vol_vox = imagestats.count_nonzero_voxels(img) | ||
|
||
assert vol_mm3 == 1000.0 | ||
assert vol_vox == 1000 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.