-
Notifications
You must be signed in to change notification settings - Fork 116
/
elxTransformBase.hxx
1514 lines (1239 loc) · 53.9 KB
/
elxTransformBase.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 UMC Utrecht and contributors
*
* 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.
*
*=========================================================================*/
#ifndef elxTransformBase_hxx
#define elxTransformBase_hxx
#include "elxTransformBase.h"
#include "elxConversion.h"
#include "elxDeref.h"
#include "elxElastixMain.h"
#include "elxTransformIO.h"
#include "itkPointSet.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkTransformixInputPointFileReader.h"
#include <itksys/SystemTools.hxx>
#include "itkVector.h"
#include "itkTransformToDisplacementFieldFilter.h"
#include "itkTransformToDeterminantOfSpatialJacobianSource.h"
#include "itkTransformToSpatialJacobianSource.h"
#include "itkImageFileWriter.h"
#include "itkImageGridSampler.h"
#include "itkContinuousIndex.h"
#include "itkChangeInformationImageFilter.h"
#include "itkMesh.h"
#include "itkMeshFileReader.h"
#include "itkMeshFileWriter.h"
#include "itkCommonEnums.h"
#include <cassert>
#include <fstream>
#include <iomanip> // For setprecision.
namespace elastix
{
/**
* ******************** BeforeAllBase ***************************
*/
template <class TElastix>
int
TransformBase<TElastix>::BeforeAllBase()
{
const Configuration & configuration = Deref(Superclass::GetConfiguration());
/** Check Command line options and print them to the logfile. */
log::info("Command line options from TransformBase:");
std::string check("");
/** Check for appearance of "-t0". */
check = configuration.GetCommandLineArgument("-t0");
if (check.empty())
{
log::info("-t0 unspecified, so no initial transform used");
}
else
{
log::info(std::ostringstream{} << "-t0 " << check);
}
/** Return a value. */
return 0;
} // end BeforeAllBase()
/**
* ******************** BeforeAllTransformix ********************
*/
template <class TElastix>
int
TransformBase<TElastix>::BeforeAllTransformix()
{
const Configuration & configuration = Deref(Superclass::GetConfiguration());
/** Declare the return value and initialize it. */
int returndummy = 0;
/** Declare check. */
std::string check = "";
/** Check for appearance of "-ipp". */
check = configuration.GetCommandLineArgument("-ipp");
if (!check.empty())
{
log::info(std::ostringstream{} << "-ipp " << check);
// Deprecated since elastix 4.3
log::warn(std::ostringstream{} << "WARNING: \"-ipp\" is deprecated, use \"-def\" instead!");
}
/** Check for appearance of "-def". */
check = configuration.GetCommandLineArgument("-def");
if (check.empty())
{
log::info("-def unspecified, so no input points transformed");
}
else
{
log::info(std::ostringstream{} << "-def " << check);
}
/** Check for appearance of "-jac". */
check = configuration.GetCommandLineArgument("-jac");
if (check.empty())
{
log::info("-jac unspecified, so no det(dT/dx) computed");
}
else
{
log::info(std::ostringstream{} << "-jac " << check);
}
/** Check for appearance of "-jacmat". */
check = configuration.GetCommandLineArgument("-jacmat");
if (check.empty())
{
log::info("-jacmat unspecified, so no dT/dx computed");
}
else
{
log::info(std::ostringstream{} << "-jacmat " << check);
}
/** Return a value. */
return returndummy;
} // end BeforeAllTransformix()
/**
* ******************* BeforeRegistrationBase *******************
*/
template <class TElastix>
void
TransformBase<TElastix>::BeforeRegistrationBase()
{
const Configuration & configuration = Deref(Superclass::GetConfiguration());
/** Read from the configuration file how to combine the initial
* transform with the current transform.
*/
std::string howToCombineTransforms = "Compose";
configuration.ReadParameter(howToCombineTransforms, "HowToCombineTransforms", 0, false);
this->GetAsITKBaseType()->SetUseComposition(howToCombineTransforms == "Compose");
/** Set the initial transform. Elastix returns an itk::Object, so try to
* cast it to an InitialTransformType, which is of type itk::Transform.
* No need to cast to InitialAdvancedTransformType, since InitialAdvancedTransformType
* inherits from InitialTransformType.
*/
if (itk::Object * const object = this->m_Elastix->GetInitialTransform())
{
if (auto * const initialTransform = dynamic_cast<InitialTransformType *>(object))
{
this->SetInitialTransform(initialTransform);
}
}
else
{
std::string fileName = configuration.GetCommandLineArgument("-t0");
if (fileName.empty())
{
const ElastixBase & elastixBase = Deref(Superclass::GetElastix());
const auto numberOfConfigurations = elastixBase.GetNumberOfTransformConfigurations();
if ((numberOfConfigurations > 0) && (&configuration != elastixBase.GetTransformConfiguration(0)))
{
const Configuration::ConstPointer previousTransformConfiguration =
elastixBase.GetPreviousTransformConfiguration(configuration);
const Configuration::ConstPointer lastTransformConfiguration =
elastixBase.GetTransformConfiguration(numberOfConfigurations - 1);
this->ReadInitialTransformFromConfiguration(previousTransformConfiguration ? previousTransformConfiguration
: lastTransformConfiguration);
}
}
else
{
if (itksys::SystemTools::FileExists(fileName))
{
this->ReadInitialTransformFromFile(fileName);
}
else
{
itkExceptionMacro("ERROR: the file " << fileName << " does not exist!");
}
}
}
} // end BeforeRegistrationBase()
/**
* ******************* GetInitialTransform **********************
*/
template <class TElastix>
auto
TransformBase<TElastix>::GetInitialTransform() const -> const InitialTransformType *
{
return this->GetAsITKBaseType()->GetInitialTransform();
} // end GetInitialTransform()
/**
* ******************* SetInitialTransform **********************
*/
template <class TElastix>
void
TransformBase<TElastix>::SetInitialTransform(InitialTransformType * _arg)
{
/** Set initial transform. */
this->GetAsITKBaseType()->SetInitialTransform(_arg);
// \todo AdvancedCombinationTransformType
} // end SetInitialTransform()
/**
* ******************* SetFinalParameters ********************
*/
template <class TElastix>
void
TransformBase<TElastix>::SetFinalParameters()
{
/** Make a local copy, since some transforms do not do this,
* like the B-spline transform.
*/
this->m_FinalParameters = this->GetElastix()->GetElxOptimizerBase()->GetAsITKBaseType()->GetCurrentPosition();
/** Set the final Parameters for the resampler. */
this->GetAsITKBaseType()->SetParameters(this->m_FinalParameters);
} // end SetFinalParameters()
/**
* ******************* AfterRegistrationBase ********************
*/
template <class TElastix>
void
TransformBase<TElastix>::AfterRegistrationBase()
{
/** Set the final Parameters. */
this->SetFinalParameters();
} // end AfterRegistrationBase()
/**
* ******************* ReadFromFile *****************************
*/
template <class TElastix>
void
TransformBase<TElastix>::ReadFromFile()
{
/** NOTE:
* This method assumes the configuration is initialized with a
* transform parameter file, so not an elastix parameter file!!
*/
const Configuration & configuration = Deref(Superclass::GetConfiguration());
/** Task 1 - Read the parameters from file. */
/** Read the TransformParameters. */
if (this->m_ReadWriteTransformParameters)
{
const auto itkParameterValues = configuration.RetrieveValuesOfParameter<double>("ITKTransformParameters");
if (itkParameterValues == nullptr)
{
/** Get the number of TransformParameters. */
unsigned int numberOfParameters = 0;
configuration.ReadParameter(numberOfParameters, "NumberOfParameters", 0);
/** Read the TransformParameters. */
std::vector<ValueType> vecPar(numberOfParameters);
configuration.ReadParameter(vecPar, "TransformParameters", 0, numberOfParameters - 1, true);
/** Do not rely on vecPar.size(), since it is unchanged by ReadParameter(). */
const std::size_t numberOfParametersFound = configuration.CountNumberOfParameterEntries("TransformParameters");
/** Sanity check. Are the number of found parameters the same as
* the number of specified parameters?
*/
if (numberOfParametersFound != numberOfParameters)
{
itkExceptionMacro("\nERROR: Invalid transform parameter file!\n"
<< "The number of parameters in \"TransformParameters\" is " << numberOfParametersFound
<< ", which does not match the number specified in \"NumberOfParameters\" ("
<< numberOfParameters << ").\n"
<< "The transform parameters should be specified as:\n"
<< " (TransformParameters num num ... num)\n"
<< "with " << numberOfParameters << " parameters.\n");
}
/** Copy to m_TransformParameters. */
// NOTE: we could avoid this by directly reading into the transform parameters,
// e.g. by overloading ReadParameter(), or use swap (?).
m_TransformParameters = Conversion::ToOptimizerParameters(vecPar);
}
else
{
m_TransformParameters = Conversion::ToOptimizerParameters(*itkParameterValues);
const auto itkFixedParameterValues =
configuration.RetrieveValuesOfParameter<double>("ITKTransformFixedParameters");
if (itkFixedParameterValues != nullptr)
{
GetSelf().SetFixedParameters(Conversion::ToOptimizerParameters(*itkFixedParameterValues));
}
}
/** Set the parameters into this transform. */
this->GetAsITKBaseType()->SetParameters(m_TransformParameters);
} // end if this->m_ReadWriteTransformParameters
/** Task 2 - Get the InitialTransform. */
const ElastixBase & elastixBase = Deref(Superclass::GetElastix());
if (elastixBase.GetNumberOfTransformConfigurations() > 1)
{
const Configuration::ConstPointer previousTransformConfiguration =
elastixBase.GetPreviousTransformConfiguration(configuration);
if (previousTransformConfiguration)
{
this->ReadInitialTransformFromConfiguration(previousTransformConfiguration);
}
}
else
{
/** Get the name of the parameter file that specifies the initial transform. */
// Retrieve the parameter by its current (preferred) parameter name:
const auto initialTransformParameterFileName =
configuration.RetrieveParameterStringValue({}, "InitialTransformParameterFileName", 0, false);
// Retrieve the parameter by its old (deprecated) parameter name as well:
const auto initialTransformParametersFileName =
configuration.RetrieveParameterStringValue({}, "InitialTransformParametersFileName", 0, false);
if (!initialTransformParametersFileName.empty())
{
log::warn("WARNING: The parameter name \"InitialTransformParametersFileName\" is deprecated. Please use "
"\"InitialTransformParameterFileName\" (without letter 's') instead.");
}
// Prefer the value from the current parameter name, otherwise use the old parameter name.
const auto & fileName = initialTransformParameterFileName.empty() ? initialTransformParametersFileName
: initialTransformParameterFileName;
/** Call the function ReadInitialTransformFromFile. */
if (!fileName.empty() && fileName != "NoInitialTransform")
{
/** Check if the initial transform of this transform parameter file
* is not the same as this transform parameter file. Otherwise,
* we will have an infinite loop.
*/
const std::string configurationParameterFileName = configuration.GetParameterFileName();
if (itksys::SystemTools::CollapseFullPath(fileName) ==
itksys::SystemTools::CollapseFullPath(configurationParameterFileName))
{
itkExceptionMacro("ERROR: The InitialTransformParameterFileName is identical to the current "
"TransformParameters filename! An infinite loop is not allowed.");
}
/** We can safely read the initial transform. */
// Find the last separator (slash or backslash) in the current transform parameter file path.
const auto lastConfigurationParameterFilePathSeparator = configurationParameterFileName.find_last_of("\\/");
const char firstFileNameLetter = fileName.front();
if (const bool isAbsoluteFilePath{ firstFileNameLetter == '\\' || firstFileNameLetter == '/' ||
(firstFileNameLetter > 0 && std::isalpha(firstFileNameLetter) &&
fileName.size() > 1 && fileName[1] == ':') };
isAbsoluteFilePath || (lastConfigurationParameterFilePathSeparator == std::string::npos) ||
itksys::SystemTools::FileExists(fileName))
{
// The file name is an absolute path, or the current transform parameter file name does not have any separator,
// or the file exists in the current working directory. So use it!
this->ReadInitialTransformFromFile(fileName);
}
else
{
// The file name of the initial transform is a relative path, so now assume that it is relative to the current
// transform parameter file (the current configuration). Try to read the initial transform from the same
// directory as the current transform, by concatenating the current configuration file path up to that last
// separator with the string specified by "InitialTransformParameterFileName".
this->ReadInitialTransformFromFile(
configurationParameterFileName.substr(0, lastConfigurationParameterFilePathSeparator + 1) + fileName);
}
}
}
/** Task 3 - Read from the configuration file how to combine the
* initial transform with the current transform.
*/
std::string howToCombineTransforms = "Compose"; // default
configuration.ReadParameter(howToCombineTransforms, "HowToCombineTransforms", 0, true);
/** Convert 'this' to a pointer to a CombinationTransform and set how
* to combine the current transform with the initial transform.
*/
this->GetAsITKBaseType()->SetUseComposition(howToCombineTransforms == "Compose");
/** Task 4 - Remember the name of the TransformParameterFileName.
* This will be needed when another transform will use this transform as an initial transform (see the WriteToFile
* method), which is relevant for transformix, as well as for elastix (specifically
* ElastixRegistrationMethod::GenerateData(), when InitialTransformParameterObject is specified).
*/
this->SetTransformParameterFileName(configuration.GetCommandLineArgument("-tp"));
} // end ReadFromFile()
/**
* ******************* ReadInitialTransformFromFile *************
*/
template <class TElastix>
void
TransformBase<TElastix>::ReadInitialTransformFromFile(const std::string & transformParameterFileName)
{
/** Create a new configuration, which will be initialized with
* the transformParameterFileName. */
const auto configurationInitialTransform = Configuration::New();
if (configurationInitialTransform->Initialize({ { "-tp", transformParameterFileName } }) != 0)
{
itkGenericExceptionMacro("ERROR: Reading initial transform parameters failed: " << transformParameterFileName);
}
this->ReadInitialTransformFromConfiguration(configurationInitialTransform);
} // end ReadInitialTransformFromFile()
/**
* ******************* ReadInitialTransformFromConfiguration *****************************
*/
template <class TElastix>
void
TransformBase<TElastix>::ReadInitialTransformFromConfiguration(
const Configuration::ConstPointer configurationInitialTransform)
{
/** Read the InitialTransform name. */
ComponentDescriptionType initialTransformName = "AffineTransform";
configurationInitialTransform->ReadParameter(initialTransformName, "Transform", 0);
/** Create an InitialTransform. */
const PtrToCreator testcreator =
ElastixMain::GetComponentDatabase().GetCreator(initialTransformName, this->m_Elastix->GetDBIndex());
const itk::Object::Pointer initialTransform = (testcreator == nullptr) ? nullptr : testcreator();
const auto elx_initialTransform = dynamic_cast<Self *>(initialTransform.GetPointer());
/** Call the ReadFromFile method of the initialTransform. */
if (elx_initialTransform != nullptr)
{
// elx_initialTransform->SetTransformParameterFileName(transformParameterFileName);
elx_initialTransform->SetElastix(this->GetElastix());
elx_initialTransform->SetConfiguration(configurationInitialTransform);
elx_initialTransform->ReadFromFile();
/** Set initial transform. */
const auto testPointer = dynamic_cast<InitialTransformType *>(initialTransform.GetPointer());
if (testPointer != nullptr)
{
this->SetInitialTransform(testPointer);
}
}
} // end ReadInitialTransformFromConfiguration()
/**
* ******************* WriteToFile ******************************
*/
template <class TElastix>
void
TransformBase<TElastix>::WriteToFile(std::ostream & transformationParameterInfo, const ParametersType & param) const
{
const Configuration & configuration = Deref(Superclass::GetConfiguration());
const auto itkTransformOutputFileNameExtensions =
configuration.GetValuesOfParameter("ITKTransformOutputFileNameExtension");
const std::string itkTransformOutputFileNameExtension =
itkTransformOutputFileNameExtensions.empty() ? "" : itkTransformOutputFileNameExtensions.front();
ParameterMapType parameterMap;
this->CreateTransformParameterMap(param, parameterMap, itkTransformOutputFileNameExtension.empty());
const auto & self = GetSelf();
if (!itkTransformOutputFileNameExtension.empty())
{
const auto firstSingleTransform = self.GetNthTransform(0);
if (firstSingleTransform != nullptr)
{
const std::string transformFileName =
std::string(m_TransformParameterFileName, 0, m_TransformParameterFileName.rfind('.')) + '.' +
itkTransformOutputFileNameExtension;
const itk::TransformBase::ConstPointer itkTransform =
TransformIO::ConvertToSingleItkTransform(*firstSingleTransform);
TransformIO::Write((itkTransform == nullptr) ? *firstSingleTransform : *itkTransform, transformFileName);
parameterMap.erase("TransformParameters");
parameterMap["Transform"] = { "File" };
parameterMap["TransformFileName"] = { transformFileName };
}
}
const auto writeCompositeTransform = configuration.RetrieveValuesOfParameter<bool>("WriteITKCompositeTransform");
if ((writeCompositeTransform != nullptr) && (*writeCompositeTransform == std::vector<bool>{ true }) &&
!itkTransformOutputFileNameExtension.empty())
{
const auto compositeTransform = TransformIO::ConvertToItkCompositeTransform(self);
if (compositeTransform == nullptr)
{
log::error(std::ostringstream{}
<< "Failed to convert a combination of transform to an ITK CompositeTransform. Please check "
"that the combination does use composition");
}
else
{
TransformIO::Write(*compositeTransform,
std::string(m_TransformParameterFileName, 0, m_TransformParameterFileName.rfind('.')) +
"-Composite." + itkTransformOutputFileNameExtension);
}
}
transformationParameterInfo << Conversion::ParameterMapToString(parameterMap);
WriteDerivedTransformDataToFile();
} // end WriteToFile()
/**
* ******************* CreateTransformParameterMap ******************************
*/
template <class TElastix>
void
TransformBase<TElastix>::CreateTransformParameterMap(const ParametersType & param,
ParameterMapType & parameterMap,
const bool includeDerivedTransformParameters) const
{
const Configuration & configuration = Deref(Superclass::GetConfiguration());
const auto & elastixObject = *(this->GetElastix());
/** The way Transforms are combined. */
const auto combinationMethod = this->GetAsITKBaseType()->GetUseAddition() ? "Add" : "Compose";
/** Write image pixel types. */
std::string fixpix = "float";
std::string movpix = "float";
configuration.ReadParameter(fixpix, "FixedInternalImagePixelType", 0);
configuration.ReadParameter(movpix, "MovingInternalImagePixelType", 0);
/** Get the Size, Spacing and Origin of the fixed image. */
const auto & fixedImage = *(this->m_Elastix->GetFixedImage());
const auto & largestPossibleRegion = fixedImage.GetLargestPossibleRegion();
/** The following line would be logically: */
// auto direction = this->m_Elastix->GetFixedImage()->GetDirection();
/** But to support the UseDirectionCosines option, we should do it like this: */
typename FixedImageType::DirectionType direction;
elastixObject.GetOriginalFixedImageDirection(direction);
/** Write the name of this transform. */
parameterMap = { { "Transform", { this->elxGetClassName() } },
{ "NumberOfParameters", { Conversion::ToString(param.GetSize()) } },
{ "InitialTransformParameterFileName", { this->GetInitialTransformParameterFileName() } },
{ "HowToCombineTransforms", { combinationMethod } },
{ "FixedImageDimension", { Conversion::ToString(FixedImageDimension) } },
{ "MovingImageDimension", { Conversion::ToString(MovingImageDimension) } },
{ "FixedInternalImagePixelType", { fixpix } },
{ "MovingInternalImagePixelType", { movpix } },
{ "Size", Conversion::ToVectorOfStrings(largestPossibleRegion.GetSize()) },
{ "Index", Conversion::ToVectorOfStrings(largestPossibleRegion.GetIndex()) },
{ "Spacing", Conversion::ToVectorOfStrings(fixedImage.GetSpacing()) },
{ "Origin", Conversion::ToVectorOfStrings(fixedImage.GetOrigin()) },
{ "Direction", Conversion::ToVectorOfStrings(direction) },
{ "UseDirectionCosines", { Conversion::ToString(elastixObject.GetUseDirectionCosines()) } } };
/** Write the parameters of this transform. */
if (this->m_ReadWriteTransformParameters)
{
/** In this case, write in a normal way to the parameter file. */
parameterMap["TransformParameters"] = { Conversion::ToVectorOfStrings(param) };
}
if (includeDerivedTransformParameters)
{
// Derived transform classes may add some extra parameters
for (auto & keyAndValue : this->CreateDerivedTransformParameterMap())
{
const auto & key = keyAndValue.first;
assert(parameterMap.count(key) == 0);
parameterMap[key] = std::move(keyAndValue.second);
}
}
} // end CreateTransformParameterMap()
/**
* ******************* TransformPoints **************************
*
* This function reads points from a file (but only if requested)
* and transforms these fixed-image coordinates to moving-image
* coordinates.
*/
template <class TElastix>
void
TransformBase<TElastix>::TransformPoints() const
{
const Configuration & configuration = Deref(Superclass::GetConfiguration());
/** If the optional command "-def" is given in the command
* line arguments, then and only then we continue.
*/
const std::string ipp = configuration.GetCommandLineArgument("-ipp");
std::string def = configuration.GetCommandLineArgument("-def");
/** For backwards compatibility def = ipp. */
if (!def.empty() && !ipp.empty())
{
itkExceptionMacro("ERROR: Can not use both \"-def\" and \"-ipp\"!\n"
<< " \"-ipp\" is deprecated, use only \"-def\".\n");
}
else if (def.empty() && !ipp.empty())
{
def = ipp;
}
/** If there is an input point-file? */
if (!def.empty() && def != "all")
{
if (itksys::SystemTools::StringEndsWith(def, ".vtk") || itksys::SystemTools::StringEndsWith(def, ".VTK"))
{
log::info(" The transform is evaluated on some points, specified in a VTK input point file.");
this->TransformPointsSomePointsVTK(def);
}
else
{
log::info(" The transform is evaluated on some points, specified in the input point file.");
this->TransformPointsSomePoints(def);
}
}
else if (def == "all")
{
log::info(" The transform is evaluated on all points. The result is a deformation field.");
this->TransformPointsAllPoints();
}
else
{
// just a message
log::info(std::ostringstream{} << " The command-line option \"-def\" is not used, so no points are transformed");
}
} // end TransformPoints()
/**
* ************** TransformPointsSomePoints *********************
*
* This function reads points from a file and transforms
* these fixed-image coordinates to moving-image
* coordinates.
*
* Reads the inputpoints from a text file, either as index or as point.
* Computes the transformed points, converts them back to an index and compute
* the deformation vector as the difference between the outputpoint and
* the input point. Save the results.
*/
template <class TElastix>
void
TransformBase<TElastix>::TransformPointsSomePoints(const std::string & filename) const
{
/** Typedef's. */
using FixedImageRegionType = typename FixedImageType::RegionType;
using FixedImageIndexType = typename FixedImageType::IndexType;
using FixedImageIndexValueType = typename FixedImageIndexType::IndexValueType;
using MovingImageIndexType = typename MovingImageType::IndexType;
using MovingImageIndexValueType = typename MovingImageIndexType::IndexValueType;
using DummyIPPPixelType = unsigned char;
using MeshTraitsType =
itk::DefaultStaticMeshTraits<DummyIPPPixelType, FixedImageDimension, FixedImageDimension, CoordRepType>;
using PointSetType = itk::PointSet<DummyIPPPixelType, FixedImageDimension, MeshTraitsType>;
using DeformationVectorType = itk::Vector<float, FixedImageDimension>;
/** Construct an ipp-file reader. */
const auto ippReader = itk::TransformixInputPointFileReader<PointSetType>::New();
ippReader->SetFileName(filename);
/** Read the input points. */
log::info(std::ostringstream{} << " Reading input point file: " << filename);
try
{
ippReader->Update();
}
catch (const itk::ExceptionObject & err)
{
log::error(std::ostringstream{} << " Error while opening input point file.\n" << err);
}
/** Some user-feedback. */
if (ippReader->GetPointsAreIndices())
{
log::info(" Input points are specified as image indices.");
}
else
{
log::info(" Input points are specified in world coordinates.");
}
const unsigned int nrofpoints = ippReader->GetNumberOfPoints();
log::info(std::ostringstream{} << " Number of specified input points: " << nrofpoints);
/** Get the set of input points. */
typename PointSetType::Pointer inputPointSet = ippReader->GetOutput();
/** Create the storage classes. */
std::vector<FixedImageIndexType> inputindexvec(nrofpoints);
std::vector<InputPointType> inputpointvec(nrofpoints);
std::vector<OutputPointType> outputpointvec(nrofpoints);
std::vector<FixedImageIndexType> outputindexfixedvec(nrofpoints);
std::vector<MovingImageIndexType> outputindexmovingvec(nrofpoints);
std::vector<DeformationVectorType> deformationvec(nrofpoints);
const auto & resampleImageFilter = *(this->m_Elastix->GetElxResamplerBase()->GetAsITKBaseType());
/** Make a temporary image with the right region info,
* which we can use to convert between points and indices.
* By taking the image from the resampler output, the UseDirectionCosines
* parameter is automatically taken into account. */
const auto dummyImage = FixedImageType::New();
dummyImage->SetRegions(
FixedImageRegionType(resampleImageFilter.GetOutputStartIndex(), resampleImageFilter.GetSize()));
dummyImage->SetOrigin(resampleImageFilter.GetOutputOrigin());
dummyImage->SetSpacing(resampleImageFilter.GetOutputSpacing());
dummyImage->SetDirection(resampleImageFilter.GetOutputDirection());
/** Also output moving image indices if a moving image was supplied. */
const typename MovingImageType::Pointer movingImage = this->GetElastix()->GetMovingImage();
const bool alsoMovingIndices = movingImage.IsNotNull();
/** Read the input points, as index or as point. */
if (ippReader->GetPointsAreIndices())
{
for (unsigned int j = 0; j < nrofpoints; ++j)
{
/** The read point from the inutPointSet is actually an index
* Cast to the proper type.
*/
InputPointType point{};
inputPointSet->GetPoint(j, &point);
for (unsigned int i = 0; i < FixedImageDimension; ++i)
{
inputindexvec[j][i] = static_cast<FixedImageIndexValueType>(itk::Math::Round<double>(point[i]));
}
/** Compute the input point in physical coordinates. */
dummyImage->TransformIndexToPhysicalPoint(inputindexvec[j], inputpointvec[j]);
}
}
else
{
for (unsigned int j = 0; j < nrofpoints; ++j)
{
/** Compute index of nearest voxel in fixed image. */
InputPointType point{};
inputPointSet->GetPoint(j, &point);
inputpointvec[j] = point;
const auto fixedcindex = dummyImage->template TransformPhysicalPointToContinuousIndex<double>(point);
for (unsigned int i = 0; i < FixedImageDimension; ++i)
{
inputindexvec[j][i] = static_cast<FixedImageIndexValueType>(itk::Math::Round<double>(fixedcindex[i]));
}
}
}
/** Apply the transform. */
log::info(" The input points are transformed.");
for (unsigned int j = 0; j < nrofpoints; ++j)
{
/** Call TransformPoint. */
outputpointvec[j] = this->GetAsITKBaseType()->TransformPoint(inputpointvec[j]);
/** Transform back to index in fixed image domain. */
const auto fixedcindex = dummyImage->template TransformPhysicalPointToContinuousIndex<double>(outputpointvec[j]);
for (unsigned int i = 0; i < FixedImageDimension; ++i)
{
outputindexfixedvec[j][i] = static_cast<FixedImageIndexValueType>(itk::Math::Round<double>(fixedcindex[i]));
}
if (alsoMovingIndices)
{
/** Transform back to index in moving image domain. */
const auto movingcindex =
movingImage->template TransformPhysicalPointToContinuousIndex<double>(outputpointvec[j]);
for (unsigned int i = 0; i < MovingImageDimension; ++i)
{
outputindexmovingvec[j][i] = static_cast<MovingImageIndexValueType>(itk::Math::Round<double>(movingcindex[i]));
}
}
/** Compute displacement. */
deformationvec[j].CastFrom(outputpointvec[j] - inputpointvec[j]);
}
const Configuration & configuration = Deref(Superclass::GetConfiguration());
if (const std::string outputDirectoryPath = configuration.GetCommandLineArgument("-out");
!outputDirectoryPath.empty())
{
/** Create filename and file stream. */
const std::string outputPointsFileName = outputDirectoryPath + "outputpoints.txt";
std::ofstream outputPointsFile(outputPointsFileName);
outputPointsFile << std::showpoint << std::fixed;
log::info(std::ostringstream{} << " The transformed points are saved in: " << outputPointsFileName);
const auto writeToFile = [&outputPointsFile](const auto & rangeOfElements) {
for (const auto element : rangeOfElements)
{
outputPointsFile << element << ' ';
}
};
/** Print the results. */
for (unsigned int j = 0; j < nrofpoints; ++j)
{
/** The input index. */
outputPointsFile << "Point\t" << j << "\t; InputIndex = [ ";
writeToFile(inputindexvec[j]);
/** The input point. */
outputPointsFile << "]\t; InputPoint = [ ";
writeToFile(inputpointvec[j]);
/** The output index in fixed image. */
outputPointsFile << "]\t; OutputIndexFixed = [ ";
writeToFile(outputindexfixedvec[j]);
/** The output point. */
outputPointsFile << "]\t; OutputPoint = [ ";
writeToFile(outputpointvec[j]);
/** The output point minus the input point. */
outputPointsFile << "]\t; Deformation = [ ";
writeToFile(deformationvec[j]);
if (alsoMovingIndices)
{
/** The output index in moving image. */
outputPointsFile << "]\t; OutputIndexMoving = [ ";
writeToFile(outputindexmovingvec[j]);
}
outputPointsFile << "]" << std::endl;
} // end for nrofpoints
}
} // end TransformPointsSomePoints()
/**
* ************** TransformPointsSomePointsVTK *********************
*
* This function reads points from a .vtk file and transforms
* these fixed-image coordinates to moving-image
* coordinates.
*
* Reads the inputmesh from a vtk file, assuming world coordinates.
* Computes the transformed points, save as outputpoints.vtk.
*/
template <class TElastix>
void
TransformBase<TElastix>::TransformPointsSomePointsVTK(const std::string & filename) const
{
/** Typedef's. \todo test DummyIPPPixelType=bool. */
using DummyIPPPixelType = float;
using MeshTraitsType =
itk::DefaultStaticMeshTraits<DummyIPPPixelType, FixedImageDimension, FixedImageDimension, CoordRepType>;
using MeshType = itk::Mesh<DummyIPPPixelType, FixedImageDimension, MeshTraitsType>;
/** Read the input points. */
const auto meshReader = itk::MeshFileReader<MeshType>::New();
meshReader->SetFileName(filename);
log::info(std::ostringstream{} << " Reading input point file: " << filename);
try
{
meshReader->Update();
}
catch (const itk::ExceptionObject & err)
{
log::error(std::ostringstream{} << " Error while opening input point file.\n" << err);
}
const auto & inputMesh = *(meshReader->GetOutput());
/** Some user-feedback. */
log::info(" Input points are specified in world coordinates.");
const unsigned long nrofpoints = inputMesh.GetNumberOfPoints();
log::info(std::ostringstream{} << " Number of specified input points: " << nrofpoints);
/** Apply the transform. */
log::info(" The input points are transformed.");
typename MeshType::ConstPointer outputMesh;
try
{
outputMesh = Self::TransformMesh(inputMesh);
}
catch (const itk::ExceptionObject & err)
{
log::error(std::ostringstream{} << " Error while transforming points.\n" << err);
}
const Configuration & configuration = Deref(Superclass::GetConfiguration());
if (const std::string outputDirectoryPath = configuration.GetCommandLineArgument("-out");
!outputDirectoryPath.empty())
{
/** Create filename and file stream. */
const std::string outputPointsFileName = configuration.GetCommandLineArgument("-out") + "outputpoints.vtk";
log::info(std::ostringstream{} << " The transformed points are saved in: " << outputPointsFileName);
try
{
itk::WriteMesh(outputMesh, outputPointsFileName);
}
catch (const itk::ExceptionObject & err)
{
log::error(std::ostringstream{} << " Error while saving points.\n" << err);
}
}
} // end TransformPointsSomePointsVTK()
/**
* ************** TransformPointsAllPoints **********************
*
* This function transforms all indexes to a physical point.
* The difference vector (= the deformation at that index) is
* stored in an image of vectors (of floats).
*/
template <class TElastix>
void
TransformBase<TElastix>::TransformPointsAllPoints() const