Skip to content

Commit 3abff0d

Browse files
committed
NF: add function to check spatial axes are first
For the processing and the visualization routines, we need to know if the spatial axes are first, followed by time etc. Make a crude check that we can depend on spatial axes being first.
1 parent 82a261c commit 3abff0d

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

nibabel/imageclasses.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,22 @@ def __getitem__(self, *args, **kwargs):
104104
('mgz', '.mgz'),
105105
('par', '.par'),
106106
))
107+
108+
109+
def spatial_axes_first(img):
110+
""" True if spatial image axes for `img` always preceed other axes
111+
112+
Parameters
113+
----------
114+
img : object
115+
Image object implementing at least ``shape`` attribute.
116+
117+
Returns
118+
-------
119+
spatial_axes_first : bool
120+
True if image only has spatial axes (number of axes < 4) or image type
121+
known to have spatial axes preceeding other axes.
122+
"""
123+
if len(img.shape) < 4:
124+
return True
125+
return not isinstance(img, Minc1Image)

nibabel/tests/test_imageclasses.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
""" Testing imageclasses module
2+
"""
3+
4+
from os.path import dirname, join as pjoin
5+
6+
import numpy as np
7+
8+
from nibabel.optpkg import optional_package
9+
10+
import nibabel as nib
11+
from nibabel.analyze import AnalyzeImage
12+
from nibabel.nifti1 import Nifti1Image
13+
from nibabel.nifti2 import Nifti2Image
14+
15+
from nibabel.imageclasses import spatial_axes_first
16+
17+
from nose.tools import (assert_true, assert_false)
18+
19+
DATA_DIR = pjoin(dirname(__file__), 'data')
20+
21+
have_h5py = optional_package('h5py')[1]
22+
23+
MINC_3DS = ('minc1_1_scale.mnc',)
24+
MINC_4DS = ('minc1_4d.mnc',)
25+
if have_h5py:
26+
MINC_3DS = MINC_3DS + ('minc2_1_scale.mnc',)
27+
MINC_4DS = MINC_4DS + ('minc2_4d.mnc',)
28+
29+
30+
def test_spatial_axes_first():
31+
# Function tests is spatial axes are first three axes in image
32+
# Always True for Nifti and friends
33+
affine = np.eye(4)
34+
for shape in ((2, 3), (4, 3, 2), (5, 4, 1, 2), (2, 3, 5, 2, 1)):
35+
for img_class in (AnalyzeImage, Nifti1Image, Nifti2Image):
36+
data = np.zeros(shape)
37+
img = img_class(data, affine)
38+
assert_true(spatial_axes_first(img))
39+
# True for MINC images < 4D
40+
for fname in MINC_3DS:
41+
img = nib.load(pjoin(DATA_DIR, fname))
42+
assert_true(len(img.shape) == 3)
43+
assert_true(spatial_axes_first(img))
44+
# False for MINC images < 4D
45+
for fname in MINC_4DS:
46+
img = nib.load(pjoin(DATA_DIR, fname))
47+
assert_true(len(img.shape) == 4)
48+
assert_false(spatial_axes_first(img))

0 commit comments

Comments
 (0)