Skip to content

Commit 7cdab20

Browse files
committed
enh: minor refactor for a more consistent rotation of inputs
1 parent 8208368 commit 7cdab20

File tree

2 files changed

+25
-11
lines changed

2 files changed

+25
-11
lines changed

niworkflows/utils/images.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,26 @@
33
import numpy as np
44

55

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."""
88
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)
1426

1527

1628
def unsafe_write_nifti_header_and_data(fname, header, data):

niworkflows/viz/utils.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
from nipype.utils import filemanip
2222
from .. import NIWORKFLOWS_LOG
23-
from ..utils.images import as_canonical
23+
from ..utils.images import rotation2canonical, rotate_affine
2424

2525

2626
SVGNS = "http://www.w3.org/2000/svg"
@@ -233,15 +233,17 @@ def plot_segs(
233233
"""
234234
plot_params = {} if plot_params is None else plot_params
235235

236-
image_nii = as_canonical(_3d_in_file(image_nii))
237-
seg_niis = [as_canonical(_3d_in_file(f)) for f in seg_niis]
236+
image_nii = _3d_in_file(image_nii)
237+
canonical_r = rotation2canonical(image_nii)
238+
image_nii = rotate_affine(image_nii, rot=canonical_r)
239+
seg_niis = [rotate_affine(_3d_in_file(f), rot=canonical_r) for f in seg_niis]
238240
data = image_nii.get_fdata()
239241

240242
plot_params = robust_set_limits(data, plot_params)
241243

242244
bbox_nii = (
243245
image_nii if bbox_nii is None
244-
else as_canonical(_3d_in_file(bbox_nii))
246+
else rotate_affine(_3d_in_file(bbox_nii), rot=canonical_r)
245247
)
246248

247249
if masked:

0 commit comments

Comments
 (0)