forked from BRAINSia/BRAINSTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBRAINSFitHelperTemplate.hxx
1791 lines (1665 loc) · 79 KB
/
BRAINSFitHelperTemplate.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
/*=========================================================================
*
* Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering
* The University of Iowa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkIO.h"
#include "BRAINSCommonLib.h"
#ifdef USE_DebugImageViewer
#include "DebugImageViewerClient.h"
#endif
#include "BRAINSFitUtils.h"
#include "itkEuler3DTransform.h"
#include "itkCheckerBoardImageFilter.h"
#include "itkOtsuHistogramMatchingImageFilter.h"
#include <fstream>
#include "BRAINSFitHelperTemplate.h"
#include "itkConjugateGradientLineSearchOptimizerv4.h"
#include "itkLBFGSBOptimizerv4.h"
#include "itkLabelObject.h"
#include "itkStatisticsLabelObject.h"
#include "itkLabelImageToStatisticsLabelMapFilter.h"
#include "itkMacro.h"
namespace itk
{
inline
void
ValidateTransformRankOrdering(const std::vector<std::string> & transformType)
{
// Need to review transform types in the transform type vector to ensure that
// they are ordered appropriately
// for processing. I.e. that they go from low dimensional to high
// dimensional, and throw an error if
// B-Spline is before Rigid, or any other non-sensical ordering of the
// transform types.
// Rigid=1, ScaleVersor3D=2, ScaleSkewVersor3D=3, Affine=4, and (BSpline or SyN)=5
#define VTROExceptionMacroMacro() \
itkGenericExceptionMacro(<< "Ordering of transforms does not proceed from\n" \
<< "smallest to largest. Please review settings for transformType.\n" \
<< "Rigid < ScaleVersor3D < ScaleSkewVersor3D < Affine < (BSpline | SyN)")
if( transformType.empty() )
{
itkGenericExceptionMacro(<< " ERROR: No transform type specified.");
}
unsigned int CurrentTransformRank = 0;
for( unsigned int l = 0; l < transformType.size(); ++l )
{
if( transformType[l] == "Rigid" )
{
if( CurrentTransformRank <= 1 )
{
CurrentTransformRank = 1;
}
else
{
VTROExceptionMacroMacro();
}
}
else if( transformType[l] == "ScaleVersor3D" )
{
if( CurrentTransformRank <= 2 )
{
CurrentTransformRank = 2;
}
else
{
VTROExceptionMacroMacro();
}
}
else if( transformType[l] == "ScaleSkewVersor3D" )
{
if( CurrentTransformRank <= 3 )
{
CurrentTransformRank = 3;
}
else
{
VTROExceptionMacroMacro();
}
}
else if( transformType[l] == "Affine" )
{
if( CurrentTransformRank <= 4 )
{
CurrentTransformRank = 4;
}
else
{
VTROExceptionMacroMacro();
}
}
else if( transformType[l] == "BSpline" )
{
if( CurrentTransformRank <= 5 )
{
CurrentTransformRank = 5;
}
else
{
VTROExceptionMacroMacro();
}
}
else if( transformType[l] == "SyN" )
{
if( CurrentTransformRank <= 5 )
{
CurrentTransformRank = 5;
}
else
{
VTROExceptionMacroMacro();
}
}
else
{
std::cerr << " ERROR: Invalid transform type specified for element " << l << " of --transformType: "
<< transformType[l] << std::endl;
VTROExceptionMacroMacro();
}
}
}
template <class FixedImageType, class MovingImageType, class TransformType,
class SpecificInitializerType, typename MetricType>
typename TransformType::Pointer
DoCenteredInitialization( typename FixedImageType::Pointer & orientedFixedVolume,
typename MovingImageType::Pointer & orientedMovingVolume,
ImageMaskPointer & fixedMask, // NOTE: This is both input and output
// variable, the Mask is updated by
// this function
ImageMaskPointer & movingMask, // NOTE: This is both input and output
// variable, the Mask is updated by
// this function
std::string & initializeTransformMode,
typename MetricType::Pointer & CostMetricObject )
{
typedef itk::Image<unsigned char, 3> MaskImageType;
typedef itk::ImageMaskSpatialObject<MaskImageType::ImageDimension> ImageMaskSpatialObjectType;
typename TransformType::Pointer initialITKTransform = TransformType::New();
initialITKTransform->SetIdentity();
if( initializeTransformMode == "useGeometryAlign" )
{
// useGeometryAlign assumes objects are center in field of view, with
// different
typedef itk::CenteredTransformInitializer<TransformType, FixedImageType,
MovingImageType> OrdinaryInitializerType;
typename OrdinaryInitializerType::Pointer CenteredInitializer =
OrdinaryInitializerType::New();
CenteredInitializer->SetFixedImage(orientedFixedVolume);
CenteredInitializer->SetMovingImage(orientedMovingVolume);
CenteredInitializer->SetTransform(initialITKTransform);
CenteredInitializer->GeometryOn(); // Use the image spce center
CenteredInitializer->InitializeTransform();
}
else if( initializeTransformMode == "useCenterOfROIAlign" )
{
if( movingMask.IsNull() || fixedMask.IsNull() )
{
itkGenericExceptionMacro(<< "FAILURE: Improper mode for initializeTransformMode: "
<< initializeTransformMode);
}
typedef typename itk::ImageMaskSpatialObject<FixedImageType::ImageDimension> CROIImageMaskSpatialObjectType;
typedef itk::Image<unsigned char, 3> CROIMaskImageType;
typename MovingImageType::PointType movingCenter;
typename FixedImageType::PointType fixedCenter;
typename CROIImageMaskSpatialObjectType::Pointer movingImageMask(
dynamic_cast<CROIImageMaskSpatialObjectType *>( movingMask.GetPointer() ) );
typename CROIMaskImageType::Pointer tempOutputMovingVolumeROI =
const_cast<CROIMaskImageType *>( movingImageMask->GetImage() );
typename CROIImageMaskSpatialObjectType::Pointer fixedImageMask(
dynamic_cast<CROIImageMaskSpatialObjectType *>( fixedMask.GetPointer() ) );
typename CROIMaskImageType::Pointer tempOutputFixedVolumeROI =
const_cast<CROIMaskImageType *>( fixedImageMask->GetImage() );
typedef itk::CastImageFilter<CROIMaskImageType, FixedImageType> MaskToFixedCastType;
typedef itk::CastImageFilter<CROIMaskImageType, MovingImageType> MaskToMovingCastType;
typename MaskToFixedCastType::Pointer mask2fixedCast = MaskToFixedCastType::New();
typename MaskToMovingCastType::Pointer mask2movingCast = MaskToMovingCastType::New();
mask2fixedCast->SetInput(tempOutputFixedVolumeROI);
mask2fixedCast->Update();
mask2movingCast->SetInput(tempOutputMovingVolumeROI);
mask2movingCast->Update();
typename SpecificInitializerType::Pointer CenteredInitializer =
SpecificInitializerType::New();
CenteredInitializer->SetFixedImage(mask2fixedCast->GetOutput() );
CenteredInitializer->SetMovingImage(mask2movingCast->GetOutput() );
CenteredInitializer->SetTransform(initialITKTransform);
CenteredInitializer->MomentsOn(); // Use intensity center of
// mass
CenteredInitializer->InitializeTransform();
}
else if( initializeTransformMode == "useCenterOfHeadAlign" )
{
typedef itk::Image<unsigned char, 3> CHMMaskImageType;
typename MovingImageType::PointType movingCenter;
typename FixedImageType::PointType fixedCenter;
typedef typename itk::FindCenterOfBrainFilter<MovingImageType>
MovingFindCenterFilter;
typename MovingFindCenterFilter::Pointer movingFindCenter =
MovingFindCenterFilter::New();
movingFindCenter->SetInput(orientedMovingVolume);
if( movingMask.IsNotNull() )
{
typename ImageMaskSpatialObjectType::Pointer movingImageMask(
dynamic_cast<ImageMaskSpatialObjectType *>( movingMask.GetPointer() ) );
typename CHMMaskImageType::Pointer tempOutputMovingVolumeROI =
const_cast<CHMMaskImageType *>( movingImageMask->GetImage() );
movingFindCenter->SetImageMask(tempOutputMovingVolumeROI);
}
movingFindCenter->Update();
movingCenter = movingFindCenter->GetCenterOfBrain();
{
// convert mask image to mask
typename ImageMaskSpatialObjectType::Pointer mask = ImageMaskSpatialObjectType::New();
mask->SetImage( movingFindCenter->GetClippedImageMask() );
mask->ComputeObjectToWorldTransform();
typename SpatialObjectType::Pointer p = dynamic_cast<SpatialObjectType *>( mask.GetPointer() );
if( p.IsNull() )
{
itkGenericExceptionMacro(<< "Can't convert mask pointer to SpatialObject");
}
movingMask = p;
}
typedef typename itk::FindCenterOfBrainFilter<FixedImageType>
FixedFindCenterFilter;
typename FixedFindCenterFilter::Pointer fixedFindCenter =
FixedFindCenterFilter::New();
fixedFindCenter->SetInput(orientedFixedVolume);
if( fixedMask.IsNotNull() )
{
typename ImageMaskSpatialObjectType::Pointer fixedImageMask(
dynamic_cast<ImageMaskSpatialObjectType *>( fixedMask.GetPointer() ) );
typename CHMMaskImageType::Pointer tempOutputFixedVolumeROI =
const_cast<CHMMaskImageType *>( fixedImageMask->GetImage() );
fixedFindCenter->SetImageMask(tempOutputFixedVolumeROI);
}
fixedFindCenter->Update();
fixedCenter = fixedFindCenter->GetCenterOfBrain();
{
// convert mask image to mask
typename ImageMaskSpatialObjectType::Pointer mask = ImageMaskSpatialObjectType::New();
mask->SetImage( fixedFindCenter->GetClippedImageMask() );
mask->ComputeObjectToWorldTransform();
typename SpatialObjectType::Pointer p = dynamic_cast<SpatialObjectType *>( mask.GetPointer() );
if( p.IsNull() )
{
itkGenericExceptionMacro(<< "Can't convert mask pointer to SpatialObject");
}
fixedMask = p;
}
const double movingHeadScaleGuessRatio = 1;
/*
*
*fixedFindCenter->GetHeadSizeEstimate()/movingFindCenter->GetHeadSizeEstimate();
*/
typename TransformType::InputPointType rotationCenter;
typename TransformType::OutputVectorType translationVector;
itk::Vector<double, 3> scaleValue;
for( unsigned int i = 0; i < Dimension; i++ )
{
rotationCenter[i] = fixedCenter[i];
translationVector[i] = movingCenter[i] - fixedCenter[i];
scaleValue[i] = movingHeadScaleGuessRatio;
}
typedef itk::Euler3DTransform<double> EulerAngle3DTransformType;
typename EulerAngle3DTransformType::Pointer bestEulerAngles3D = EulerAngle3DTransformType::New();
bestEulerAngles3D->SetCenter(rotationCenter);
bestEulerAngles3D->SetTranslation(translationVector);
typedef itk::Euler3DTransform<double> EulerAngle3DTransformType;
typename EulerAngle3DTransformType::Pointer currentEulerAngles3D = EulerAngle3DTransformType::New();
currentEulerAngles3D->SetCenter(rotationCenter);
currentEulerAngles3D->SetTranslation(translationVector);
CostMetricObject->SetMovingTransform(currentEulerAngles3D);
CostMetricObject->Initialize();
{
currentEulerAngles3D->SetRotation(0, 0, 0);
// Initialize with current guess;
//double max_cc = CostMetricObject->GetValue( currentEulerAngles3D->GetParameters() );
double max_cc = CostMetricObject->GetValue();
// rough search in neighborhood.
const double one_degree = 1.0F * vnl_math::pi / 180.0F;
const double HAStepSize = 3.0 * one_degree;
const double PAStepSize = 3.0 * one_degree;
// Quick search just needs to get an approximate angle correct.
{
const double HARange = 12.0;
for( double HA = -HARange * one_degree; HA <= HARange * one_degree; HA += HAStepSize )
{
const double PARange = 12.0;
for( double PA = -PARange * one_degree; PA <= PARange * one_degree; PA += PAStepSize )
{
currentEulerAngles3D->SetRotation(PA, 0, HA);
//const double current_cc = CostMetricObject->GetValue( currentEulerAngles3D->GetParameters() );
const double current_cc = CostMetricObject->GetValue();
if( current_cc < max_cc )
{
max_cc = current_cc;
bestEulerAngles3D->SetFixedParameters( currentEulerAngles3D->GetFixedParameters() );
bestEulerAngles3D->SetParameters( currentEulerAngles3D->GetParameters() );
}
// #define DEBUGGING_PRINT_IMAGES
#ifdef DEBUGGING_PRINT_IMAGES
{
std::cout << "quick search "
<< " HA= " << ( currentEulerAngles3D->GetParameters()[2] ) * 180.0 / vnl_math::pi
<< " PA= " << ( currentEulerAngles3D->GetParameters()[0] ) * 180.0 / vnl_math::pi
<< " cc=" << current_cc
<< std::endl;
}
if( 0 )
{
typedef itk::ResampleImageFilter<FixedImageType, MovingImageType, double> ResampleFilterType;
typename ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform(currentEulerAngles3D);
resampler->SetInput(orientedMovingVolume);
// Remember: the Data is Moving's, the shape is Fixed's.
resampler->SetOutputParametersFromImage(orientedFixedVolume);
resampler->Update(); // Explicit Update() required
// here.
typename FixedImageType::Pointer ResampledImage = resampler->GetOutput();
typedef itk::CheckerBoardImageFilter<FixedImageType> Checkerfilter;
typename Checkerfilter::Pointer checker = Checkerfilter::New();
unsigned int array[3] = { 36, 36, 36 };
checker->SetInput1(orientedFixedVolume);
checker->SetInput2(ResampledImage);
checker->SetCheckerPattern(array);
try
{
checker->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Caught an ITK exception: " << std::endl;
std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl;
throw;
}
char filename[300];
sprintf(filename, "%05.2f_%05.2f_%05.2f.nii.gz",
( currentEulerAngles3D->GetParameters()[2] ) * 180 / vnl_math::pi,
( currentEulerAngles3D->GetParameters()[0] ) * 180 / vnl_math::pi, current_cc);
{
typedef typename itk::ImageFileWriter<FixedImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->UseCompressionOn();
writer->SetFileName(filename);
writer->SetInput( checker->GetOutput() );
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception Object caught: " << std::endl;
std::cout << err << std::endl;
throw;
}
}
}
#endif
}
}
}
// DEBUGGING_PRINT_IMAGES INFORMATION
#ifdef DEBUGGING_PRINT_IMAGES
{
std::cout << "FINAL: quick search "
<< " HA= " << ( bestEulerAngles3D->GetParameters()[2] ) * 180.0 / vnl_math::pi
<< " PA= " << ( bestEulerAngles3D->GetParameters()[0] ) * 180.0 / vnl_math::pi
<< " cc=" << max_cc
<< std::endl;
}
#endif
}
typedef itk::VersorRigid3DTransform<double> VersorRigid3DTransformType;
typename VersorRigid3DTransformType::Pointer quickSetVersor = VersorRigid3DTransformType::New();
quickSetVersor->SetCenter( bestEulerAngles3D->GetCenter() );
quickSetVersor->SetTranslation( bestEulerAngles3D->GetTranslation() );
{
itk::Versor<double> localRotation;
localRotation.Set( bestEulerAngles3D->GetMatrix() );
quickSetVersor->SetRotation(localRotation);
}
#ifdef DEBUGGING_PRINT_IMAGES
{
typedef itk::ResampleImageFilter<FixedImageType, MovingImageType, double> ResampleFilterType;
typename ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform(quickSetVersor);
resampler->SetInput(orientedMovingVolume);
// Remember: the Data is Moving's, the shape is Fixed's.
resampler->SetOutputParametersFromImage(orientedFixedVolume);
resampler->Update(); // Explicit Update() required here.
typename FixedImageType::Pointer ResampledImage = resampler->GetOutput();
typedef itk::CheckerBoardImageFilter<FixedImageType> Checkerfilter;
typename Checkerfilter::Pointer checker = Checkerfilter::New();
unsigned int array[3] = { 18, 18, 18 };
checker->SetInput1(orientedFixedVolume);
checker->SetInput2(ResampledImage);
checker->SetCheckerPattern(array);
try
{
checker->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Caught an ITK exception: " << std::endl;
std::cout << err << " " << __FILE__ << " " << __LINE__ << std::endl;
throw;
}
char filename[300];
sprintf(filename, "FINAL_%05.2f_%05.2f_%05.2f.nii.gz",
( bestEulerAngles3D->GetParameters()[2] ) * 180 / vnl_math::pi,
( bestEulerAngles3D->GetParameters()[0] ) * 180 / vnl_math::pi, max_cc);
{
typedef typename itk::ImageFileWriter<FixedImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
wirter->UseCompressionOn();
writer->SetFileName(filename);
writer->SetInput(ResampledImage);
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cout << "Exception Object caught: " << std::endl;
std::cout << err << std::endl;
throw;
}
}
}
#endif
AssignRigid::AssignConvertedTransform( initialITKTransform, quickSetVersor.GetPointer() );
}
else if( initializeTransformMode == "useMomentsAlign" )
{
// useMomentsAlign assumes that the structures being registered have same
// amount of mass approximately uniformly distributed.
typename SpecificInitializerType::Pointer CenteredInitializer =
SpecificInitializerType::New();
CenteredInitializer->SetFixedImage(orientedFixedVolume);
CenteredInitializer->SetMovingImage(orientedMovingVolume);
CenteredInitializer->SetTransform(initialITKTransform);
CenteredInitializer->MomentsOn(); // Use intensity center of mass
CenteredInitializer->InitializeTransform();
}
else // can't happen unless an unimplemented CLP option was added:
{
itkGenericExceptionMacro(<< "FAILURE: Improper mode for initializeTransformMode: "
<< initializeTransformMode);
}
std::cout << "Initializing transform with " << initializeTransformMode
<< " to " << std::endl;
std::cout << initialITKTransform << std::endl;
std::cout << "===============================================" << std::endl;
return initialITKTransform;
}
template <class FixedImageType, class MovingImageType>
BRAINSFitHelperTemplate<FixedImageType, MovingImageType>::BRAINSFitHelperTemplate() :
m_FixedVolume(ITK_NULLPTR),
m_FixedVolume2(ITK_NULLPTR),
m_MovingVolume(ITK_NULLPTR),
m_MovingVolume2(ITK_NULLPTR),
m_FixedBinaryVolume(ITK_NULLPTR),
m_MovingBinaryVolume(ITK_NULLPTR),
m_OutputFixedVolumeROI(""),
m_OutputMovingVolumeROI(""),
m_SamplingPercentage(1),
m_NumberOfHistogramBins(50),
m_HistogramMatch(false),
m_RemoveIntensityOutliers(0.00),
m_NumberOfMatchPoints(10),
m_NumberOfIterations(1, 1500),
m_MaximumStepLength(0.2),
m_MinimumStepLength(1, 0.005),
m_RelaxationFactor(0.5),
m_TranslationScale(1000.0),
m_ReproportionScale(1.0),
m_SkewScale(1.0),
m_BackgroundFillValue(0.0),
m_TransformType(1, "Rigid"),
m_InitializeTransformMode("Off"),
m_MaskInferiorCutOffFromCenter(1000),
m_SplineGridSize(3, 10),
m_CostFunctionConvergenceFactor(1e+9),
m_ProjectedGradientTolerance(1e-5),
m_MaxBSplineDisplacement(0.0),
m_ActualNumberOfIterations(0),
m_PermittedNumberOfIterations(0),
m_DebugLevel(0),
m_CurrentGenericTransform(ITK_NULLPTR),
m_RestoreState(ITK_NULLPTR),
m_DisplayDeformedImage(false),
m_PromptUserAfterDisplay(false),
m_FinalMetricValue(0.0),
m_ObserveIterations(true),
m_CostMetricObject(ITK_NULLPTR),
m_UseROIBSpline(0),
m_SamplingStrategy(AffineRegistrationType::NONE),
m_InitializeRegistrationByCurrentGenericTransform(true),
m_MaximumNumberOfEvaluations(900),
m_MaximumNumberOfCorrections(12),
m_SyNMetricType(""),
m_SaveState(""),
m_SyNFull(true),
m_ForceMINumberOfThreads(-1)
{
m_SplineGridSize[0] = 14;
m_SplineGridSize[1] = 10;
m_SplineGridSize[2] = 12;
}
template <class FixedImageType, class MovingImageType>
template <class TransformType, class OptimizerType, class MetricType>
void
BRAINSFitHelperTemplate<FixedImageType, MovingImageType>::FitCommonCode(
int numberOfIterations,
double minimumStepLength,
typename CompositeTransformType::Pointer & initialITKTransform)
{
// FitCommonCode
typedef typename itk::MultiModal3DMutualRegistrationHelper
<TransformType,
OptimizerType,
FixedImageType,
MovingImageType,
MetricType> MultiModal3DMutualRegistrationHelperType;
typename MultiModal3DMutualRegistrationHelperType::Pointer
appMutualRegistration = MultiModal3DMutualRegistrationHelperType::New();
appMutualRegistration->SetNumberOfHistogramBins(m_NumberOfHistogramBins);
appMutualRegistration->SetNumberOfIterations( numberOfIterations);
appMutualRegistration->SetSamplingStrategy(m_SamplingStrategy);
appMutualRegistration->SetSamplingPercentage(m_SamplingPercentage);
appMutualRegistration->SetRelaxationFactor( m_RelaxationFactor );
appMutualRegistration->SetMaximumStepLength( m_MaximumStepLength );
appMutualRegistration->SetMinimumStepLength( minimumStepLength );
appMutualRegistration->SetTranslationScale( m_TranslationScale );
appMutualRegistration->SetReproportionScale( m_ReproportionScale );
appMutualRegistration->SetSkewScale( m_SkewScale );
// NOTE: binary masks are set for the cost metric object!!!
appMutualRegistration->SetFixedImage( m_FixedVolume );
appMutualRegistration->SetMovingImage( m_MovingVolume );
if( m_FixedVolume2.IsNotNull() && m_MovingVolume2.IsNotNull() )
{
appMutualRegistration->SetFixedImage2( m_FixedVolume2 );
appMutualRegistration->SetMovingImage2( m_MovingVolume2 );
}
appMutualRegistration->SetCostMetricObject( this->m_CostMetricObject );
appMutualRegistration->SetBackgroundFillValue( m_BackgroundFillValue );
appMutualRegistration->SetInitialTransform( initialITKTransform.GetPointer() );
appMutualRegistration->SetDisplayDeformedImage(m_DisplayDeformedImage);
appMutualRegistration->SetPromptUserAfterDisplay(m_PromptUserAfterDisplay);
appMutualRegistration->SetObserveIterations(m_ObserveIterations);
/*
* At this point appMutualRegistration should be all set to make
* an itk pipeline class templated in TransformType etc.
* with all its inputs in place;
*/
// initialize the interconnects between components
appMutualRegistration->Initialize();
typename CompositeTransformType::Pointer finalTransform;
try
{
appMutualRegistration->Update();
finalTransform = appMutualRegistration->GetTransform(); // finalTransform is a composite transform
// Find the metric value (It is needed when logFileReport flag is ON).
//this->m_FinalMetricValue = appMutualRegistration->GetFinalMetricValue();
this->m_ActualNumberOfIterations = appMutualRegistration->GetActualNumberOfIterations();
this->m_PermittedNumberOfIterations = numberOfIterations;
}
catch( itk::ExceptionObject& err )
{
// pass exception to caller
itkGenericExceptionMacro(<< "Exception caught during registration: " << err);
}
// Put the result transform in the CurrentGenericTransform.
// This composite transform will be used for initailization of the next stage.
//
// Note1: The "finalTransform" is a composite transform that includes the result of the current registratin stage.
//
// Note2: Since the "finalTransform" has already been affected by the previous initial transform,
// we can remove the old initial transform from the queue of the CurrentGenericTransform.
//
this->m_CurrentGenericTransform->ClearTransformQueue();
typename CompositeTransformType::Pointer compToAdd;
typename CompositeTransformType::ConstPointer compXfrm =
dynamic_cast<const CompositeTransformType *>( finalTransform.GetPointer() );
if( compXfrm.IsNotNull() )
{
compToAdd = compXfrm->Clone();
this->m_CurrentGenericTransform = compToAdd;
}
else
{
itkExceptionMacro(<< "The registration output composite transform is a NULL transform.");
}
}
template <class FixedImageType, class MovingImageType>
void
BRAINSFitHelperTemplate<FixedImageType, MovingImageType>::Update(void)
{
typedef itk::Image<unsigned char, 3> MaskImageType;
typedef itk::ImageMaskSpatialObject<MaskImageType::ImageDimension> ImageMaskSpatialObjectType;
typedef itk::VersorRigid3DTransform<double> VersorRigid3DTransformType;
// The m_CostMetricObject should be a multi metric type.
typename MultiMetricType::Pointer multiMetric =
dynamic_cast<MultiMetricType *>( this->m_CostMetricObject.GetPointer() );
if( multiMetric.IsNull() )
{
itkGenericExceptionMacro("Error in metric type conversion");
}
std::vector<FixedImagePointer> preprocessedFixedImagesList;
std::vector<MovingImagePointer> preprocessedMovingImagesList;
preprocessedFixedImagesList.push_back( m_FixedVolume );
preprocessedMovingImagesList.push_back( m_MovingVolume );
if( m_FixedVolume2.IsNotNull() && m_MovingVolume2.IsNotNull() )
{
preprocessedFixedImagesList.push_back( m_FixedVolume2 );
preprocessedMovingImagesList.push_back( m_MovingVolume2 );
}
if( this->m_DebugLevel > 3 )
{
this->PrintSelf(std::cout, 3);
}
std::vector<double> localMinimumStepLength( m_TransformType.size() );
if( m_MinimumStepLength.size() != m_TransformType.size() )
{
if( m_MinimumStepLength.size() != 1 )
{
itkGenericExceptionMacro(<< "ERROR: Wrong number of parameters for MinimumStepLength."
<< "It either needs to be 1 or the same size as TransformType.");
}
for( unsigned int q = 0; q < m_TransformType.size(); ++q )
{
localMinimumStepLength[q] = m_MinimumStepLength[0];
}
}
else
{
localMinimumStepLength = m_MinimumStepLength;
}
std::vector<int> localNumberOfIterations( m_TransformType.size() );
if( m_NumberOfIterations.size() != m_TransformType.size() )
{
if( m_NumberOfIterations.size() != 1 )
{
itkGenericExceptionMacro(<< "ERROR: Wrong number of parameters for NumberOfIterations."
<< " It either needs to be 1 or the same size as TransformType.")
}
for( unsigned int q = 0; q < m_TransformType.size(); ++q )
{
localNumberOfIterations[q] = m_NumberOfIterations[0];
}
}
else
{
localNumberOfIterations = m_NumberOfIterations;
}
std::string localInitializeTransformMode(this->m_InitializeTransformMode);
for( unsigned int currentTransformIndex = 0;
currentTransformIndex < m_TransformType.size();
currentTransformIndex++ )
{
const std::string currentTransformType(m_TransformType[currentTransformIndex]);
std::cout << "TranformTypes: "
<< currentTransformType << "(" << currentTransformIndex + 1 << " of " << m_TransformType.size() << ")."
<< std::endl;
std::cout << std::flush << std::endl;
}
// Initialize Transforms
// Note that we don't want to estimate initialization if initial moving transform is provided already.
if( m_CurrentGenericTransform.IsNull() && localInitializeTransformMode != "Off" )
// Use CenteredVersorTranformInitializer
{
typedef itk::VersorRigid3DTransform<double> TransformType;
std::cout << "Initializing transform with " << localInitializeTransformMode << std::endl;
typedef itk::CenteredVersorTransformInitializer<FixedImageType,
MovingImageType> InitializerType;
TransformType::Pointer initialITKTransform =
DoCenteredInitialization<FixedImageType,
MovingImageType,
TransformType,
InitializerType,
MultiMetricType>(
m_FixedVolume,
m_MovingVolume,
m_FixedBinaryVolume,
m_MovingBinaryVolume,
localInitializeTransformMode,
multiMetric );
// The currentGenericTransform will be initialized by estimated initial transform.
this->m_CurrentGenericTransform = CompositeTransformType::New();
this->m_CurrentGenericTransform->AddTransform( initialITKTransform.GetPointer() );
localInitializeTransformMode = "Off"; // Now reset to Off once initialization is done.
// Now if necessary clip the images based on m_MaskInferiorCutOffFromCenter
DoCenteredTransformMaskClipping<TransformType, FixedImageType::ImageDimension>(
m_FixedBinaryVolume,
m_MovingBinaryVolume,
initialITKTransform,
m_MaskInferiorCutOffFromCenter);
{ // Write out some debugging information if requested
if( ( !this->m_FixedBinaryVolume.IsNull() ) && ( m_OutputFixedVolumeROI != "" ) )
{
const MaskImageType::ConstPointer tempOutputFixedVolumeROI =
ExtractConstPointerToImageMaskFromImageSpatialObject(this->m_FixedBinaryVolume.GetPointer() );
itkUtil::WriteConstImage<MaskImageType>(tempOutputFixedVolumeROI, m_OutputFixedVolumeROI);
}
if( ( !this->m_MovingBinaryVolume.IsNull() ) && ( m_OutputMovingVolumeROI != "" ) )
{
const MaskImageType::ConstPointer tempOutputMovingVolumeROI =
ExtractConstPointerToImageMaskFromImageSpatialObject(this->m_MovingBinaryVolume.GetPointer() );
itkUtil::WriteConstImage<MaskImageType>(tempOutputMovingVolumeROI, m_OutputMovingVolumeROI);
}
}
}
for( unsigned int currentTransformIndex = 0;
currentTransformIndex < m_TransformType.size();
currentTransformIndex++ )
{
const std::string currentTransformType(m_TransformType[currentTransformIndex]);
std::cout << "\n\n\n=============================== "
<< "ITKv4 Registration: Starting Transform Estimations for "
<< currentTransformType << "(" << currentTransformIndex + 1
<< " of " << m_TransformType.size() << ")."
<< "==============================="
<< std::endl;
std::cout << std::flush << std::endl;
//
// Break into cases on TransformType:
//
if( currentTransformType == "Rigid" )
{
// Choose TransformType for the itk registration class template:
typedef itk::RegularStepGradientDescentOptimizerv4<double> OptimizerType;
//
// Process the initialITKTransform as VersorRigid3DTransform:
//
typedef VersorRigid3DTransformType TransformType;
TransformType::Pointer initialITKTransform = TransformType::New();
initialITKTransform->SetIdentity();
if( m_CurrentGenericTransform.IsNotNull() ) //When null, m_CurrentGenericTransform will be initialized by identity.
{
/* NOTE1: m_CurrentGenericTransform is a composite transform. When not null, it is initialized by:
{Intial Moving Transform
OR
Estimated initial transform indicated by initialTransformMode
OR
Output of previous level}
* NOTE2: If the transform Type of the current level is linear,
the m_CurrentGenericTransform should contain only one transform as we collapse all linear transforms together.
*/
if( m_CurrentGenericTransform->GetNumberOfTransforms() != 1 )
{
itkGenericExceptionMacro("Linear initial composite transform should have only one component \
as all linaear transforms are collapsed together.");
}
const itk::Transform<double, 3, 3>::ConstPointer currInitTransformFormGenericComposite =
m_CurrentGenericTransform->GetFrontTransform();
try
{
const std::string transformFileType = currInitTransformFormGenericComposite->GetNameOfClass();
if( transformFileType == "VersorRigid3DTransform" )
{
const itk::VersorRigid3DTransform<double>::ConstPointer tempInitializerITKTransform =
dynamic_cast<VersorRigid3DTransformType const *>( currInitTransformFormGenericComposite.GetPointer() );
if( tempInitializerITKTransform.IsNull() )
{
std::cout << "Error in type conversion" << __FILE__ << __LINE__ << std::endl;
}
AssignRigid::AssignConvertedTransform(initialITKTransform,
tempInitializerITKTransform);
}
else if( ( transformFileType == "ScaleVersor3DTransform" )
|| ( transformFileType == "ScaleSkewVersor3DTransform" )
|| ( transformFileType == "AffineTransform" ) )
{
// CONVERTING TO RIGID TRANSFORM TYPE from other type:
std::cout << "WARNING: Extracting Rigid component type from transform." << std::endl;
VersorRigid3DTransformType::Pointer tempInitializerITKTransform =
ComputeRigidTransformFromGeneric(currInitTransformFormGenericComposite.GetPointer() );
AssignRigid::AssignConvertedTransform( initialITKTransform, tempInitializerITKTransform.GetPointer() );
}
else
{
std::cout
<<
"Unsupported initial transform file -- TransformBase first transform typestring, "
<< transformFileType
<< " not equal to required type VersorRigid3DTransform"
<< std::endl;
return;
}
}
catch( itk::ExceptionObject & excp )
{
std::cout << "[FAILED]" << std::endl;
std::cerr
<< "Error while reading the m_CurrentGenericTransform" << std::endl;
std::cerr << excp << std::endl;
throw;
}
}
else
{
m_CurrentGenericTransform = CompositeTransformType::New();
}
// replace the original initial transform with the extracted version.
m_CurrentGenericTransform->ClearTransformQueue();
m_CurrentGenericTransform->AddTransform( initialITKTransform );
this->FitCommonCode<TransformType, OptimizerType, MetricType>
(localNumberOfIterations[currentTransformIndex],
localMinimumStepLength[currentTransformIndex],
this->m_CurrentGenericTransform);
// NOW, after running the above function, the m_CurrentGenericTransform contains the integration of initial transform and rigid registration results.
///////////////////////
}
else if( currentTransformType == "ScaleVersor3D" )
{
// Choose TransformType for the itk registration class template:
typedef itk::ScaleVersor3DTransform<double> TransformType; // NumberOfEstimatedParameter = 9;
typedef itk::RegularStepGradientDescentOptimizerv4<double> OptimizerType;
//
// Process the initialITKTransform as ScaleVersor3DTransform:
//
TransformType::Pointer initialITKTransform = TransformType::New();
initialITKTransform->SetIdentity();
if( m_CurrentGenericTransform.IsNotNull() )
{
/* NOTE1: m_CurrentGenericTransform is a composite transform. When not null, it is initialized by:
{Intial Moving Transform
OR
Estimated initial transform indicated by initialTransformMode
OR
Output of previous level}
* NOTE2: If the transform Type of the current level is linear,
the m_CurrentGenericTransform should contain only one transform as we collapse all linear transforms together.
*/
if( m_CurrentGenericTransform->GetNumberOfTransforms() != 1 )
{
itkGenericExceptionMacro("Linear initial composite transform should have only one component \
as all linaear transforms are collapsed together.");
}
const itk::Transform<double, 3, 3>::ConstPointer currInitTransformFormGenericComposite =
m_CurrentGenericTransform->GetFrontTransform();
try
{
const std::string transformFileType = currInitTransformFormGenericComposite->GetNameOfClass();
if( transformFileType == "VersorRigid3DTransform" )
{
const VersorRigid3DTransformType::ConstPointer tempInitializerITKTransform =
dynamic_cast<VersorRigid3DTransformType const *>( currInitTransformFormGenericComposite.GetPointer() );
if( tempInitializerITKTransform.IsNull() )
{
std::cout << "Error in type conversion" << __FILE__ << __LINE__ << std::endl;
}
AssignRigid::AssignConvertedTransform(initialITKTransform,
tempInitializerITKTransform);
}
else if( transformFileType == "ScaleVersor3DTransform" )
{
const itk::ScaleVersor3DTransform<double>::ConstPointer tempInitializerITKTransform =
dynamic_cast<itk::ScaleVersor3DTransform<double> const *>( currInitTransformFormGenericComposite.GetPointer() );
if( tempInitializerITKTransform.IsNull() )
{
std::cout << "Error in type conversion" << __FILE__ << __LINE__ << std::endl;
}
AssignRigid::AssignConvertedTransform(initialITKTransform,
tempInitializerITKTransform);
}
else if( ( transformFileType == "ScaleSkewVersor3DTransform" )
|| ( transformFileType == "AffineTransform" ) )
{
// CONVERTING TO RIGID TRANSFORM TYPE from other type:
// TODO: we should preserve the Scale components
std::cout << "WARNING: Extracting Rigid component type from transform." << std::endl;
VersorRigid3DTransformType::Pointer tempInitializerITKTransform = ComputeRigidTransformFromGeneric(
currInitTransformFormGenericComposite.GetPointer() );
AssignRigid::AssignConvertedTransform( initialITKTransform, tempInitializerITKTransform.GetPointer() );
}
else
{
std::cout
<<
"Unsupported initial transform file -- TransformBase first transform typestring, "
<< transformFileType
<<
" not equal to required type VersorRigid3DTransform OR ScaleVersor3DTransform"
<< std::endl;
return;
}
}
catch( itk::ExceptionObject & excp )
{
std::cout << "[FAILED]" << std::endl;
std::cerr
<< "Error while reading the m_CurrentGenericTransform"
<< std::endl;
std::cerr << excp << std::endl;
throw;
}
}
else
{
m_CurrentGenericTransform = CompositeTransformType::New();
}
// replace the original initial transform with the above converted version.
m_CurrentGenericTransform->ClearTransformQueue();
m_CurrentGenericTransform->AddTransform( initialITKTransform );
this->FitCommonCode<TransformType, OptimizerType, MetricType>
(localNumberOfIterations[currentTransformIndex],
localMinimumStepLength[currentTransformIndex],
this->m_CurrentGenericTransform);
// NOW, after running the above function, the m_CurrentGenericTransform contains the integration of initial transform and ScaleVersor registration results.
/////////////////////
}
else if( currentTransformType == "ScaleSkewVersor3D" )
{
// Choose TransformType for the itk registration class template:
typedef itk::ScaleSkewVersor3DTransform<double> TransformType; // NumberOfEstimatedParameter = 15;
typedef itk::RegularStepGradientDescentOptimizerv4<double> OptimizerType;
//
// Process the initialITKTransform as ScaleSkewVersor3D: