Skip to content

Commit 2ec1f10

Browse files
committed
ENH: Enable conversion to RAS+ of affine transforms
1 parent ed7e8ad commit 2ec1f10

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

nitransforms/io/afni.py

+36-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Read/write AFNI's transforms."""
22
from math import pi
3+
import warnings
34
import numpy as np
45
from nibabel.affines import obliquity, voxel_sizes
56

@@ -18,6 +19,39 @@ def __str__(self):
1819
param = self.structarr['parameters']
1920
return '\t'.join(['%g' % p for p in param[:3, :].reshape(-1)])
2021

22+
def to_ras(self, moving=None, reference=None):
23+
"""Convert to RAS+ coordinate system."""
24+
pre = LPS.copy()
25+
post = LPS.copy()
26+
27+
if moving is None:
28+
moving = reference
29+
30+
if reference is None:
31+
warnings.warn('At least, the reference image should be set.')
32+
else:
33+
if _is_oblique(reference.affine):
34+
warnings.warn('Reference affine axes are oblique.')
35+
M = reference.affine
36+
A = shape_zoom_affine(reference.shape,
37+
voxel_sizes(M), x_flip=False, y_flip=False)
38+
pre = M.dot(np.linalg.inv(A)).dot(LPS)
39+
40+
if _is_oblique(moving.affine):
41+
warnings.warn('Moving affine axes are oblique.')
42+
M2 = moving.affine
43+
A2 = shape_zoom_affine(moving.shape,
44+
voxel_sizes(M2), x_flip=True, y_flip=True)
45+
post = A2.dot(np.linalg.inv(M2))
46+
47+
pre = np.linalg.inv(pre)
48+
post = np.linalg.inv(post)
49+
50+
# swapaxes is necessary, as axis 0 encodes series of transforms
51+
ras = self.structarr['parameters'].copy()
52+
parameters = np.swapaxes(post.dot(ras.dot(pre)), 0, 1).T
53+
return parameters
54+
2155
def to_string(self, banner=True):
2256
"""Convert to a string directly writeable to file."""
2357
string = '%s\n' % self
@@ -33,14 +67,14 @@ def from_ras(cls, ras, moving=None, reference=None):
3367
pre = LPS.copy()
3468
post = LPS.copy()
3569
if _is_oblique(reference.affine):
36-
print('Reference affine axes are oblique.')
70+
warnings.warn('Reference affine axes are oblique.')
3771
M = reference.affine
3872
A = shape_zoom_affine(reference.shape,
3973
voxel_sizes(M), x_flip=False, y_flip=False)
4074
pre = M.dot(np.linalg.inv(A)).dot(LPS)
4175

4276
if _is_oblique(moving.affine):
43-
print('Moving affine axes are oblique.')
77+
warnings.warn('Moving affine axes are oblique.')
4478
M2 = moving.affine
4579
A2 = shape_zoom_affine(moving.shape,
4680
voxel_sizes(M2), x_flip=True, y_flip=True)

0 commit comments

Comments
 (0)