PageRenderTime 57ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/nipype/interfaces/elastix/registration.py

https://github.com/yarikoptic/nipype
Python | 285 lines | 259 code | 9 blank | 17 comment | 2 complexity | 0f6fd94a9a7c5e948311f160c2be94c5 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. # coding: utf-8
  3. # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
  4. # vi: set ft=python sts=4 ts=4 sw=4 et:
  5. """
  6. Interfaces to perform image registrations and to apply the resulting
  7. displacement maps to images and points.
  8. """
  9. from __future__ import (print_function, division, unicode_literals,
  10. absolute_import)
  11. from builtins import open
  12. import os.path as op
  13. import re
  14. from ... import logging
  15. from .base import ElastixBaseInputSpec
  16. from ..base import CommandLine, TraitedSpec, File, traits, InputMultiPath
  17. iflogger = logging.getLogger('nipype.interface')
  18. class RegistrationInputSpec(ElastixBaseInputSpec):
  19. fixed_image = File(
  20. exists=True, mandatory=True, argstr='-f %s', desc='fixed image')
  21. moving_image = File(
  22. exists=True, mandatory=True, argstr='-m %s', desc='moving image')
  23. parameters = InputMultiPath(
  24. File(exists=True),
  25. mandatory=True,
  26. argstr='-p %s...',
  27. desc='parameter file, elastix handles 1 or more -p')
  28. fixed_mask = File(
  29. exists=True, argstr='-fMask %s', desc='mask for fixed image')
  30. moving_mask = File(
  31. exists=True, argstr='-mMask %s', desc='mask for moving image')
  32. initial_transform = File(
  33. exists=True,
  34. argstr='-t0 %s',
  35. desc='parameter file for initial transform')
  36. class RegistrationOutputSpec(TraitedSpec):
  37. transform = InputMultiPath(File(exists=True), desc='output transform')
  38. warped_file = File(desc='input moving image warped to fixed image')
  39. warped_files = InputMultiPath(
  40. File(exists=False),
  41. desc=('input moving image warped to fixed image at each level'))
  42. warped_files_flags = traits.List(
  43. traits.Bool(False),
  44. desc='flag indicating if warped image was generated')
  45. class Registration(CommandLine):
  46. """
  47. Elastix nonlinear registration interface
  48. Example
  49. -------
  50. >>> from nipype.interfaces.elastix import Registration
  51. >>> reg = Registration()
  52. >>> reg.inputs.fixed_image = 'fixed1.nii'
  53. >>> reg.inputs.moving_image = 'moving1.nii'
  54. >>> reg.inputs.parameters = ['elastix.txt']
  55. >>> reg.cmdline
  56. 'elastix -f fixed1.nii -m moving1.nii -threads 1 -out ./ -p elastix.txt'
  57. """
  58. _cmd = 'elastix'
  59. input_spec = RegistrationInputSpec
  60. output_spec = RegistrationOutputSpec
  61. def _list_outputs(self):
  62. outputs = self._outputs().get()
  63. out_dir = op.abspath(self.inputs.output_path)
  64. regex = re.compile(r'^\((\w+)\s(.+)\)$')
  65. outputs['transform'] = []
  66. outputs['warped_files'] = []
  67. outputs['warped_files_flags'] = []
  68. for i, params in enumerate(self.inputs.parameters):
  69. config = {}
  70. with open(params, 'r') as f:
  71. for line in f.readlines():
  72. line = line.strip()
  73. if not line.startswith('//') and line:
  74. m = regex.search(line)
  75. if m:
  76. value = self._cast(m.group(2).strip())
  77. config[m.group(1).strip()] = value
  78. outputs['transform'].append(
  79. op.join(out_dir, 'TransformParameters.%01d.txt' % i))
  80. warped_file = None
  81. if config['WriteResultImage']:
  82. warped_file = op.join(out_dir, 'result.%01d.%s' %
  83. (i, config['ResultImageFormat']))
  84. outputs['warped_files'].append(warped_file)
  85. outputs['warped_files_flags'].append(config['WriteResultImage'])
  86. if outputs['warped_files_flags'][-1]:
  87. outputs['warped_file'] = outputs['warped_files'][-1]
  88. return outputs
  89. def _cast(self, val):
  90. if val.startswith('"') and val.endswith('"'):
  91. if val == '"true"':
  92. return True
  93. elif val == '"false"':
  94. return False
  95. else:
  96. return val[1:-1]
  97. try:
  98. return int(val)
  99. except ValueError:
  100. try:
  101. return float(val)
  102. except ValueError:
  103. return val
  104. class ApplyWarpInputSpec(ElastixBaseInputSpec):
  105. transform_file = File(
  106. exists=True,
  107. mandatory=True,
  108. argstr='-tp %s',
  109. desc='transform-parameter file, only 1')
  110. moving_image = File(
  111. exists=True,
  112. argstr='-in %s',
  113. mandatory=True,
  114. desc='input image to deform')
  115. class ApplyWarpOutputSpec(TraitedSpec):
  116. warped_file = File(desc='input moving image warped to fixed image')
  117. class ApplyWarp(CommandLine):
  118. """
  119. Use ``transformix`` to apply a transform on an input image.
  120. The transform is specified in the transform-parameter file.
  121. Example
  122. -------
  123. >>> from nipype.interfaces.elastix import ApplyWarp
  124. >>> reg = ApplyWarp()
  125. >>> reg.inputs.moving_image = 'moving1.nii'
  126. >>> reg.inputs.transform_file = 'TransformParameters.0.txt'
  127. >>> reg.cmdline
  128. 'transformix -in moving1.nii -threads 1 -out ./ -tp TransformParameters.0.txt'
  129. """
  130. _cmd = 'transformix'
  131. input_spec = ApplyWarpInputSpec
  132. output_spec = ApplyWarpOutputSpec
  133. def _list_outputs(self):
  134. outputs = self._outputs().get()
  135. out_dir = op.abspath(self.inputs.output_path)
  136. outputs['warped_file'] = op.join(out_dir, 'result.nii.gz')
  137. return outputs
  138. class AnalyzeWarpInputSpec(ApplyWarpInputSpec):
  139. points = traits.Enum(
  140. 'all',
  141. usedefault=True,
  142. position=0,
  143. argstr='-def %s',
  144. desc='transform all points from the input-image, which effectively'
  145. ' generates a deformation field.')
  146. jac = traits.Enum(
  147. 'all',
  148. usedefault=True,
  149. argstr='-jac %s',
  150. desc='generate an image with the determinant of the spatial Jacobian')
  151. jacmat = traits.Enum(
  152. 'all',
  153. usedefault=True,
  154. argstr='-jacmat %s',
  155. desc='generate an image with the spatial Jacobian matrix at each voxel')
  156. moving_image = File(
  157. exists=True,
  158. argstr='-in %s',
  159. desc='input image to deform (not used)')
  160. class AnalyzeWarpOutputSpec(TraitedSpec):
  161. disp_field = File(desc='displacements field')
  162. jacdet_map = File(desc='det(Jacobian) map')
  163. jacmat_map = File(desc='Jacobian matrix map')
  164. class AnalyzeWarp(ApplyWarp):
  165. """
  166. Use transformix to get details from the input transform (generate
  167. the corresponding deformation field, generate the determinant of the
  168. Jacobian map or the Jacobian map itself)
  169. Example
  170. -------
  171. >>> from nipype.interfaces.elastix import AnalyzeWarp
  172. >>> reg = AnalyzeWarp()
  173. >>> reg.inputs.transform_file = 'TransformParameters.0.txt'
  174. >>> reg.cmdline
  175. 'transformix -def all -jac all -jacmat all -threads 1 -out ./ -tp TransformParameters.0.txt'
  176. """
  177. input_spec = AnalyzeWarpInputSpec
  178. output_spec = AnalyzeWarpOutputSpec
  179. def _list_outputs(self):
  180. outputs = self._outputs().get()
  181. out_dir = op.abspath(self.inputs.output_path)
  182. outputs['disp_field'] = op.join(out_dir, 'deformationField.nii.gz')
  183. outputs['jacdet_map'] = op.join(out_dir, 'spatialJacobian.nii.gz')
  184. outputs['jacmat_map'] = op.join(out_dir, 'fullSpatialJacobian.nii.gz')
  185. return outputs
  186. class PointsWarpInputSpec(ElastixBaseInputSpec):
  187. points_file = File(
  188. exists=True,
  189. argstr='-def %s',
  190. mandatory=True,
  191. desc='input points (accepts .vtk triangular meshes).')
  192. transform_file = File(
  193. exists=True,
  194. mandatory=True,
  195. argstr='-tp %s',
  196. desc='transform-parameter file, only 1')
  197. class PointsWarpOutputSpec(TraitedSpec):
  198. warped_file = File(desc='input points displaced in fixed image domain')
  199. class PointsWarp(CommandLine):
  200. """Use ``transformix`` to apply a transform on an input point set.
  201. The transform is specified in the transform-parameter file.
  202. Example
  203. -------
  204. >>> from nipype.interfaces.elastix import PointsWarp
  205. >>> reg = PointsWarp()
  206. >>> reg.inputs.points_file = 'surf1.vtk'
  207. >>> reg.inputs.transform_file = 'TransformParameters.0.txt'
  208. >>> reg.cmdline
  209. 'transformix -threads 1 -out ./ -def surf1.vtk -tp TransformParameters.0.txt'
  210. """
  211. _cmd = 'transformix'
  212. input_spec = PointsWarpInputSpec
  213. output_spec = PointsWarpOutputSpec
  214. def _list_outputs(self):
  215. outputs = self._outputs().get()
  216. out_dir = op.abspath(self.inputs.output_path)
  217. fname, ext = op.splitext(op.basename(self.inputs.points_file))
  218. outputs['warped_file'] = op.join(out_dir, 'outputpoints%s' % ext)
  219. return outputs