SimpleITK  1.2.4
ImageRegistrationMethod4/ImageRegistrationMethod4.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 
22 import SimpleITK as sitk
23 import sys
24 import os
25 
26 
27 if len ( sys.argv ) < 4:
28  print( "Usage: {0} <fixedImageFilter> <movingImageFile> <outputTransformFile> <numberOfBins> <samplingPercentage>".format(sys.argv[0]))
29  sys.exit ( 1 )
30 
31 def command_iteration(method) :
32  print("{0:3} = {1:10.5f} : {2}".format(method.GetOptimizerIteration(),
33  method.GetMetricValue(),
34  method.GetOptimizerPosition()))
35 
36 
37 fixed = sitk.ReadImage(sys.argv[1], sitk.sitkFloat32)
38 moving = sitk.ReadImage(sys.argv[2], sitk.sitkFloat32)
39 
40 
41 numberOfBins = 24
42 samplingPercentage = 0.10
43 
44 if len ( sys.argv ) > 4:
45  numberOfBins = int(sys.argv[4])
46 if len ( sys.argv ) > 5:
47  samplingPercentage = float(sys.argv[5])
48 
50 R.SetMetricAsMattesMutualInformation(numberOfBins)
51 R.SetMetricSamplingPercentage(samplingPercentage,sitk.sitkWallClock)
52 R.SetMetricSamplingStrategy(R.RANDOM)
53 R.SetOptimizerAsRegularStepGradientDescent(1.0,.001,200)
54 R.SetInitialTransform(sitk.TranslationTransform(fixed.GetDimension()))
55 R.SetInterpolator(sitk.sitkLinear)
56 
57 R.AddCommand( sitk.sitkIterationEvent, lambda: command_iteration(R) )
58 
59 outTx = R.Execute(fixed, moving)
60 
61 
62 print("-------")
63 print(outTx)
64 print("Optimizer stop condition: {0}".format(R.GetOptimizerStopConditionDescription()))
65 print(" Iteration: {0}".format(R.GetOptimizerIteration()))
66 print(" Metric value: {0}".format(R.GetMetricValue()))
67 
68 sitk.WriteTransform(outTx, sys.argv[3])
69 
70 
71 if ( not "SITK_NOSHOW" in os.environ ):
72  resampler = sitk.ResampleImageFilter()
73  resampler.SetReferenceImage(fixed);
74  resampler.SetInterpolator(sitk.sitkLinear)
75  resampler.SetDefaultPixelValue(100)
76  resampler.SetTransform(outTx)
77 
78  out = resampler.Execute(moving)
79  simg1 = sitk.Cast(sitk.RescaleIntensity(fixed), sitk.sitkUInt8)
80  simg2 = sitk.Cast(sitk.RescaleIntensity(out), sitk.sitkUInt8)
81  cimg = sitk.Compose(simg1, simg2, simg1//2.+simg2//2.)
82  sitk.Show( cimg, "ImageRegistration4 Composition" )