|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- |
| 3 | +# vi: set ft=python sts=4 ts=4 sw=4 et: |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import nibabel as nb |
| 7 | + |
| 8 | +from ..utils.filemanip import fname_presuffix |
| 9 | +from .base import (SimpleInterface, TraitedSpec, BaseInterfaceInputSpec, |
| 10 | + traits, File) |
| 11 | + |
| 12 | +_axes = ('RL', 'AP', 'SI') |
| 13 | +_orientations = tuple( |
| 14 | + ''.join((x[i], y[j], z[k])) |
| 15 | + for x in _axes for y in _axes for z in _axes |
| 16 | + if x != y != z != x |
| 17 | + for i in (0, 1) for j in (0, 1) for k in (0, 1)) |
| 18 | + |
| 19 | + |
| 20 | +class ReorientInputSpec(BaseInterfaceInputSpec): |
| 21 | + in_file = File(exists=True, mandatory=True, desc='Input image') |
| 22 | + orientation = traits.Enum(_orientations, usedefault=True, |
| 23 | + desc='Target axis orientation') |
| 24 | + |
| 25 | + |
| 26 | +class ReorientOutputSpec(TraitedSpec): |
| 27 | + out_file = File(exists=True, desc='Reoriented image') |
| 28 | + transform = File(exists=True, |
| 29 | + desc='Affine transform from input orientation to output') |
| 30 | + |
| 31 | + |
| 32 | +class Reorient(SimpleInterface): |
| 33 | + """Conform an image to a given orientation |
| 34 | +
|
| 35 | + Flips and reorder the image data array so that the axes match the |
| 36 | + directions indicated in ``orientation``. |
| 37 | + The default ``RAS`` orientation corresponds to the first axis being ordered |
| 38 | + from left to right, the second axis from posterior to anterior, and the |
| 39 | + third axis from inferior to superior. |
| 40 | +
|
| 41 | + For oblique images, the original orientation is considered to be the |
| 42 | + closest plumb orientation. |
| 43 | +
|
| 44 | + No resampling is performed, and thus the output image is not de-obliqued |
| 45 | + or registered to any other image or template. |
| 46 | +
|
| 47 | + The effective transform is calculated from the original affine matrix to |
| 48 | + the reoriented affine matrix. |
| 49 | +
|
| 50 | + Examples |
| 51 | + -------- |
| 52 | +
|
| 53 | + If an image is not reoriented, the original file is not modified |
| 54 | +
|
| 55 | + >>> import numpy as np |
| 56 | + >>> from nipype.interfaces.image import Reorient |
| 57 | + >>> reorient = Reorient(orientation='LPS') |
| 58 | + >>> reorient.inputs.in_file = 'segmentation0.nii.gz' |
| 59 | + >>> res = reorient.run() |
| 60 | + >>> res.outputs.out_file |
| 61 | + 'segmentation0.nii.gz' |
| 62 | +
|
| 63 | + >>> print(np.loadtxt(res.outputs.transform)) |
| 64 | + [[1. 0. 0. 0.] |
| 65 | + [0. 1. 0. 0.] |
| 66 | + [0. 0. 1. 0.] |
| 67 | + [0. 0. 0. 1.]] |
| 68 | +
|
| 69 | + >>> reorient.inputs.orientation = 'RAS' |
| 70 | + >>> res = reorient.run() |
| 71 | + >>> res.outputs.out_file # doctest: +ELLIPSIS |
| 72 | + '.../segmentation0_ras.nii.gz' |
| 73 | +
|
| 74 | + >>> print(np.loadtxt(res.outputs.transform)) |
| 75 | + [[-1. 0. 0. 60.] |
| 76 | + [ 0. -1. 0. 72.] |
| 77 | + [ 0. 0. 1. 0.] |
| 78 | + [ 0. 0. 0. 1.]] |
| 79 | +
|
| 80 | + """ |
| 81 | + input_spec = ReorientInputSpec |
| 82 | + output_spec = ReorientOutputSpec |
| 83 | + |
| 84 | + def _run_interface(self, runtime): |
| 85 | + from nibabel.orientations import ( |
| 86 | + axcodes2ornt, ornt_transform, inv_ornt_aff) |
| 87 | + |
| 88 | + fname = self.inputs.in_file |
| 89 | + orig_img = nb.load(fname) |
| 90 | + |
| 91 | + # Find transform from current (approximate) orientation to |
| 92 | + # target, in nibabel orientation matrix and affine forms |
| 93 | + orig_ornt = nb.io_orientation(orig_img.affine) |
| 94 | + targ_ornt = axcodes2ornt(self.inputs.orientation) |
| 95 | + transform = ornt_transform(orig_ornt, targ_ornt) |
| 96 | + affine_xfm = inv_ornt_aff(transform, orig_img.shape) |
| 97 | + |
| 98 | + # Check can be eliminated when minimum nibabel version >= 2.2 |
| 99 | + if hasattr(orig_img, 'as_reoriented'): |
| 100 | + reoriented = orig_img.as_reoriented(transform) |
| 101 | + else: |
| 102 | + reoriented = _as_reoriented_backport(orig_img, transform) |
| 103 | + |
| 104 | + # Image may be reoriented |
| 105 | + if reoriented is not orig_img: |
| 106 | + suffix = '_' + self.inputs.orientation.lower() |
| 107 | + out_name = fname_presuffix(fname, suffix=suffix, |
| 108 | + newpath=runtime.cwd) |
| 109 | + reoriented.to_filename(out_name) |
| 110 | + else: |
| 111 | + out_name = fname |
| 112 | + |
| 113 | + mat_name = fname_presuffix(fname, suffix='.mat', |
| 114 | + newpath=runtime.cwd, use_ext=False) |
| 115 | + np.savetxt(mat_name, affine_xfm, fmt='%.08f') |
| 116 | + |
| 117 | + self._results['out_file'] = out_name |
| 118 | + self._results['transform'] = mat_name |
| 119 | + |
| 120 | + return runtime |
| 121 | + |
| 122 | + |
| 123 | +def _as_reoriented_backport(img, ornt): |
| 124 | + """Backport of img.as_reoriented as of nibabel 2.2.0""" |
| 125 | + from nibabel.orientations import inv_ornt_aff |
| 126 | + if np.array_equal(ornt, [[0, 1], [1, 1], [2, 1]]): |
| 127 | + return img |
| 128 | + |
| 129 | + t_arr = nb.apply_orientation(img.get_data(), ornt) |
| 130 | + new_aff = img.affine.dot(inv_ornt_aff(ornt, img.shape)) |
| 131 | + reoriented = img.__class__(t_arr, new_aff, img.header) |
| 132 | + |
| 133 | + if isinstance(reoriented, nb.Nifti1Pair): |
| 134 | + # Also apply the transform to the dim_info fields |
| 135 | + new_dim = list(reoriented.header.get_dim_info()) |
| 136 | + for idx, value in enumerate(new_dim): |
| 137 | + # For each value, leave as None if it was that way, |
| 138 | + # otherwise check where we have mapped it to |
| 139 | + if value is None: |
| 140 | + continue |
| 141 | + new_dim[idx] = np.where(ornt[:, 0] == idx)[0] |
| 142 | + |
| 143 | + reoriented.header.set_dim_info(*new_dim) |
| 144 | + |
| 145 | + return reoriented |
0 commit comments