|
3 | 3 | import numpy as np |
4 | 4 |
|
5 | 5 |
|
6 | | -def as_canonical(img): |
7 | | - """Drop rotation w.r.t. cardinal axes of input image.""" |
| 6 | +def rotation2canonical(img): |
| 7 | + """Calculate the rotation w.r.t. cardinal axes of input image.""" |
8 | 8 | img = nb.as_closest_canonical(img) |
9 | | - zooms = list(img.header.get_zooms()[:3]) |
10 | | - newaff = np.diag(zooms + [1]) |
11 | | - rot = newaff[:3, :3].dot(np.linalg.inv(img.affine[:3, :3])) |
12 | | - newaff[:3, 3] = rot.dot(img.affine[:3, 3]) |
13 | | - return nb.Nifti1Image(img.dataobj, newaff, img.header) |
| 9 | + newaff = np.diag(img.header.get_zooms()[:3]) |
| 10 | + r = newaff @ np.linalg.inv(img.affine[:3, :3]) |
| 11 | + if np.allclose(r, np.eye(3)): |
| 12 | + return None |
| 13 | + return r |
| 14 | + |
| 15 | + |
| 16 | +def rotate_affine(img, rot=None): |
| 17 | + """Rewrite the affine of a spatial image.""" |
| 18 | + if rot is None: |
| 19 | + return img |
| 20 | + |
| 21 | + img = nb.as_closest_canonical(img) |
| 22 | + affine = np.eye(4) |
| 23 | + affine[:3, :3] = rot @ img.affine[:3, :3] |
| 24 | + affine[:3, 3] = rot @ img.affine[:3, 3] |
| 25 | + return img.__class__(img.dataobj, affine, img.header) |
14 | 26 |
|
15 | 27 |
|
16 | 28 | def unsafe_write_nifti_header_and_data(fname, header, data): |
|
0 commit comments