-
Notifications
You must be signed in to change notification settings - Fork 521
/
utils.py
183 lines (147 loc) · 5.65 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# -*- coding: utf-8 -*-
# coding: utf-8
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Generic interfaces to manipulate registration parameters files, including
transform files (to configure warpings)
"""
import os.path as op
from ... import logging
from ..base import (
BaseInterface,
BaseInterfaceInputSpec,
isdefined,
TraitedSpec,
File,
traits,
)
iflogger = logging.getLogger("nipype.interface")
class EditTransformInputSpec(BaseInterfaceInputSpec):
transform_file = File(
exists=True, mandatory=True, desc="transform-parameter file, only 1"
)
reference_image = File(
exists=True,
desc=("set a new reference image to change the " "target coordinate system."),
)
interpolation = traits.Enum(
"cubic",
"linear",
"nearest",
usedefault=True,
argstr="FinalBSplineInterpolationOrder",
desc="set a new interpolator for transformation",
)
output_type = traits.Enum(
"float",
"unsigned char",
"unsigned short",
"short",
"unsigned long",
"long",
"double",
argstr="ResultImagePixelType",
desc="set a new output pixel type for resampled images",
)
output_format = traits.Enum(
"nii.gz",
"nii",
"mhd",
"hdr",
"vtk",
argstr="ResultImageFormat",
desc="set a new image format for resampled images",
)
output_file = File(desc="the filename for the resulting transform file")
class EditTransformOutputSpec(TraitedSpec):
output_file = File(exists=True, desc="output transform file")
class EditTransform(BaseInterface):
"""
Manipulates an existing transform file generated with elastix
Example
-------
>>> from nipype.interfaces.elastix import EditTransform
>>> tfm = EditTransform()
>>> tfm.inputs.transform_file = 'TransformParameters.0.txt' # doctest: +SKIP
>>> tfm.inputs.reference_image = 'fixed1.nii' # doctest: +SKIP
>>> tfm.inputs.output_type = 'unsigned char'
>>> tfm.run() # doctest: +SKIP
"""
input_spec = EditTransformInputSpec
output_spec = EditTransformOutputSpec
_out_file = ""
_pattern = r'\((?P<entry>%s\s"?)([-\.\s\w]+)("?\))'
_interp = {"nearest": 0, "linear": 1, "cubic": 3}
def _run_interface(self, runtime):
import re
import nibabel as nb
import numpy as np
contents = ""
with open(self.inputs.transform_file, "r") as f:
contents = f.read()
if isdefined(self.inputs.output_type):
p = re.compile(
(self._pattern % "ResultImagePixelType").decode("string-escape")
)
rep = r"(\g<entry>%s\g<3>" % self.inputs.output_type
contents = p.sub(rep, contents)
if isdefined(self.inputs.output_format):
p = re.compile(
(self._pattern % "ResultImageFormat").decode("string-escape")
)
rep = r"(\g<entry>%s\g<3>" % self.inputs.output_format
contents = p.sub(rep, contents)
if isdefined(self.inputs.interpolation):
p = re.compile(
(self._pattern % "FinalBSplineInterpolationOrder").decode(
"string-escape"
)
)
rep = r"(\g<entry>%s\g<3>" % self._interp[self.inputs.interpolation]
contents = p.sub(rep, contents)
if isdefined(self.inputs.reference_image):
im = nb.load(self.inputs.reference_image)
if len(im.header.get_zooms()) == 4:
im = nb.func.four_to_three(im)[0]
size = " ".join(["%01d" % s for s in im.shape])
p = re.compile((self._pattern % "Size").decode("string-escape"))
rep = r"(\g<entry>%s\g<3>" % size
contents = p.sub(rep, contents)
index = " ".join(["0" for s in im.shape])
p = re.compile((self._pattern % "Index").decode("string-escape"))
rep = r"(\g<entry>%s\g<3>" % index
contents = p.sub(rep, contents)
spacing = " ".join(["%0.4f" % f for f in im.header.get_zooms()])
p = re.compile((self._pattern % "Spacing").decode("string-escape"))
rep = r"(\g<entry>%s\g<3>" % spacing
contents = p.sub(rep, contents)
itkmat = np.eye(4)
itkmat[0, 0] = -1
itkmat[1, 1] = -1
affine = np.dot(itkmat, im.affine)
dirs = " ".join(["%0.4f" % f for f in affine[0:3, 0:3].reshape(-1)])
orig = " ".join(["%0.4f" % f for f in affine[0:3, 3].reshape(-1)])
# p = re.compile((self._pattern % 'Direction').decode('string-escape'))
# rep = '(\g<entry>%s\g<3>' % dirs
# contents = p.sub(rep, contents)
p = re.compile((self._pattern % "Origin").decode("string-escape"))
rep = r"(\g<entry>%s\g<3>" % orig
contents = p.sub(rep, contents)
with open(self._get_outfile(), "w") as of:
of.write(contents)
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["output_file"] = getattr(self, "_out_file")
return outputs
def _get_outfile(self):
val = getattr(self, "_out_file")
if val is not None and val != "":
return val
if isdefined(self.inputs.output_file):
setattr(self, "_out_file", self.inputs.output_file)
return self.inputs.output_file
out_file = op.abspath(op.basename(self.inputs.transform_file))
setattr(self, "_out_file", out_file)
return out_file