-
-
Notifications
You must be signed in to change notification settings - Fork 372
/
antsMotionCorr.cxx
1975 lines (1797 loc) · 82.8 KB
/
antsMotionCorr.cxx
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 Insight Software Consortium
*
* 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 "antsUtilities.h"
#include "antsAllocImage.h"
#include "ReadWriteData.h"
#include "antsCommandLineParser.h"
#include "itkCSVNumericObjectFileWriter.h"
#include "itkImageRegistrationMethodv4.h"
#include "itkSyNImageRegistrationMethod.h"
#include "itkDisplacementFieldTransform.h"
#include "itkANTSNeighborhoodCorrelationImageToImageMetricv4.h"
#include "itkMeanSquaresImageToImageMetricv4.h"
#include "itkCorrelationImageToImageMetricv4.h"
#include "itkImageToImageMetricv4.h"
#include "itkMattesMutualInformationImageToImageMetricv4.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToHistogramFilter.h"
#include "itkHistogramMatchingImageFilter.h"
#include "itkIntensityWindowingImageFilter.h"
#include "itkTransformToDisplacementFieldFilter.h"
#include "itkIdentityTransform.h"
#include "itkAffineTransform.h"
#include "itkBSplineTransform.h"
#include "itkBSplineSmoothingOnUpdateDisplacementFieldTransform.h"
#include "itkCompositeTransform.h"
#include "itkGaussianSmoothingOnUpdateDisplacementFieldTransform.h"
#include "itkIdentityTransform.h"
#include "itkEuler2DTransform.h"
#include "itkEuler3DTransform.h"
#include "itkTransform.h"
#include "itkExtractImageFilter.h"
#include "itkBSplineTransformParametersAdaptor.h"
#include "itkBSplineSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor.h"
#include "itkGaussianSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor.h"
#include "itkTimeVaryingVelocityFieldTransformParametersAdaptor.h"
#include "itkGradientDescentOptimizerv4.h"
#include "itkConjugateGradientLineSearchOptimizerv4.h"
#include "itkQuasiNewtonOptimizerv4.h"
#include "itkHistogramMatchingImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkMacro.h"
#include "itkRegistrationParameterScalesFromPhysicalShift.h"
#include "itkResampleImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkTimeProbe.h"
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkSimilarity2DTransform.h"
#include "itkSimilarity3DTransform.h"
#include <sstream>
namespace ants
{
/** \class antsRegistrationCommandIterationUpdate
* \brief change parameters between iterations of registration
*/
template <typename TFilter>
class antsRegistrationCommandIterationUpdate : public itk::Command
{
public:
typedef antsRegistrationCommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
antsRegistrationCommandIterationUpdate()
{
this->m_LogStream = &std::cout;
}
public:
void Execute(itk::Object *caller, const itk::EventObject & event) override
{
Execute( (const itk::Object *) caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event) override
{
TFilter * filter = const_cast<TFilter *>( dynamic_cast<const TFilter *>( object ) );
unsigned int currentLevel = 0;
if( typeid( event ) == typeid( itk::IterationEvent ) )
{
currentLevel = filter->GetCurrentLevel() + 1;
}
if( currentLevel < this->m_NumberOfIterations.size() )
{
typename TFilter::ShrinkFactorsPerDimensionContainerType shrinkFactors = filter->GetShrinkFactorsPerDimension(
currentLevel );
typename TFilter::SmoothingSigmasArrayType smoothingSigmas = filter->GetSmoothingSigmasPerLevel();
typename TFilter::TransformParametersAdaptorsContainerType adaptors =
filter->GetTransformParametersAdaptorsPerLevel();
this->Logger() << " Current level = " << currentLevel << std::endl;
this->Logger() << " number of iterations = " << this->m_NumberOfIterations[currentLevel] << std::endl;
this->Logger() << " shrink factors = " << shrinkFactors << std::endl;
this->Logger() << " smoothing sigmas = " << smoothingSigmas[currentLevel] << std::endl;
this->Logger() << " required fixed parameters = " << adaptors[currentLevel]->GetRequiredFixedParameters()
<< std::endl;
typedef itk::ConjugateGradientLineSearchOptimizerv4 GradientDescentOptimizerType;
GradientDescentOptimizerType * optimizer = reinterpret_cast<GradientDescentOptimizerType *>( filter->GetModifiableOptimizer() );
optimizer->SetNumberOfIterations( this->m_NumberOfIterations[currentLevel] );
optimizer->SetMinimumConvergenceValue( 1.e-7 );
optimizer->SetConvergenceWindowSize( 10 );
optimizer->SetLowerLimit( 0 );
optimizer->SetUpperLimit( 2 );
optimizer->SetEpsilon( 0.1 );
}
}
void SetNumberOfIterations( const std::vector<unsigned int> & iterations )
{
this->m_NumberOfIterations = iterations;
}
void SetLogStream(std::ostream & logStream)
{
this->m_LogStream = &logStream;
}
private:
std::ostream & Logger() const
{
return *m_LogStream;
}
std::vector<unsigned int> m_NumberOfIterations;
std::ostream * m_LogStream;
};
template <typename T>
inline std::string ants_moco_to_string(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
template <typename ImageType>
typename ImageType::Pointer PreprocessImage( ImageType * inputImage,
typename ImageType::PixelType lowerScaleFunction,
typename ImageType::PixelType upperScaleFunction,
float winsorizeLowerQuantile, float winsorizeUpperQuantile,
ImageType *histogramMatchSourceImage = nullptr )
{
bool verbose = false;
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 lowerFunction = histogramFilter->GetOutput()->Quantile( 0, winsorizeLowerQuantile );
float upperFunction = histogramFilter->GetOutput()->Quantile( 0, winsorizeUpperQuantile );
typedef itk::IntensityWindowingImageFilter<ImageType, ImageType> IntensityWindowingImageFilterType;
typename IntensityWindowingImageFilterType::Pointer windowingFilter = IntensityWindowingImageFilterType::New();
windowingFilter->SetInput( inputImage );
windowingFilter->SetWindowMinimum( lowerFunction );
windowingFilter->SetWindowMaximum( upperFunction );
windowingFilter->SetOutputMinimum( lowerScaleFunction );
windowingFilter->SetOutputMaximum( upperScaleFunction );
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();
typedef itk::MinimumMaximumImageCalculator<ImageType> CalculatorType;
typename CalculatorType::Pointer calc = CalculatorType::New();
calc->SetImage( inputImage );
calc->ComputeMaximum();
calc->ComputeMinimum();
if( itk::Math::abs ( calc->GetMaximum() - calc->GetMinimum() ) < 1.e-9 )
{
if ( verbose ) std::cout << "Warning: bad time point - too little intensity variation" << std::endl;
return histogramMatchSourceImage;
}
}
else
{
outputImage = windowingFilter->GetOutput();
outputImage->Update();
outputImage->DisconnectPipeline();
}
return outputImage;
}
template <typename T>
struct ants_moco_index_cmp
{
ants_moco_index_cmp(const T _arr) : arr(_arr)
{
}
bool operator()(const size_t a, const size_t b) const
{
return arr[a] < arr[b];
}
const T arr;
};
template <typename TFilter>
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() = default;
public:
void Execute(itk::Object *caller, const itk::EventObject & event) override
{
Execute( (const itk::Object *) caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event) override
{
bool verbose = false;
TFilter * filter = const_cast<TFilter *>( dynamic_cast<const TFilter *>( object ) );
if( typeid( event ) != typeid( itk::IterationEvent ) )
{
return;
}
unsigned int currentLevel = filter->GetCurrentLevel();
typename TFilter::ShrinkFactorsPerDimensionContainerType shrinkFactors = filter->GetShrinkFactorsPerDimension(
currentLevel );
typename TFilter::SmoothingSigmasArrayType smoothingSigmas = filter->GetSmoothingSigmasPerLevel();
typename TFilter::TransformParametersAdaptorsContainerType adaptors =
filter->GetTransformParametersAdaptorsPerLevel();
if ( verbose ) std::cout << " Current level = " << currentLevel << std::endl;
if ( verbose ) std::cout << " number of iterations = " << this->m_NumberOfIterations[currentLevel] << std::endl;
if ( verbose ) std::cout << " shrink factor = " << shrinkFactors[currentLevel] << std::endl;
if ( verbose ) std::cout << " smoothing sigma = " << smoothingSigmas[currentLevel] << std::endl;
if ( verbose ) std::cout << " required fixed parameters = " << adaptors[currentLevel]->GetRequiredFixedParameters()
<< std::endl;
typedef itk::ConjugateGradientLineSearchOptimizerv4 OptimizerType;
OptimizerType * optimizer = reinterpret_cast<OptimizerType *>( filter->GetModifiableOptimizer() );
optimizer->SetNumberOfIterations( this->m_NumberOfIterations[currentLevel] );
optimizer->SetMinimumConvergenceValue( 1.e-7 );
optimizer->SetConvergenceWindowSize( 10 );
optimizer->SetLowerLimit( 0 );
optimizer->SetUpperLimit( 2 );
optimizer->SetEpsilon( 0.1 );
}
void SetNumberOfIterations( std::vector<unsigned int> iterations )
{
this->m_NumberOfIterations = iterations;
}
private:
std::vector<unsigned int> m_NumberOfIterations;
};
// Transform traits to generalize the rigid transform
//
template <unsigned int ImageDimension>
class RigidTransformTraits
{
// Don't worry about the fact that the default option is the
// affine Transform, that one will not actually be instantiated.
public:
typedef itk::AffineTransform<double, ImageDimension> TransformType;
};
template <>
class RigidTransformTraits<2>
{
public:
typedef itk::Euler2DTransform<double> TransformType;
};
template <>
class RigidTransformTraits<3>
{
public:
// typedef itk::VersorRigid3DTransform<double> TransformType;
// typedef itk::QuaternionRigidTransform<double> TransformType;
typedef itk::Euler3DTransform<double> TransformType;
};
template <unsigned int ImageDimension>
class SimilarityTransformTraits
{
// Don't worry about the fact that the default option is the
// affine Transform, that one will not actually be instantiated.
public:
typedef itk::AffineTransform<double, ImageDimension> TransformType;
};
template <>
class SimilarityTransformTraits<2>
{
public:
typedef itk::Similarity2DTransform<double> TransformType;
};
template <>
class SimilarityTransformTraits<3>
{
public:
typedef itk::Similarity3DTransform<double> TransformType;
};
/*
template <unsigned int ImageDimension>
class CompositeAffineTransformTraits
{
// Don't worry about the fact that the default option is the
// affine Transform, that one will not actually be instantiated.
public:
typedef itk::AffineTransform<double, ImageDimension> TransformType;
};
template <>
class CompositeAffineTransformTraits<2>
{
public:
typedef itk::ANTSCenteredAffine2DTransform<double> TransformType;
};
template <>
class CompositeAffineTransformTraits<3>
{
public:
typedef itk::ANTSAffine3DTransform<double> TransformType;
};
*/
template <typename TImageIn, typename TImageOut>
void
AverageTimeImages( typename TImageIn::Pointer image_in, typename TImageOut::Pointer image_avg,
std::vector<unsigned int> timelist )
{
bool verbose = false;
typedef TImageIn ImageType;
typedef TImageOut OutImageType;
enum { ImageDimension = ImageType::ImageDimension };
typedef itk::ImageRegionIteratorWithIndex<OutImageType> Iterator;
image_avg->FillBuffer(0);
unsigned int timedims = image_in->GetLargestPossibleRegion().GetSize()[ImageDimension - 1];
if( timelist.empty() )
{
for( unsigned int timedim = 0; timedim < timedims; timedim++ )
{
timelist.push_back(timedim);
}
}
if ( verbose ) std::cout << " averaging with " << timelist.size() << " images of " << timedims << " timedims " << std::endl;
Iterator vfIter2( image_avg, image_avg->GetLargestPossibleRegion() );
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
typename OutImageType::PixelType fval = 0;
typename ImageType::IndexType ind;
typename OutImageType::IndexType spind = vfIter2.GetIndex();
for(unsigned int & xx : timelist)
{
for( unsigned int yy = 0; yy < ImageDimension - 1; yy++ )
{
ind[yy] = spind[yy];
}
ind[ImageDimension - 1] = xx;
fval += image_in->GetPixel(ind);
}
fval /= (double)timelist.size();
image_avg->SetPixel(spind, fval);
}
if ( verbose ) std::cout << " averaging images done " << std::endl;
return;
}
template <unsigned int ImageDimension>
int ants_motion( itk::ants::CommandLineParser *parser )
{
unsigned int verbose = 0;
itk::ants::CommandLineParser::OptionType::Pointer vOption =
parser->GetOption( "verbose" );
if( vOption && vOption->GetNumberOfFunctions() )
{
verbose = parser->Convert<unsigned int>( vOption->GetFunction( 0 )->GetName() );
}
if ( verbose ) std::cout << " verbose " << std::endl;
// We infer the number of stages by the number of transformations
// specified by the user which should match the number of metrics.
unsigned numberOfStages = 0;
typedef float PixelType;
typedef double RealType;
typedef itk::Image<PixelType, ImageDimension> FixedIOImageType;
typedef itk::Image<PixelType, ImageDimension> FixedImageType;
typedef itk::Image<PixelType, ImageDimension + 1> MovingIOImageType;
typedef itk::Image<PixelType, ImageDimension + 1> MovingImageType;
typedef itk::Vector<RealType, ImageDimension+1> VectorIOType;
typedef itk::Image<VectorIOType, ImageDimension+1> DisplacementIOFieldType;
typedef itk::Vector<RealType, ImageDimension> VectorType;
typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType;
typedef vnl_matrix<RealType> vMatrix;
vMatrix param_values;
typedef itk::CompositeTransform<RealType, ImageDimension> CompositeTransformType;
std::vector<typename CompositeTransformType::Pointer> CompositeTransformVector;
typedef typename itk::ants::CommandLineParser ParserType;
typedef typename ParserType::OptionType OptionType;
typename OptionType::Pointer averageOption = parser->GetOption( "average-image" );
if( averageOption && averageOption->GetNumberOfFunctions() )
{
typename OptionType::Pointer outputOption = parser->GetOption( "output" );
if( !outputOption )
{
std::cerr << "Output option not specified. Should be the output average image name." << std::endl;
return EXIT_FAILURE;
}
std::string outputPrefix = outputOption->GetFunction( 0 )->GetParameter( 0 );
if( outputPrefix.length() < 3 )
{
outputPrefix = outputOption->GetFunction( 0 )->GetName();
}
std::string fn = averageOption->GetFunction( 0 )->GetName();
typename MovingIOImageType::Pointer movingImage;
ReadImage<MovingIOImageType>( movingImage, fn.c_str() );
typename FixedIOImageType::Pointer avgImage;
typedef itk::ExtractImageFilter<MovingIOImageType, FixedIOImageType> ExtractFilterType;
typename MovingIOImageType::RegionType extractRegion = movingImage->GetLargestPossibleRegion();
extractRegion.SetSize(ImageDimension, 0);
typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
extractFilter->SetInput( movingImage );
extractFilter->SetDirectionCollapseToSubmatrix();
if( ImageDimension == 2 )
{
extractFilter->SetDirectionCollapseToIdentity();
}
unsigned int td = 0;
extractRegion.SetIndex(ImageDimension, td );
extractFilter->SetExtractionRegion( extractRegion );
extractFilter->Update();
avgImage = extractFilter->GetOutput();
std::vector<unsigned int> timelist;
AverageTimeImages<MovingIOImageType, FixedIOImageType>( movingImage, avgImage, timelist );
if ( verbose ) std::cout << "average out " << outputPrefix << std::endl;
WriteImage<FixedIOImageType>( avgImage, outputPrefix.c_str() );
return EXIT_SUCCESS;
}
typename OptionType::Pointer transformOption = parser->GetOption( "transform" );
if( transformOption && transformOption->GetNumberOfFunctions() )
{
numberOfStages = transformOption->GetNumberOfFunctions();
}
else
{
std::cerr << "No transformations are specified." << std::endl;
return EXIT_FAILURE;
}
if ( verbose ) std::cout << "Registration using " << numberOfStages << " total stages." << std::endl;
typename OptionType::Pointer metricOption = parser->GetOption( "metric" );
if( !metricOption || metricOption->GetNumberOfFunctions() != numberOfStages )
{
std::cerr << "The number of metrics specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
typename OptionType::Pointer iterationsOption = parser->GetOption( "iterations" );
if( !iterationsOption || iterationsOption->GetNumberOfFunctions() != numberOfStages )
{
std::cerr << "The number of iteration sets specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
typename OptionType::Pointer shrinkFactorsOption = parser->GetOption( "shrinkFactors" );
if( !shrinkFactorsOption || shrinkFactorsOption->GetNumberOfFunctions() != numberOfStages )
{
std::cerr << "The number of shrinkFactor sets specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
typename OptionType::Pointer smoothingSigmasOption = parser->GetOption( "smoothingSigmas" );
if( !smoothingSigmasOption || smoothingSigmasOption->GetNumberOfFunctions() != numberOfStages )
{
std::cerr << "The number of smoothing sigma sets specified does not match the number of stages." << std::endl;
return EXIT_FAILURE;
}
typename OptionType::Pointer outputOption = parser->GetOption( "output" );
if( !outputOption )
{
std::cerr << "Output option not specified." << std::endl;
return EXIT_FAILURE;
}
std::string outputPrefix = outputOption->GetFunction( 0 )->GetParameter( 0 );
if( outputPrefix.length() < 3 )
{
outputPrefix = outputOption->GetFunction( 0 )->GetName();
}
unsigned int nimagestoavg = 0;
itk::ants::CommandLineParser::OptionType::Pointer navgOption = parser->GetOption( "n-images" );
if( navgOption && navgOption->GetNumberOfFunctions() )
{
nimagestoavg = parser->Convert<unsigned int>( navgOption->GetFunction( 0 )->GetName() );
if ( verbose ) std::cout << " nimagestoavg " << nimagestoavg << std::endl;
}
unsigned int writeDisplacementField = 0;
itk::ants::CommandLineParser::OptionType::Pointer wdopt = parser->GetOption( "write-displacement" );
if( wdopt && wdopt->GetNumberOfFunctions() )
{
writeDisplacementField = parser->Convert<unsigned int>( wdopt->GetFunction( 0 )->GetName() );
}
bool doEstimateLearningRateOnce(false);
OptionType::Pointer rateOption = parser->GetOption( "use-estimate-learning-rate-once" );
if( rateOption && rateOption->GetNumberOfFunctions() )
{
std::string rateFunction = rateOption->GetFunction( 0 )->GetName();
ConvertToLowerCase( rateFunction );
if( rateFunction.compare( "1" ) == 0 || rateFunction.compare( "true" ) == 0 )
{
doEstimateLearningRateOnce = true;
}
}
bool doHistogramMatch(true);
OptionType::Pointer histogramMatchOption = parser->GetOption( "use-histogram-matching" );
if( histogramMatchOption && histogramMatchOption->GetNumberOfFunctions() )
{
std::string histogramMatchFunction = histogramMatchOption->GetFunction( 0 )->GetName();
ConvertToLowerCase( histogramMatchFunction );
if( histogramMatchFunction.compare( "0" ) == 0 || histogramMatchFunction.compare( "false" ) == 0 )
{
doHistogramMatch = false;
}
}
// Zero seed means use default behavior: registration randomizer seeds from system time
// and does not re-seed iterator
int antsRandomSeed = 0;
itk::ants::CommandLineParser::OptionType::Pointer randomSeedOption = parser->GetOption( "random-seed" );
if( randomSeedOption && randomSeedOption->GetNumberOfFunctions() )
{
antsRandomSeed = parser->Convert<int>( randomSeedOption->GetFunction(0)->GetName() );
}
else
{
char* envSeed = getenv( "ANTS_RANDOM_SEED" );
if ( envSeed != nullptr )
{
antsRandomSeed = std::stoi( envSeed );
}
}
unsigned int nparams = 2;
itk::TimeProbe totalTimer;
totalTimer.Start();
double metricmean = 0;
typedef itk::AffineTransform<RealType, ImageDimension> AffineTransformType;
typedef itk::ImageRegistrationMethodv4<FixedImageType, FixedImageType, AffineTransformType> AffineRegistrationType;
// We iterate backwards because the command line options are stored as a stack (first in last out)
typename DisplacementIOFieldType::Pointer displacementout = nullptr;
typename DisplacementIOFieldType::Pointer displacementinv = nullptr;
for( int currentStage = numberOfStages - 1; currentStage >= 0; currentStage-- )
{
if ( verbose ) std::cout << std::endl << "Stage " << numberOfStages - currentStage << std::endl;
std::stringstream currentStageString;
currentStageString << currentStage;
// Get the fixed and moving images
std::string fixedImageFileName = metricOption->GetFunction( currentStage )->GetParameter( 0 );
std::string movingImageFileName = metricOption->GetFunction( currentStage )->GetParameter( 1 );
if ( verbose ) std::cout << " fixed image: " << fixedImageFileName << std::endl;
if ( verbose ) std::cout << " moving image: " << movingImageFileName << std::endl;
typename FixedImageType::Pointer fixed_time_slice = nullptr;
typename FixedImageType::Pointer moving_time_slice = nullptr;
typename FixedIOImageType::Pointer fixedInImage;
ReadImage<FixedIOImageType>( fixedInImage, fixedImageFileName.c_str() );
fixedInImage->Update();
fixedInImage->DisconnectPipeline();
typename FixedImageType::Pointer fixedImage;
fixedImage = arCastImage<FixedIOImageType, FixedImageType>( fixedInImage );
typename MovingIOImageType::Pointer movingInImage;
typename MovingImageType::Pointer movingImage;
ReadImage<MovingIOImageType>( movingInImage, movingImageFileName.c_str() );
movingInImage->Update();
movingInImage->DisconnectPipeline();
movingImage = arCastImage<MovingIOImageType, MovingImageType>( movingInImage );
unsigned int timedims = movingImage->GetLargestPossibleRegion().GetSize()[ImageDimension];
typename MovingIOImageType::Pointer outputImage = MovingIOImageType::New();
typename MovingIOImageType::RegionType outRegion;
typename MovingIOImageType::SizeType outSize;
typename MovingIOImageType::SpacingType outSpacing;
typename MovingIOImageType::PointType outOrigin;
typename MovingIOImageType::DirectionType outDirection;
for( unsigned int d = 0; d < ImageDimension; d++ )
{
outSize[d] = fixedImage->GetLargestPossibleRegion().GetSize()[d];
outSpacing[d] = fixedImage->GetSpacing()[d];
outOrigin[d] = fixedImage->GetOrigin()[d];
for( unsigned int e = 0; e < ImageDimension; e++ )
{
outDirection(e, d) = fixedImage->GetDirection() (e, d);
}
}
for( unsigned int d = 0; d < ImageDimension; d++ )
{
outDirection(d, ImageDimension) = 0;
outDirection(ImageDimension, d) = 0;
}
outDirection(ImageDimension, ImageDimension) = 1.0;
outSize[ImageDimension] = timedims;
outSpacing[ImageDimension] = movingImage->GetSpacing()[ImageDimension];
outOrigin[ImageDimension] = movingImage->GetOrigin()[ImageDimension];
outRegion.SetSize( outSize );
outputImage->SetRegions( outRegion );
outputImage->SetSpacing( outSpacing );
outputImage->SetOrigin( outOrigin );
outputImage->SetDirection( outDirection );
outputImage->Allocate();
outputImage->FillBuffer( 0 );
if ( writeDisplacementField > 0 )
{
/** Handle all output: images and displacement fields */
typedef itk::IdentityTransform<RealType, ImageDimension+1> IdentityIOTransformType;
typename IdentityIOTransformType::Pointer identityIOTransform = IdentityIOTransformType::New();
typedef typename itk::TransformToDisplacementFieldFilter<DisplacementIOFieldType, RealType> ConverterType;
typename ConverterType::Pointer idconverter = ConverterType::New();
idconverter->SetOutputOrigin( outputImage->GetOrigin() );
idconverter->SetOutputStartIndex( outputImage->GetBufferedRegion().GetIndex() );
idconverter->SetSize( outputImage->GetBufferedRegion().GetSize() );
idconverter->SetOutputSpacing( outputImage->GetSpacing() );
idconverter->SetOutputDirection( outputImage->GetDirection() );
idconverter->SetTransform( identityIOTransform );
idconverter->Update();
displacementout = idconverter->GetOutput();
typename ConverterType::Pointer invconverter = ConverterType::New();
invconverter->SetOutputOrigin( movingInImage->GetOrigin() );
invconverter->SetOutputStartIndex(
movingInImage->GetBufferedRegion().GetIndex() );
invconverter->SetSize( movingInImage->GetBufferedRegion().GetSize() );
invconverter->SetOutputSpacing( movingInImage->GetSpacing() );
invconverter->SetOutputDirection( movingInImage->GetDirection() );
invconverter->SetTransform( identityIOTransform );
invconverter->Update();
displacementinv = invconverter->GetOutput();
}
// Get the number of iterations and use that information to specify the number of levels
std::vector<unsigned int> iterations =
parser->ConvertVector<unsigned int>( iterationsOption->GetFunction( currentStage )->GetName() );
unsigned int numberOfLevels = iterations.size();
if ( verbose ) std::cout << " number of levels = " << numberOfLevels << std::endl;
// Get shrink factors
std::vector<unsigned int> factors =
parser->ConvertVector<unsigned int>( shrinkFactorsOption->GetFunction( currentStage )->GetName() );
typename AffineRegistrationType::ShrinkFactorsArrayType shrinkFactorsPerLevel;
shrinkFactorsPerLevel.SetSize( factors.size() );
if( factors.size() != numberOfLevels )
{
std::cerr << "ERROR: The number of shrink factors does not match the number of levels." << std::endl;
return EXIT_FAILURE;
}
else
{
for( unsigned int n = 0; n < shrinkFactorsPerLevel.Size(); n++ )
{
shrinkFactorsPerLevel[n] = factors[n];
}
if ( verbose ) std::cout << " shrink factors per level: " << shrinkFactorsPerLevel << std::endl;
}
// Get smoothing sigmas
std::vector<float> sigmas = parser->ConvertVector<float>( smoothingSigmasOption->GetFunction(
currentStage )->GetName() );
typename AffineRegistrationType::SmoothingSigmasArrayType smoothingSigmasPerLevel;
smoothingSigmasPerLevel.SetSize( sigmas.size() );
if( sigmas.size() != numberOfLevels )
{
std::cerr << "ERROR: The number of smoothing sigmas does not match the number of levels." << std::endl;
return EXIT_FAILURE;
}
else
{
for( unsigned int n = 0; n < smoothingSigmasPerLevel.Size(); n++ )
{
smoothingSigmasPerLevel[n] = sigmas[n];
}
if ( verbose ) std::cout << " smoothing sigmas per level: " << smoothingSigmasPerLevel << std::endl;
}
// the fixed image is a reference image in 3D while the moving is a 4D image
// loop over every time point and register image_i+1 to image_i
//
// Set up the image metric and scales estimator
std::vector<unsigned int> timelist;
std::vector<double> metriclist;
for( unsigned int timedim = 0; timedim < timedims; timedim++ )
{
timelist.push_back(timedim);
}
for( unsigned int timedim = 0; timedim < timedims; timedim++ )
{
typename CompositeTransformType::Pointer compositeTransform = nullptr;
if( currentStage == static_cast<int>(numberOfStages) - 1 )
{
compositeTransform = CompositeTransformType::New();
CompositeTransformVector.push_back(compositeTransform);
}
else if( CompositeTransformVector.size() == timedims && !CompositeTransformVector[timedim].IsNull() )
{
compositeTransform = CompositeTransformVector[timedim];
if( timedim == 0 )
{
if ( verbose ) std::cout << " use existing transform " << compositeTransform->GetParameters() << std::endl;
}
}
typedef itk::IdentityTransform<RealType, ImageDimension> IdentityTransformType;
typename IdentityTransformType::Pointer identityTransform = IdentityTransformType::New();
//
typedef itk::ExtractImageFilter<MovingImageType, FixedImageType> ExtractFilterType;
typename MovingImageType::RegionType extractRegion = movingImage->GetLargestPossibleRegion();
extractRegion.SetSize(ImageDimension, 0);
bool maptoneighbor = true;
typename OptionType::Pointer fixedOption =
parser->GetOption( "useFixedReferenceImage" );
if( fixedOption && fixedOption->GetNumberOfFunctions() )
{
std::string fixedFunction = fixedOption->GetFunction( 0 )->GetName();
ConvertToLowerCase( fixedFunction );
if( fixedFunction.compare( "1" ) == 0 || fixedFunction.compare( "true" ) == 0 )
{
if( timedim == 0 )
{
if ( verbose ) std::cout << " using fixed reference image for all frames " << std::endl;
}
fixed_time_slice = fixedImage;
extractRegion.SetIndex(ImageDimension, timedim );
typename ExtractFilterType::Pointer extractFilter2 = ExtractFilterType::New();
extractFilter2->SetInput( movingImage );
extractFilter2->SetDirectionCollapseToSubmatrix();
if( ImageDimension == 2 )
{
extractFilter2->SetDirectionCollapseToIdentity();
}
extractFilter2->SetExtractionRegion( extractRegion );
extractFilter2->Update();
moving_time_slice = extractFilter2->GetOutput();
maptoneighbor = false;
}
}
if( maptoneighbor )
{
extractRegion.SetIndex(ImageDimension, timedim );
typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
extractFilter->SetInput( movingImage );
extractFilter->SetDirectionCollapseToSubmatrix();
if( ImageDimension == 2 )
{
extractFilter->SetDirectionCollapseToIdentity();
}
extractFilter->SetExtractionRegion( extractRegion );
extractFilter->Update();
fixed_time_slice = extractFilter->GetOutput();
unsigned int td = timedim + 1;
if( td > timedims - 1 )
{
td = timedims - 1;
}
extractRegion.SetIndex(ImageDimension, td );
typename ExtractFilterType::Pointer extractFilter2 = ExtractFilterType::New();
extractFilter2->SetInput( movingImage );
extractFilter2->SetDirectionCollapseToSubmatrix();
if( ImageDimension == 2 )
{
extractFilter->SetDirectionCollapseToIdentity();
}
extractFilter2->SetExtractionRegion( extractRegion );
extractFilter2->Update();
moving_time_slice = extractFilter2->GetOutput();
}
typename FixedImageType::Pointer preprocessFixedImage =
PreprocessImage<FixedImageType>( fixed_time_slice, 0,
1, 0.001, 0.999,
nullptr );
typename FixedImageType::Pointer histogramMatchRef = nullptr;
if ( doHistogramMatch )
{
histogramMatchRef = preprocessFixedImage;
}
if ( verbose ) std::cout << " use histogram matching " << doHistogramMatch << std::endl;
typename FixedImageType::Pointer preprocessMovingImage =
PreprocessImage<FixedImageType>( moving_time_slice,
0, 1,
0.001, 0.999,
histogramMatchRef );
typedef itk::ImageToImageMetricv4<FixedImageType, FixedImageType> MetricType;
typename MetricType::Pointer metric;
std::string whichMetric = metricOption->GetFunction( currentStage )->GetName();
ConvertToLowerCase( whichMetric );
float samplingPercentage = 1.0;
if( metricOption->GetFunction( 0 )->GetNumberOfParameters() > 5 )
{
samplingPercentage = parser->Convert<float>( metricOption->GetFunction( currentStage )->GetParameter( 5 ) );
}
std::string samplingStrategy = "";
if( metricOption->GetFunction( 0 )->GetNumberOfParameters() > 4 )
{
samplingStrategy = metricOption->GetFunction( currentStage )->GetParameter( 4 );
}
ConvertToLowerCase( samplingStrategy );
typename AffineRegistrationType::MetricSamplingStrategyType metricSamplingStrategy = AffineRegistrationType::NONE;
if( std::strcmp( samplingStrategy.c_str(), "random" ) == 0 )
{
if( timedim == 0 )
{
if ( verbose ) std::cout << " random sampling (percentage = " << samplingPercentage << ")" << std::endl;
}
metricSamplingStrategy = AffineRegistrationType::RANDOM;
}
if( std::strcmp( samplingStrategy.c_str(), "regular" ) == 0 )
{
if( timedim == 0 )
{
if ( verbose ) std::cout << " regular sampling (percentage = " << samplingPercentage << ")" << std::endl;
}
metricSamplingStrategy = AffineRegistrationType::REGULAR;
}
if( std::strcmp( whichMetric.c_str(), "cc" ) == 0 )
{
unsigned int radiusOption = parser->Convert<unsigned int>( metricOption->GetFunction( currentStage )->GetParameter( 3 ) );
if( timedim == 0 )
{
if ( verbose ) std::cout << " using the CC metric (radius = " << radiusOption << ")." << std::endl;
}
typedef itk::ANTSNeighborhoodCorrelationImageToImageMetricv4<FixedImageType,
FixedImageType> CorrelationMetricType;
typename CorrelationMetricType::Pointer correlationMetric = CorrelationMetricType::New();
typename CorrelationMetricType::RadiusType radius;
radius.Fill( radiusOption );
correlationMetric->SetRadius( radius );
correlationMetric->SetUseMovingImageGradientFilter( false );
correlationMetric->SetUseFixedImageGradientFilter( false );
metric = correlationMetric;
}
else if( std::strcmp( whichMetric.c_str(), "mi" ) == 0 )
{
unsigned int binOption =
parser->Convert<unsigned int>( metricOption->GetFunction( currentStage )->GetParameter( 3 ) );
if( timedim == 0 )
{
if ( verbose ) std::cout << " using the Mattes MI metric." << std::endl;
}
typedef itk::MattesMutualInformationImageToImageMetricv4<FixedImageType,
FixedImageType> MutualInformationMetricType;
typename MutualInformationMetricType::Pointer mutualInformationMetric = MutualInformationMetricType::New();
mutualInformationMetric = mutualInformationMetric;
mutualInformationMetric->SetNumberOfHistogramBins( binOption );
mutualInformationMetric->SetUseMovingImageGradientFilter( false );
mutualInformationMetric->SetUseFixedImageGradientFilter( false );
metric = mutualInformationMetric;
}
else if( std::strcmp( whichMetric.c_str(), "demons" ) == 0 )
{
if( timedim == 0 )
{
if ( verbose ) std::cout << " using the Demons metric." << std::endl;
}
typedef itk::MeanSquaresImageToImageMetricv4<FixedImageType, FixedImageType> DemonsMetricType;
typename DemonsMetricType::Pointer demonsMetric = DemonsMetricType::New();
demonsMetric = demonsMetric;
metric = demonsMetric;
}
else if( std::strcmp( whichMetric.c_str(), "gc" ) == 0 )
{
if( timedim == 0 )
{
if ( verbose ) std::cout << " using the global correlation metric." << std::endl;
}
typedef itk::CorrelationImageToImageMetricv4<FixedImageType, FixedImageType> corrMetricType;
typename corrMetricType::Pointer corrMetric = corrMetricType::New();
metric = corrMetric;
if ( verbose ) std::cout << " global corr metric set " << std::endl;
}
else
{
std::cerr << "ERROR: Unrecognized image metric: " << whichMetric << std::endl;
return EXIT_FAILURE;
}
metric->SetVirtualDomainFromImage( fixed_time_slice );
typedef itk::RegistrationParameterScalesFromPhysicalShift<MetricType> ScalesEstimatorType;
typename ScalesEstimatorType::Pointer scalesEstimator = ScalesEstimatorType::New();
scalesEstimator->SetMetric( metric );
scalesEstimator->SetTransformForward( true );
float learningRate = parser->Convert<float>( transformOption->GetFunction( currentStage )->GetParameter( 0 ) );
typedef itk::ConjugateGradientLineSearchOptimizerv4 OptimizerType;
OptimizerType::Pointer optimizer = OptimizerType::New();
optimizer->SetNumberOfIterations( iterations[0] );
optimizer->SetMinimumConvergenceValue( 1.e-7 );
optimizer->SetConvergenceWindowSize( 10 );
optimizer->SetLowerLimit( 0 );
optimizer->SetUpperLimit( 2 );
optimizer->SetEpsilon( 0.1 );
typename OptionType::Pointer scalesOption = parser->GetOption( "useScalesEstimator" );
if( scalesOption && scalesOption->GetNumberOfFunctions() )
{
std::string scalesFunction = scalesOption->GetFunction( 0 )->GetName();