SimpleITK  1.0.1
ImageRegistrationMethod3/ImageRegistrationMethod3.py
1 #!/usr/bin/env python
2 #=========================================================================
3 #
4 # Copyright Insight Software Consortium
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0.txt
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 #=========================================================================
19 
20 from __future__ import print_function
21 from functools import reduce
22 
23 
24 import SimpleITK as sitk
25 import sys
26 import os
27 
28 
29 def command_iteration(method) :
30  if (method.GetOptimizerIteration()==0):
31  print("Estimated Scales: ", method.GetOptimizerScales())
32  print("{0:3} = {1:7.5f} : {2}".format(method.GetOptimizerIteration(),
33  method.GetMetricValue(),
34  method.GetOptimizerPosition()))
35 
36 
37 
38 if len ( sys.argv ) < 4:
39  print( "Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile>".format(sys.argv[0]))
40  sys.exit ( 1 )
41 
42 pixelType = sitk.sitkFloat32
43 
44 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
45 
46 
47 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
48 
50 
51 R.SetMetricAsCorrelation()
52 
53 R.SetOptimizerAsRegularStepGradientDescent(learningRate=2.0,
54  minStep=1e-4,
55  numberOfIterations=500,
56  gradientMagnitudeTolerance=1e-8 )
57 R.SetOptimizerScalesFromIndexShift()
58 
60 R.SetInitialTransform(tx)
61 
62 R.SetInterpolator(sitk.sitkLinear)
63 
64 R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
65 
66 outTx = R.Execute(fixed, moving)
67 
68 print("-------")
69 print(outTx)
70 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
71 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
72 print(" Metric value: {0}".format(R.GetMetricValue()))
73 
74 
75 sitk.WriteTransform(outTx, sys.argv[3])
76 
77 if ( not "SITK_NOSHOW" in os.environ ):
78 
79  resampler = sitk.ResampleImageFilter()
80  resampler.SetReferenceImage(fixed);
81  resampler.SetInterpolator(sitk.sitkLinear)
82  resampler.SetDefaultPixelValue(1)
83  resampler.SetTransform(outTx)
84 
85  out = resampler.Execute(moving)
86 
87  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
88  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
89  cimg = sitk.Compose(simg1, simg2, simg1/2.+simg2/2.)
90  sitk.Show( cimg, "ImageRegistration2 Composition" )