1
+ import nibabel as nib
1
2
from nibabel .fileslice import fill_slicer
3
+ import nibabel .pointset as ps
2
4
3
5
4
6
class CoordinateImage :
@@ -14,6 +16,22 @@ def __init__(self, data, coordaxis, header=None):
14
16
self .coordaxis = coordaxis
15
17
self .header = header
16
18
19
+ @classmethod
20
+ def from_image (klass , img ):
21
+ coordaxis = CoordinateAxis .from_header (img .header )
22
+ if isinstance (img , nib .Cifti2Image ):
23
+ if img .ndim != 2 :
24
+ raise ValueError ("Can only interpret 2D images" )
25
+ for i in img .header .mapped_indices :
26
+ if isinstance (img .header .get_axis (i ), nib .cifti2 .BrainModelAxis ):
27
+ break
28
+ # Reinterpret data ordering based on location of coordinate axis
29
+ data = img .dataobj .copy ()
30
+ data .order = ['F' , 'C' ][i ]
31
+ if i == 1 :
32
+ data ._shape = data ._shape [::- 1 ]
33
+ return klass (data , coordaxis , img .header )
34
+
17
35
18
36
class CoordinateAxis :
19
37
"""
@@ -81,6 +99,28 @@ def get_indices(self, parcel, indices=None):
81
99
def __len__ (self ):
82
100
return sum (len (parcel ) for parcel in self .parcels )
83
101
102
+ # Hacky factory method for now
103
+ @classmethod
104
+ def from_header (klass , hdr ):
105
+ parcels = []
106
+ if isinstance (hdr , nib .Cifti2Header ):
107
+ axes = [hdr .get_axis (i ) for i in hdr .mapped_indices ]
108
+ for ax in axes :
109
+ if isinstance (ax , nib .cifti2 .BrainModelAxis ):
110
+ break
111
+ else :
112
+ raise ValueError ("No BrainModelAxis, cannot create CoordinateAxis" )
113
+ for name , slicer , struct in ax .iter_structures ():
114
+ if struct .volume_shape :
115
+ substruct = ps .NdGrid (struct .volume_shape , struct .affine )
116
+ indices = struct .voxel
117
+ else :
118
+ substruct = None
119
+ indices = struct .vertex
120
+ parcels .append (Parcel (name , substruct , indices ))
121
+
122
+ return klass (parcels )
123
+
84
124
85
125
class Parcel :
86
126
"""
0 commit comments