SimpleITK  1.0.1
ImageRegistrationMethod2/ImageRegistrationMethod2.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  print("{0:3} = {1:7.5f} : {2}".format(method.GetOptimizerIteration(),
31  method.GetMetricValue(),
32  method.GetOptimizerPosition()))
33 
34 
35 
36 if len ( sys.argv ) < 4:
37  print( "Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile>".format(sys.argv[0]))
38  sys.exit ( 1 )
39 
40 pixelType = sitk.sitkFloat32
41 
42 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
43 fixed = sitk.Normalize(fixed)
44 fixed = sitk.DiscreteGaussian(fixed, 2.0)
45 
46 
47 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
48 moving = sitk.Normalize(moving)
49 moving = sitk.DiscreteGaussian(moving, 2.0)
50 
51 
53 
54 R.SetMetricAsJointHistogramMutualInformation()
55 
56 R.SetOptimizerAsGradientDescentLineSearch(learningRate=1.0,
57  numberOfIterations=200,
58  convergenceMinimumValue=1e-5,
59  convergenceWindowSize=5)
60 
61 R.SetInitialTransform(sitk.TranslationTransform(fixed.GetDimension()))
62 
63 R.SetInterpolator(sitk.sitkLinear)
64 
65 R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
66 
67 outTx = R.Execute(fixed, moving)
68 
69 print("-------")
70 print(outTx)
71 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
72 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
73 print(" Metric value: {0}".format(R.GetMetricValue()))
74 
75 
76 sitk.WriteTransform(outTx, sys.argv[3])
77 
78 if ( not "SITK_NOSHOW" in os.environ ):
79 
80  resampler = sitk.ResampleImageFilter()
81  resampler.SetReferenceImage(fixed);
82  resampler.SetInterpolator(sitk.sitkLinear)
83  resampler.SetDefaultPixelValue(1)
84  resampler.SetTransform(outTx)
85 
86  out = resampler.Execute(moving)
87 
88  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
89  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
90  cimg = sitk.Compose(simg1, simg2, simg1/2.+simg2/2.)
91  sitk.Show( cimg, "ImageRegistration2 Composition" )