-
-
Notifications
You must be signed in to change notification settings - Fork 381
/
itkantsRegistrationHelper.hxx
4283 lines (3790 loc) · 206 KB
/
itkantsRegistrationHelper.hxx
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef __itkantsRegistrationHelper_hxx
#define __itkantsRegistrationHelper_hxx
#include <vnl/vnl_matrix.h>
#include <vnl/vnl_copy.h>
namespace ants
{
/**
* GetShrinkImageOutputInformation provides a consistent way to compute the
* outputImage space for each level of a registration in a consistent way.
* By always using the same reference image, we can ensure that the same
* shrink results always are produced.
*/
template <typename TComputeType, unsigned VImageDimension>
typename itk::ImageBase<VImageDimension>::Pointer
RegistrationHelper<TComputeType, VImageDimension>::GetShrinkImageOutputInformation(
const itk::ImageBase<VImageDimension> * inputImageInformation,
const typename RegistrationHelper<TComputeType, VImageDimension>::ShrinkFactorsPerDimensionContainerType &
shrinkFactorsPerDimensionForCurrentLevel) const
{
typedef itk::Image<unsigned char, VImageDimension> DummyImageType;
typename DummyImageType::Pointer dummyImage = AllocImage<DummyImageType>(inputImageInformation, 0);
// We use the shrink image filter to calculate the fixed parameters of the virtual
// domain at each level. To speed up calculation and avoid unnecessary memory
// usage, we could calculate these fixed parameters directly.
typedef itk::ShrinkImageFilter<DummyImageType, DummyImageType> ShrinkFilterType;
typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
shrinkFilter->SetShrinkFactors(shrinkFactorsPerDimensionForCurrentLevel);
shrinkFilter->SetInput(dummyImage);
shrinkFilter
->GenerateOutputInformation(); // Don't need to allocate space or run the filter, just create output information
typename itk::ImageBase<VImageDimension>::Pointer returnImageBase = shrinkFilter->GetOutput();
return returnImageBase;
}
template <typename TComputeType, unsigned VImageDimension>
RegistrationHelper<TComputeType, VImageDimension>::RegistrationHelper()
: m_CompositeTransform(nullptr)
, m_RegistrationState(nullptr)
, m_FixedInitialTransform(nullptr)
, m_NumberOfStages(0)
, m_Metrics()
, m_TransformMethods()
, m_Iterations()
, m_SmoothingSigmas()
, m_RestrictDeformationOptimizerWeights()
, m_ShrinkFactors()
, m_UseHistogramMatching(true)
, m_WinsorizeImageIntensities(false)
, m_DoEstimateLearningRateAtEachIteration(true)
, m_LowerQuantile(0.0)
, m_UpperQuantile(1.0)
, m_LogStream(&std::cout)
, m_PrintSimilarityMeasureInterval(0)
, m_WriteIntervalVolumes(0)
, m_InitializeTransformsPerStage(false)
, m_AllPreviousTransformsAreLinear(true)
{
typedef itk::LinearInterpolateImageFunction<ImageType, RealType> LinearInterpolatorType;
typename LinearInterpolatorType::Pointer linearInterpolator = LinearInterpolatorType::New();
this->m_Interpolator = linearInterpolator;
}
template <typename TComputeType, unsigned VImageDimension>
RegistrationHelper<TComputeType, VImageDimension>::~RegistrationHelper() = default;
template <typename ImageType>
typename ImageType::Pointer
PreprocessImage(typename ImageType::ConstPointer inputImage,
typename ImageType::PixelType lowerScaleValue,
typename ImageType::PixelType upperScaleValue,
float winsorizeLowerQuantile,
float winsorizeUpperQuantile,
typename ImageType::ConstPointer histogramMatchSourceImage = nullptr)
{
typedef itk::Statistics::ImageToHistogramFilter<ImageType> HistogramFilterType;
typedef typename HistogramFilterType::InputBooleanObjectType InputBooleanObjectType;
typedef typename HistogramFilterType::HistogramSizeType HistogramSizeType;
HistogramSizeType histogramSize(1);
histogramSize[0] = 256;
typename InputBooleanObjectType::Pointer autoMinMaxInputObject = InputBooleanObjectType::New();
autoMinMaxInputObject->Set(true);
typename HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New();
histogramFilter->SetInput(inputImage);
histogramFilter->SetAutoMinimumMaximumInput(autoMinMaxInputObject);
histogramFilter->SetHistogramSize(histogramSize);
histogramFilter->SetMarginalScale(10.0);
histogramFilter->Update();
float lowerValue = histogramFilter->GetOutput()->Quantile(0, winsorizeLowerQuantile);
float upperValue = histogramFilter->GetOutput()->Quantile(0, winsorizeUpperQuantile);
typedef itk::IntensityWindowingImageFilter<ImageType, ImageType> IntensityWindowingImageFilterType;
typename IntensityWindowingImageFilterType::Pointer windowingFilter = IntensityWindowingImageFilterType::New();
windowingFilter->SetInput(inputImage);
windowingFilter->SetWindowMinimum(lowerValue);
windowingFilter->SetWindowMaximum(upperValue);
windowingFilter->SetOutputMinimum(lowerScaleValue);
windowingFilter->SetOutputMaximum(upperScaleValue);
windowingFilter->Update();
typename ImageType::Pointer outputImage = nullptr;
if (histogramMatchSourceImage)
{
typedef itk::HistogramMatchingImageFilter<ImageType, ImageType> HistogramMatchingFilterType;
typename HistogramMatchingFilterType::Pointer matchingFilter = HistogramMatchingFilterType::New();
matchingFilter->SetSourceImage(windowingFilter->GetOutput());
matchingFilter->SetReferenceImage(histogramMatchSourceImage);
matchingFilter->SetNumberOfHistogramLevels(256);
matchingFilter->SetNumberOfMatchPoints(12);
matchingFilter->ThresholdAtMeanIntensityOn();
matchingFilter->Update();
outputImage = matchingFilter->GetOutput();
outputImage->Update();
outputImage->DisconnectPipeline();
}
else
{
outputImage = windowingFilter->GetOutput();
outputImage->Update();
outputImage->DisconnectPipeline();
}
return outputImage;
}
template <typename TComputeType, unsigned VImageDimension>
typename RegistrationHelper<TComputeType, VImageDimension>::MetricEnumeration
RegistrationHelper<TComputeType, VImageDimension>::StringToMetricType(const std::string & str) const
{
if (str == "cc")
{
return CC;
}
else if (str == "mi2")
{
return MI;
}
else if (str == "mattes" || str == "mi")
{
return Mattes;
}
else if (str == "meansquares" || str == "msq" || str == "ssd")
{
return MeanSquares;
}
else if (str == "demons")
{
return Demons;
}
else if (str == "gc")
{
return GC;
}
else if (str == "icp")
{
return ICP;
}
else if (str == "pse")
{
return PSE;
}
else if (str == "jhct")
{
return JHCT;
}
else if (str == "igdm")
{
return IGDM;
}
return IllegalMetric;
}
template <typename TComputeType, unsigned VImageDimension>
typename RegistrationHelper<TComputeType, VImageDimension>::XfrmMethod
RegistrationHelper<TComputeType, VImageDimension>::StringToXfrmMethod(const std::string & str) const
{
if (str == "rigid")
{
return Rigid;
}
else if (str == "affine")
{
return Affine;
}
if (str == "compositeaffine" || str == "compaff")
{
return CompositeAffine;
}
if (str == "similarity")
{
return Similarity;
}
if (str == "translation")
{
return Translation;
}
if (str == "bspline" || str == "ffd")
{
return BSpline;
}
if (str == "gaussiandisplacementfield" || str == "gdf")
{
return GaussianDisplacementField;
}
if (str == "bsplinedisplacementfield" || str == "dmffd")
{
return BSplineDisplacementField;
}
if (str == "timevaryingvelocityfield" || str == "tvf")
{
return TimeVaryingVelocityField;
}
if (str == "timevaryingbsplinevelocityfield" || str == "tvdmffd")
{
return TimeVaryingBSplineVelocityField;
}
if (str == "syn" || str == "symmetricnormalization")
{
return SyN;
}
if (str == "bsplinesyn")
{
return BSplineSyN;
}
if (str == "exp" || str == "exponential")
{
return Exponential;
}
if (str == "bsplineexponential")
{
return BSplineExponential;
}
return UnknownXfrm;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddMetric(MetricEnumeration metricType,
ImageType * fixedImage,
ImageType * movingImage,
LabeledPointSetType * fixedLabeledPointSet,
LabeledPointSetType * movingLabeledPointSet,
IntensityPointSetType * fixedIntensityPointSet,
IntensityPointSetType * movingIntensityPointSet,
unsigned int stageID,
RealType weighting,
SamplingStrategy samplingStrategy,
int numberOfBins,
unsigned int radius,
bool useGradientFilter,
bool useBoundaryPointsOnly,
RealType pointSetSigma,
unsigned int evaluationKNeighborhood,
RealType alpha,
bool useAnisotropicCovariances,
RealType samplingPercentage,
RealType intensityDistanceSigma,
RealType euclideanDistanceSigma)
{
Metric init(metricType,
fixedImage,
movingImage,
fixedLabeledPointSet,
movingLabeledPointSet,
fixedIntensityPointSet,
movingIntensityPointSet,
stageID,
weighting,
samplingStrategy,
numberOfBins,
radius,
useGradientFilter,
useBoundaryPointsOnly,
pointSetSigma,
evaluationKNeighborhood,
alpha,
useAnisotropicCovariances,
samplingPercentage,
intensityDistanceSigma,
euclideanDistanceSigma);
this->m_Metrics.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
typename RegistrationHelper<TComputeType, VImageDimension>::MetricListType
RegistrationHelper<TComputeType, VImageDimension>::GetMetricListPerStage(unsigned int stageID)
{
MetricListType stageMetricList;
typename MetricListType::const_iterator it;
for (it = this->m_Metrics.begin(); it != this->m_Metrics.end(); ++it)
{
if ((*it).m_StageID == stageID)
{
stageMetricList.push_back(*it);
}
}
return stageMetricList;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddRigidTransform(RealType GradientStep)
{
TransformMethod init;
init.m_XfrmMethod = Rigid;
init.m_GradientStep = GradientStep;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddAffineTransform(RealType GradientStep)
{
TransformMethod init;
init.m_XfrmMethod = Affine;
init.m_GradientStep = GradientStep;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddCompositeAffineTransform(RealType GradientStep)
{
TransformMethod init;
init.m_XfrmMethod = CompositeAffine;
init.m_GradientStep = GradientStep;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddSimilarityTransform(RealType GradientStep)
{
TransformMethod init;
init.m_XfrmMethod = Similarity;
init.m_GradientStep = GradientStep;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddTranslationTransform(RealType GradientStep)
{
TransformMethod init;
init.m_XfrmMethod = Translation;
init.m_GradientStep = GradientStep;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddBSplineTransform(RealType GradientStep,
std::vector<unsigned int> & MeshSizeAtBaseLevel)
{
TransformMethod init;
init.m_XfrmMethod = BSpline;
init.m_GradientStep = GradientStep;
init.m_MeshSizeAtBaseLevel = MeshSizeAtBaseLevel;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddGaussianDisplacementFieldTransform(
RealType GradientStep,
RealType UpdateFieldVarianceInVarianceSpace,
RealType TotalFieldVarianceInVarianceSpace)
{
TransformMethod init;
init.m_XfrmMethod = GaussianDisplacementField;
init.m_GradientStep = GradientStep;
init.m_UpdateFieldVarianceInVarianceSpace = UpdateFieldVarianceInVarianceSpace;
init.m_TotalFieldVarianceInVarianceSpace = TotalFieldVarianceInVarianceSpace;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddBSplineDisplacementFieldTransform(
RealType GradientStep,
std::vector<unsigned int> & UpdateFieldMeshSizeAtBaseLevel,
std::vector<unsigned int> & TotalFieldMeshSizeAtBaseLevel,
unsigned int SplineOrder)
{
TransformMethod init;
init.m_XfrmMethod = BSplineDisplacementField;
init.m_GradientStep = GradientStep;
init.m_UpdateFieldMeshSizeAtBaseLevel = UpdateFieldMeshSizeAtBaseLevel;
init.m_TotalFieldMeshSizeAtBaseLevel = TotalFieldMeshSizeAtBaseLevel;
init.m_SplineOrder = SplineOrder;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddTimeVaryingVelocityFieldTransform(
RealType GradientStep,
unsigned int NumberOfTimeIndices,
RealType UpdateFieldVarianceInVarianceSpace,
RealType UpdateFieldTimeSigma,
RealType TotalFieldVarianceInVarianceSpace,
RealType TotalFieldTimeSigma)
{
TransformMethod init;
init.m_XfrmMethod = TimeVaryingVelocityField;
init.m_GradientStep = GradientStep;
init.m_NumberOfTimeIndices = NumberOfTimeIndices;
init.m_UpdateFieldVarianceInVarianceSpace = UpdateFieldVarianceInVarianceSpace;
init.m_UpdateFieldTimeSigma = UpdateFieldTimeSigma;
init.m_TotalFieldVarianceInVarianceSpace = TotalFieldVarianceInVarianceSpace;
init.m_TotalFieldTimeSigma = TotalFieldTimeSigma;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddTimeVaryingBSplineVelocityFieldTransform(
RealType GradientStep,
std::vector<unsigned int> VelocityFieldMeshSize,
unsigned int NumberOfTimePointSamples,
unsigned int SplineOrder)
{
TransformMethod init;
init.m_XfrmMethod = TimeVaryingBSplineVelocityField;
init.m_GradientStep = GradientStep;
init.m_VelocityFieldMeshSize = VelocityFieldMeshSize;
init.m_NumberOfTimePointSamples = NumberOfTimePointSamples;
init.m_SplineOrder = SplineOrder;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddSyNTransform(RealType GradientStep,
RealType UpdateFieldVarianceInVarianceSpace,
RealType TotalFieldVarianceInVarianceSpace)
{
TransformMethod init;
init.m_XfrmMethod = SyN;
init.m_GradientStep = GradientStep;
init.m_UpdateFieldVarianceInVarianceSpace = UpdateFieldVarianceInVarianceSpace;
init.m_TotalFieldVarianceInVarianceSpace = TotalFieldVarianceInVarianceSpace;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddBSplineSyNTransform(
RealType GradientStep,
std::vector<unsigned int> & UpdateFieldMeshSizeAtBaseLevel,
std::vector<unsigned int> & TotalFieldMeshSizeAtBaseLevel,
unsigned int SplineOrder)
{
TransformMethod init;
init.m_XfrmMethod = BSplineSyN;
init.m_GradientStep = GradientStep;
init.m_UpdateFieldMeshSizeAtBaseLevel = UpdateFieldMeshSizeAtBaseLevel;
init.m_TotalFieldMeshSizeAtBaseLevel = TotalFieldMeshSizeAtBaseLevel;
init.m_SplineOrder = SplineOrder;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddExponentialTransform(
RealType GradientStep,
RealType UpdateFieldVarianceInVarianceSpace,
RealType VelocityFieldVarianceInVarianceSpace,
unsigned int NumberOfIntegrationSteps)
{
TransformMethod init;
init.m_XfrmMethod = Exponential;
init.m_GradientStep = GradientStep;
init.m_UpdateFieldVarianceInVarianceSpace = UpdateFieldVarianceInVarianceSpace;
init.m_VelocityFieldVarianceInVarianceSpace = VelocityFieldVarianceInVarianceSpace;
init.m_NumberOfTimeIndices = NumberOfIntegrationSteps;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddBSplineExponentialTransform(
RealType GradientStep,
std::vector<unsigned int> & UpdateFieldMeshSizeAtBaseLevel,
std::vector<unsigned int> & VelocityFieldMeshSizeAtBaseLevel,
unsigned int NumberOfIntegrationSteps,
unsigned int SplineOrder)
{
TransformMethod init;
init.m_XfrmMethod = BSplineExponential;
init.m_GradientStep = GradientStep;
init.m_UpdateFieldMeshSizeAtBaseLevel = UpdateFieldMeshSizeAtBaseLevel;
init.m_VelocityFieldMeshSizeAtBaseLevel = VelocityFieldMeshSizeAtBaseLevel;
init.m_SplineOrder = SplineOrder;
init.m_NumberOfTimeIndices = NumberOfIntegrationSteps;
this->m_TransformMethods.push_back(init);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetIterations(
const std::vector<std::vector<unsigned int>> & Iterations)
{
this->m_Iterations = Iterations;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetConvergenceThresholds(const std::vector<RealType> & thresholds)
{
this->m_ConvergenceThresholds = thresholds;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetConvergenceWindowSizes(
const std::vector<unsigned int> & windowSizes)
{
this->m_ConvergenceWindowSizes = windowSizes;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetSmoothingSigmas(
const std::vector<std::vector<float>> & SmoothingSigmas)
{
this->m_SmoothingSigmas = SmoothingSigmas;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetRestrictDeformationOptimizerWeights(
const std::vector<std::vector<RealType>> & restrictDeformationWeights)
{
this->m_RestrictDeformationOptimizerWeights = restrictDeformationWeights;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetSmoothingSigmasAreInPhysicalUnits(
const std::vector<bool> & SmoothingSigmasAreInPhysicalUnits)
{
this->m_SmoothingSigmasAreInPhysicalUnits = SmoothingSigmasAreInPhysicalUnits;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetShrinkFactors(
const std::vector<std::vector<unsigned int>> & ShrinkFactors)
{
this->m_ShrinkFactors = ShrinkFactors;
}
template <typename TComputeType, unsigned VImageDimension>
typename RegistrationHelper<TComputeType, VImageDimension>::ShrinkFactorsPerDimensionContainerType
RegistrationHelper<TComputeType, VImageDimension>::CalculateShrinkFactorsPerDimension(unsigned int factor,
ImageSpacingType spacing)
{
using SpacingValueType = typename ImageSpacingType::ComponentType;
SpacingValueType minSpacing = spacing[0];
unsigned int minIndex = 0;
for (unsigned int n = 1; n < VImageDimension; n++)
{
if (minSpacing > static_cast<SpacingValueType>(spacing[n]))
{
minSpacing = spacing[n];
minIndex = n;
}
}
ShrinkFactorsPerDimensionContainerType shrinkFactorsPerDimension;
shrinkFactorsPerDimension.Fill(0);
shrinkFactorsPerDimension[minIndex] = factor;
ImageSpacingType newSpacing;
newSpacing[minIndex] = spacing[minIndex] * factor;
for (unsigned int n = 0; n < VImageDimension; n++)
{
if (shrinkFactorsPerDimension[n] == 0)
{
SpacingValueType newMinSpacing =
static_cast<SpacingValueType>(spacing[n]) * static_cast<SpacingValueType>(factor);
RealType minDifferenceFromMinSpacing = static_cast<RealType>(std::fabs(newMinSpacing - newSpacing[minIndex]));
unsigned int minFactor = factor;
for (unsigned int f = factor - 1; f > 0; f--)
{
newMinSpacing = static_cast<SpacingValueType>(spacing[n]) * static_cast<SpacingValueType>(f);
// We use <= such that the smaller factor is preferred if distances are the same
if (static_cast<RealType>(std::fabs(newMinSpacing - newSpacing[minIndex])) <= minDifferenceFromMinSpacing)
{
minDifferenceFromMinSpacing = itk::Math::abs(newMinSpacing - newSpacing[minIndex]);
minFactor = f;
}
}
shrinkFactorsPerDimension[n] = minFactor;
}
}
return shrinkFactorsPerDimension;
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::SetWinsorizeImageIntensities(bool Winsorize,
float LowerQuantile,
float UpperQuantile)
{
this->m_WinsorizeImageIntensities = Winsorize;
this->m_LowerQuantile = LowerQuantile;
this->m_UpperQuantile = UpperQuantile;
}
template <typename TComputeType, unsigned VImageDimension>
int
RegistrationHelper<TComputeType, VImageDimension>::ValidateParameters()
{
if (this->m_NumberOfStages == 0)
{
this->Logger() << "No transformations are specified." << std::endl;
return EXIT_FAILURE;
}
if (this->m_Iterations.size() != this->m_NumberOfStages)
{
this->Logger() << "The number of iteration sets specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
if (this->m_ShrinkFactors.size() != this->m_NumberOfStages)
{
this->Logger() << "The number of shrinkFactors specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
if (this->m_SmoothingSigmas.size() != this->m_NumberOfStages)
{
this->Logger() << "The number of smoothing sigma sets specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
if (this->m_SmoothingSigmasAreInPhysicalUnits.size() != this->m_NumberOfStages)
{
this->Logger() << "The number of smoothing sigma in physical units bool values does not match the number of stages."
<< std::endl;
return EXIT_FAILURE;
}
for (unsigned int i = 0; i < this->m_Metrics.size(); i++)
{
if (!this->IsPointSetMetric(this->m_Metrics[i].m_MetricType))
{
if (this->m_Metrics[i].m_FixedImage.IsNull() || this->m_Metrics[i].m_MovingImage.IsNull())
{
this->Logger() << "The image metric has no fixed and/or moving image." << std::endl;
return EXIT_FAILURE;
}
}
}
// Check the number of masks. We are going to allow the user 2 options w.r.t.
// mask specification:
// 1. Either the user specifies a single mask to be used for all stages or
// 2. the user specifies a mask for each stage.
// Note that we handle the fixed and moving masks separately to enforce this constraint.
if (this->m_FixedImageMasks.size() > 1 && this->m_FixedImageMasks.size() != this->m_NumberOfStages)
{
this->Logger() << "The number of fixed masks must be equal to 1 (use the mask for all "
<< "stages) or the number of fixed masks must be equal to the number of stages." << std::endl;
return EXIT_FAILURE;
}
if (this->m_MovingImageMasks.size() > 1 && this->m_MovingImageMasks.size() != this->m_NumberOfStages)
{
this->Logger() << "The number of moving masks must be equal to 1 (i.e., use the mask for all "
<< "stages) or the number of moving masks must be equal to the number of stages." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
template <typename TComputeType, unsigned VImageDimension>
typename RegistrationHelper<TComputeType, VImageDimension>::ImageType::Pointer
RegistrationHelper<TComputeType, VImageDimension>::GetWarpedImage() const
{
typename ImageType::Pointer fixedImage = this->m_Metrics[0].m_FixedImage;
typename ImageType::Pointer movingImage = this->m_Metrics[0].m_MovingImage;
typedef itk::ResampleImageFilter<ImageType, ImageType, RealType> ResampleFilterType;
typename ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform(this->m_CompositeTransform);
resampler->SetInput(movingImage);
resampler->SetOutputParametersFromImage(fixedImage);
resampler->SetInterpolator(this->m_Interpolator);
resampler->SetDefaultPixelValue(0);
resampler->Update();
typename ImageType::Pointer WarpedImage;
WarpedImage = resampler->GetOutput();
return WarpedImage.GetPointer();
}
template <typename TComputeType, unsigned VImageDimension>
typename RegistrationHelper<TComputeType, VImageDimension>::ImageType::Pointer
RegistrationHelper<TComputeType, VImageDimension>::GetInverseWarpedImage() const
{
typename ImageType::Pointer fixedImage = this->m_Metrics[0].m_FixedImage;
typename ImageType::Pointer movingImage = this->m_Metrics[0].m_MovingImage;
if (this->m_CompositeTransform->GetInverseTransform().IsNull())
{
return nullptr;
}
typedef itk::ResampleImageFilter<ImageType, ImageType, RealType> ResampleFilterType;
typename ResampleFilterType::Pointer inverseResampler = ResampleFilterType::New();
inverseResampler->SetTransform(this->m_CompositeTransform->GetInverseTransform());
inverseResampler->SetInput(fixedImage);
inverseResampler->SetOutputParametersFromImage(movingImage);
inverseResampler->SetInterpolator(this->m_Interpolator);
inverseResampler->SetDefaultPixelValue(0);
inverseResampler->Update();
typename ImageType::Pointer InverseWarpedImage;
InverseWarpedImage = inverseResampler->GetOutput();
return InverseWarpedImage.GetPointer();
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddFixedImageMask(typename MaskImageType::Pointer & fixedImageMask)
{
typename ImageMaskSpatialObjectType::Pointer so = nullptr;
if (fixedImageMask.IsNotNull())
{
so = ImageMaskSpatialObjectType::New();
so->SetImage(fixedImageMask.GetPointer());
}
this->AddFixedImageMask(so);
}
template <typename TComputeType, unsigned VImageDimension>
void
RegistrationHelper<TComputeType, VImageDimension>::AddMovingImageMask(typename MaskImageType::Pointer & movingImageMask)
{
typename ImageMaskSpatialObjectType::Pointer so = nullptr;
if (movingImageMask.IsNotNull())
{
so = ImageMaskSpatialObjectType::New();
so->SetImage(movingImageMask.GetPointer());
}
this->AddMovingImageMask(so);
}
template <typename TComputeType, unsigned VImageDimension>
int
RegistrationHelper<TComputeType, VImageDimension>::DoRegistration()
{
itk::TimeProbe totalTimer;
totalTimer.Start();
this->m_NumberOfStages = this->m_TransformMethods.size();
if (this->ValidateParameters() != EXIT_SUCCESS)
{
return EXIT_FAILURE;
}
this->PrintState();
this->Logger() << "Registration using " << this->m_NumberOfStages << " total stages." << std::endl;
// NOTE: the -1 is to ignore the initial identity identity transform
if (this->m_CompositeTransform.IsNull())
{
this->m_CompositeTransform = CompositeTransformType::New();
}
if (this->m_FixedInitialTransform.IsNull())
{
this->m_FixedInitialTransform = CompositeTransformType::New();
}
// ########################################################################################
// ########################################################################################
// ##The main loop for exstimating the total composite transform
// ########################################################################################
// ########################################################################################
for (unsigned int currentStageNumber = 0; currentStageNumber < this->m_NumberOfStages; currentStageNumber++)
{
itk::TimeProbe timer;
timer.Start();
this->Logger() << std::endl << "Stage " << currentStageNumber << std::endl;
std::stringstream currentStageString;
currentStageString << currentStageNumber;
// Get the number of iterations and use that information to specify the number of levels
const std::vector<unsigned int> & currentStageIterations = this->m_Iterations[currentStageNumber];
this->Logger() << " iterations = ";
for (unsigned int m = 0; m < currentStageIterations.size(); m++)
{
this->Logger() << currentStageIterations[m];
if (m < currentStageIterations.size() - 1)
{
this->Logger() << 'x';
}
}
this->Logger() << std::endl;
const RealType convergenceThreshold = this->m_ConvergenceThresholds[currentStageNumber];
this->Logger() << " convergence threshold = " << convergenceThreshold << std::endl;
const unsigned int convergenceWindowSize = this->m_ConvergenceWindowSizes[currentStageNumber];
this->Logger() << " convergence window size = " << convergenceWindowSize << std::endl;
const unsigned int numberOfLevels = currentStageIterations.size();
this->Logger() << " number of levels = " << numberOfLevels << std::endl;
unsigned int fixedMaskIndex = itk::NumericTraits<unsigned int>::max();
unsigned int movingMaskIndex = itk::NumericTraits<unsigned int>::max();
bool useFixedImageMaskForThisStage = false;
bool useMovingImageMaskForThisStage = false;
// We already checked that number of masks = 1 or = number of stages
if (this->m_FixedImageMasks.size() > 0)
{
useFixedImageMaskForThisStage = true;
if (this->m_FixedImageMasks.size() == 1)
{
fixedMaskIndex = 0;
}
else
{
fixedMaskIndex = currentStageNumber;
}
}
if (this->m_MovingImageMasks.size() > 0)
{
useMovingImageMaskForThisStage = true;
if (this->m_MovingImageMasks.size() == 1)
{
movingMaskIndex = 0;
}
else
{
movingMaskIndex = currentStageNumber;
}
}
// Get the number of metrics at the current stage. If more than one metric
// then we need to use the MultiMetricType. Due to the way the metrics are
// pulled off the command line stack, we need to iterate from the top down.
MetricListType stageMetricList = this->GetMetricListPerStage(this->m_NumberOfStages - currentStageNumber - 1);
typename ObjectMetricType::Pointer singleMetric;
typename MultiMetricType::Pointer multiMetric;
typename MultiMetricType::WeightsArrayType metricWeights(stageMetricList.size());
metricWeights.Fill(1.0);
bool useMultiMetric = false;
if (stageMetricList.size() > 1)
{
useMultiMetric = true;
multiMetric = MultiMetricType::New();
}
std::vector<typename ImageType::Pointer> preprocessedFixedImagesPerStage;
std::vector<typename ImageType::Pointer> preprocessedMovingImagesPerStage;
typename ImageBaseType::Pointer virtualDomainImage = nullptr;
for (unsigned int currentMetricNumber = 0; currentMetricNumber < stageMetricList.size(); currentMetricNumber++)
{
MetricEnumeration currentMetricType = stageMetricList[currentMetricNumber].m_MetricType;
typename ImageMetricType::Pointer imageMetric = nullptr;
typedef itk::LabeledPointSetToPointSetMetricv4<LabeledPointSetType, LabeledPointSetType, RealType>
LabeledPointSetMetricType;
typename LabeledPointSetMetricType::Pointer labeledPointSetMetric = LabeledPointSetMetricType::New();
typedef itk::
MeanSquaresPointSetToPointSetIntensityMetricv4<IntensityPointSetType, IntensityPointSetType, RealType>
IntensityPointSetMetricType;
typename IntensityPointSetMetricType::Pointer intensityPointSetMetric = nullptr;
switch (currentMetricType)
{
case CC:
{
const unsigned int radiusOption = stageMetricList[currentMetricNumber].m_Radius;
this->Logger() << " using the CC metric (radius = " << radiusOption
<< ", weight = " << stageMetricList[currentMetricNumber].m_Weighting
<< ", use gradient filter = " << stageMetricList[currentMetricNumber].m_UseGradientFilter
<< ")" << std::endl;
typedef itk::ANTSNeighborhoodCorrelationImageToImageMetricv4<ImageType, ImageType, ImageType, TComputeType>
CorrelationMetricType;
typename CorrelationMetricType::Pointer correlationMetric = CorrelationMetricType::New();
{
typename CorrelationMetricType::RadiusType radius;
radius.Fill(radiusOption);
correlationMetric->SetRadius(radius);
}
imageMetric = correlationMetric;
}
break;
case Mattes:
{
const unsigned int binOption = stageMetricList[currentMetricNumber].m_NumberOfBins;
this->Logger() << " using the Mattes MI metric (number of bins = " << binOption
<< ", weight = " << stageMetricList[currentMetricNumber].m_Weighting
<< ", use gradient filter = " << stageMetricList[currentMetricNumber].m_UseGradientFilter
<< ")" << std::endl;
typedef itk::MattesMutualInformationImageToImageMetricv4<ImageType, ImageType, ImageType, TComputeType>
MutualInformationMetricType;
typename MutualInformationMetricType::Pointer mutualInformationMetric = MutualInformationMetricType::New();
// mutualInformationMetric = mutualInformationMetric;
mutualInformationMetric->SetNumberOfHistogramBins(binOption);
mutualInformationMetric->SetUseSampledPointSet(false);
imageMetric = mutualInformationMetric;
}
break;
case MI:
{
const unsigned int binOption = stageMetricList[currentMetricNumber].m_NumberOfBins;
this->Logger() << " using the joint histogram MI metric (number of bins = " << binOption
<< ", weight = " << stageMetricList[currentMetricNumber].m_Weighting
<< ", use gradient filter = " << stageMetricList[currentMetricNumber].m_UseGradientFilter
<< ")" << std::endl;
typedef itk::
JointHistogramMutualInformationImageToImageMetricv4<ImageType, ImageType, ImageType, TComputeType>
MutualInformationMetricType;
typename MutualInformationMetricType::Pointer mutualInformationMetric = MutualInformationMetricType::New();
// mutualInformationMetric = mutualInformationMetric;
mutualInformationMetric->SetNumberOfHistogramBins(binOption);
mutualInformationMetric->SetUseSampledPointSet(false);
mutualInformationMetric->SetVarianceForJointPDFSmoothing(1.0);
imageMetric = mutualInformationMetric;
}
break;
case MeanSquares:
{
this->Logger() << " using the MeanSquares metric "
<< "( weight = " << stageMetricList[currentMetricNumber].m_Weighting
<< ", use gradient filter = " << stageMetricList[currentMetricNumber].m_UseGradientFilter
<< ")" << std::endl;
typedef itk::MeanSquaresImageToImageMetricv4<ImageType, ImageType, ImageType, TComputeType>
MeanSquaresMetricType;
typename MeanSquaresMetricType::Pointer meanSquaresMetric = MeanSquaresMetricType::New();
// meanSquaresMetric = meanSquaresMetric;
imageMetric = meanSquaresMetric;
}
break;
case Demons:
{
this->Logger() << " using the Demons metric "
<< "( weight = " << stageMetricList[currentMetricNumber].m_Weighting
<< ", use gradient filter = " << stageMetricList[currentMetricNumber].m_UseGradientFilter
<< ")" << std::endl;
typedef itk::DemonsImageToImageMetricv4<ImageType, ImageType, ImageType, TComputeType> DemonsMetricType;
typename DemonsMetricType::Pointer demonsMetric = DemonsMetricType::New();