|
2 | 2 | import os
|
3 | 3 | import warnings
|
4 | 4 | import numpy as np
|
| 5 | +from numpy.linalg import inv |
5 | 6 | from pathlib import Path
|
6 |
| -from nibabel import load as _nbload |
7 | 7 | from nibabel.affines import voxel_sizes
|
8 | 8 |
|
9 |
| -from .base import BaseLinearTransformList, LinearParameters, TransformFileError |
| 9 | +from .base import ( |
| 10 | + BaseLinearTransformList, |
| 11 | + LinearParameters, |
| 12 | + TransformFileError, |
| 13 | + _ensure_image, |
| 14 | +) |
10 | 15 |
|
11 | 16 |
|
12 | 17 | class FSLLinearTransform(LinearParameters):
|
@@ -41,14 +46,14 @@ def from_ras(cls, ras, moving=None, reference=None):
|
41 | 46 |
|
42 | 47 | # Adjust for reference image offset and orientation
|
43 | 48 | refswp, refspc = _fsl_aff_adapt(reference)
|
44 |
| - pre = reference.affine.dot(np.linalg.inv(refspc).dot(np.linalg.inv(refswp))) |
| 49 | + pre = reference.affine.dot(inv(refspc).dot(inv(refswp))) |
45 | 50 |
|
46 | 51 | # Adjust for moving image offset and orientation
|
47 | 52 | movswp, movspc = _fsl_aff_adapt(moving)
|
48 |
| - post = np.linalg.inv(movswp).dot(movspc.dot(np.linalg.inv(moving.affine))) |
| 53 | + post = inv(movswp).dot(movspc.dot(inv(moving.affine))) |
49 | 54 |
|
50 | 55 | # Compose FSL transform
|
51 |
| - mat = np.linalg.inv(np.swapaxes(post.dot(ras.dot(pre)), 0, 1)) |
| 56 | + mat = inv(np.swapaxes(post.dot(ras.dot(pre)), 0, 1)) |
52 | 57 |
|
53 | 58 | tf = cls()
|
54 | 59 | tf.structarr["parameters"] = mat.T
|
@@ -84,19 +89,13 @@ def to_ras(self, moving=None, reference=None):
|
84 | 89 | moving = _ensure_image(moving)
|
85 | 90 |
|
86 | 91 | refswp, refspc = _fsl_aff_adapt(reference)
|
87 |
| - pre = reference.affine.dot(np.linalg.inv(refspc).dot(np.linalg.inv(refswp))) |
88 | 92 |
|
| 93 | + pre = refswp @ refspc @ inv(reference.affine) |
89 | 94 | # Adjust for moving image offset and orientation
|
90 | 95 | movswp, movspc = _fsl_aff_adapt(moving)
|
91 |
| - post = np.linalg.inv(movswp).dot(movspc.dot(np.linalg.inv(moving.affine))) |
92 |
| - |
| 96 | + post = moving.affine @ inv(movspc) @ inv(movswp) |
93 | 97 | mat = self.structarr["parameters"].T
|
94 |
| - |
95 |
| - return ( |
96 |
| - np.linalg.inv(post) |
97 |
| - @ np.swapaxes(np.linalg.inv(mat), 0, 1) |
98 |
| - @ np.linalg.inv(pre) |
99 |
| - ) |
| 98 | + return post @ np.swapaxes(inv(mat), 0, 1) @ pre |
100 | 99 |
|
101 | 100 |
|
102 | 101 | class FSLLinearTransformArray(BaseLinearTransformList):
|
@@ -187,9 +186,3 @@ def _fsl_aff_adapt(space):
|
187 | 186 | swp[0, 0] = -1.0
|
188 | 187 | swp[0, 3] = (space.shape[0] - 1) * zooms[0]
|
189 | 188 | return swp, np.diag(zooms)
|
190 |
| - |
191 |
| - |
192 |
| -def _ensure_image(img): |
193 |
| - if isinstance(img, (str, Path)): |
194 |
| - return _nbload(img) |
195 |
| - return img |
0 commit comments