-
Notifications
You must be signed in to change notification settings - Fork 0
/
_gbe_3DRegistration.cpp
1495 lines (1309 loc) · 46.6 KB
/
_gbe_3DRegistration.cpp
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
#pragma once
#include "_gbe_3DRegistration.h"
/*Global Variables*/
std::string OutputTransformfilename = "3DRigidRegistrationTransform.txt";
std::string Iterationfilename = "3DRigidRegistrationIt.txt";
/*OBSERVER CLASSES*/
#include "itkCommand.h"
template <typename TRegistration>
class RegistrationInterfaceCommand : public itk::Command
{
public:
using Self = RegistrationInterfaceCommand;
using Superclass = itk::Command;
using Pointer = itk::SmartPointer<Self>;
itkNewMacro(Self);
protected:
RegistrationInterfaceCommand() = default;
public:
using RegistrationType = TRegistration;
using RegistrationPointer = RegistrationType * ;
//using OptimizerType = itk::RegularStepGradientDescentOptimizerv4<double>;
//typedef itk::PowellOptimizerv4<double> OptimizerType;
typedef itk::LBFGSOptimizerv4 OptimizerType;
using OptimizerPointer = OptimizerType * ;
void
Execute(itk::Object* object, const itk::EventObject& event) override
{
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// First we verify that the event invoked is of the right type,
// \code{itk::MultiResolutionIterationEvent()}.
// If not, we return without any further action.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
if (!(itk::MultiResolutionIterationEvent().CheckEvent(&event)))
{
return;
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We then convert the input object pointer to a RegistrationPointer.
// Note that no error checking is done here to verify the
// \code{dynamic\_cast} was successful since we know the actual object
// is a registration method. Then we ask for the optimizer object
// from the registration method.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
auto registration = static_cast<RegistrationPointer>(object);
auto optimizer =
static_cast<OptimizerPointer>(registration->GetModifiableOptimizer());
// Software Guide : EndCodeSnippet
unsigned int currentLevel = registration->GetCurrentLevel();
typename RegistrationType::ShrinkFactorsPerDimensionContainerType shrinkFactors =
registration->GetShrinkFactorsPerDimension(currentLevel);
typename RegistrationType::SmoothingSigmasArrayType smoothingSigmas =
registration->GetSmoothingSigmasPerLevel();
std::cout << "-------------------------------------" << std::endl;
std::cout << " Current level = " << currentLevel << std::endl;
std::cout << " shrink factor = " << shrinkFactors << std::endl;
std::cout << " smoothing sigma = ";
std::cout << smoothingSigmas[currentLevel] << std::endl;
std::cout << std::endl;
// Software Guide : BeginLatex
//
// If this is the first resolution level we set the learning rate
// (representing the first step size) and the minimum step length (representing
// the convergence criterion) to large values. At each subsequent resolution
// level, we will reduce the minimum step length by a factor of 5 in order to
// allow the optimizer to focus on progressively smaller regions. The learning
// rate is set up to the current step length. In this way, when the
// optimizer is reinitialized at the beginning of the registration process for
// the next level, the step length will simply start with the last value used
// for the previous level. This will guarantee the continuity of the path
// taken by the optimizer through the parameter space.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
//if (registration->GetCurrentLevel() == 0)
//{
// optimizer->SetLearningRate(16.00);
// optimizer->SetMinimumStepLength(2.5);
//}
//else
//{
// optimizer->SetLearningRate(optimizer->GetCurrentStepLength());
// optimizer->SetMinimumStepLength(optimizer->GetMinimumStepLength() * 0.2);
//}
// Software Guide : EndCodeSnippet
}
// Software Guide : BeginLatex
//
// Another version of the \code{Execute()} method accepting a \code{const}
// input object is also required since this method is defined as pure virtual
// in the base class. This version simply returns without taking any action.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
void
Execute(const itk::Object*, const itk::EventObject&) override
{
return;
}
};
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro(Self);
protected:
CommandIterationUpdate() {};
public:
//typedef itk::RegularStepGradientDescentOptimizerv4<double> OptimizerType;
//typedef itk::ConjugateGradientLineSearchOptimizerv4Template<double> OptimizerType;
//typedef itk::PowellOptimizerv4<double> OptimizerType;
typedef itk::LBFGSOptimizerv4 OptimizerType;
typedef const OptimizerType * OptimizerPointer;
std::ofstream windowObs;
void Execute(itk::Object *caller, const itk::EventObject & event) ITK_OVERRIDE
{
Execute((const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event) ITK_OVERRIDE
{
OptimizerPointer optimizer = static_cast<OptimizerPointer>(object);
if (!itk::IterationEvent().CheckEvent(&event))
{
return;
}
if (!windowObs.is_open())
windowObs.open(Iterationfilename);
windowObs << optimizer->GetCurrentIteration() << " ";
windowObs << optimizer->GetValue() << " ";
windowObs << optimizer->GetCurrentPosition() << "\n\n";
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
//int MultimodalRegistration(int argc, char *argv[])
//{
// std::cout << "Not yet implemented\n";
// return EXIT_SUCCESS;
//}
void exe_usage()
{
std::cerr << "\n";
std::cerr << "Usage: ImageRegistration3DClass <unsigned int registration_routine> <options> CTname CBCTname -o outputfilename(default:CBCT_ax_aligned_iso.mha)\n";
std::cerr << " where <options> is one or more of the following:\n\n";
//std::cerr << " <-A> Use GPU hardware (to be implemented) [default: cpu]\n";
std::cerr << " <-h> Display (this) usage information\n";
std::cerr << " <-v> Verbose output [default: no]\n";
//std::cerr << " <-resample <double>> Downsample by a factor <double>\n";
std::cerr << " <--like> Match CBCT to CT dimensions\n";
std::cerr << " <-c> Crop fixed to moving dimensions during registration -- speeds up the process and avoids Mutual Information issues\n";
std::cerr << " <-res <double, double, double>> Resample both images to <double, double, double>\n";
std::cerr << " <-fres <double, double, double>> Resample fixed image to <double, double, double>\n";
std::cerr << " <-mres <double, double, double>> Resample moving image to <double, double, double>\n";
std::cerr << " <-dpix <float>> Set Default Pixel Value to <float>\n";
std::cerr << " <-mm filename> Moving Image Mask [default: no]\n";
std::cerr << " <-mf filename> Fixed Image Mask [default: no] - under construction\n";
std::cerr << " <-par filename> Output parameters filename [default: yes]\n";
std::cerr << " <-rt filename> Beta version of Isocenter alignment -- not currently working on LPI images\n";
//std::cerr << " <-p> Permute image convention order (coronal to axial first) [default: no]\n";
//std::cerr << " <-iso double double double> Align CBCT to isocenter [default: yes]\n";
//std::cerr << " <-s> Scale image intensity [default: no] - calibration work in progress \n";
std::cerr << " <-dbg> Debugging output [default: no]\n";
std::cerr << " <-o filename> Output image filename\n\n";
std::cerr << " by Gabriele Belotti\n";
std::cerr << " [email protected]\n";
std::cerr << " (Politecnico di Milano)\n\n";
exit(EXIT_FAILURE);
}
_3DRegistration::_3DRegistration()
{
timer.Start("Total");
}
_3DRegistration::_3DRegistration(int argc, char *argv[])
{
timer.Start("Total");
std::cout << "Parsing arguments\n";
if (argc <= 3)
{
std::cout << "Not enough input arguments\n";
exe_usage();
}
while (argc > 1)
{
this->ok = false;
if ((this->ok == false) && (strcmp(argv[1], "-iso") == 0))
{
argc--; argv++;
this->cx = atof(argv[1]);
argc--; argv++;
this->cy = atof(argv[1]);
argc--; argv++;
this->cz = atof(argv[1]);
argc--; argv++;
this->customized_iso = true;
continue;
}
if ((ok == false) && (strcmp(argv[1], "-rt") == 0) && (customized_iso == false))
{
argc--; argv++;
std::cout << "RTplan reading\n";
ok = true;
this->RTplanFilename = argv[1];
this->ReadIsocenter();
argc--; argv++;
}
if ((this->ok == false) && (strcmp(argv[1], "-h") == 0))
{
argc--; argv++;
this->ok = true;
exe_usage();
}
if ((this->ok == false) && (strcmp(argv[1], "-v") == 0))
{
argc--; argv++;
this->ok = true;
this->verbose = true;
continue;
std::cout << "Verbose execution selected\n";
}
if ((this->ok == false) && (strcmp(argv[1], "-c") == 0))
{
argc--; argv++;
this->ok = true;
this->autocrop = true;
continue;
std::cout << "Autocropping selected\n";
}
if ((ok == false) && (strcmp(argv[1], "--like") == 0))
{
argc--; argv++;
ok = true;
this->like = true;
std::cout << "Selected fixed dimensions for output\n";
}
if ((ok == false) && (strcmp(argv[1], "--real") == 0))
{
argc--; argv++;
ok = true;
this->real = true;
std::cout << "Selected moving size with fixed resolution for output\n";
}
if ((this->ok == false) && (strcmp(argv[1], "-dbg") == 0))
{
argc--; argv++;
ok = true;
debug = true;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-dpix") == 0))
{
argc--; argv++;
ok = true;
//this->DefaultPixelValue = atof(argv[1]);
this->SetDefaultPixelValue(atof(argv[1]));
argc--; argv++;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-res") == 0))
{
argc--; argv++;
ok = true;
this->FixedImageResampleSpacing[0] = atof(argv[1]);
this->MovingImageResampleSpacing[0] = atof(argv[1]);
argc--; argv++;
this->FixedImageResampleSpacing[1] = atof(argv[1]);
this->MovingImageResampleSpacing[1] = atof(argv[1]);
argc--; argv++;
this->FixedImageResampleSpacing[2] = atof(argv[1]);
this->MovingImageResampleSpacing[2] = atof(argv[1]);
argc--; argv++;
this->fixed_resample = true;
this->moving_resample = true;
this->resolution = true;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-fres") == 0))
{
argc--; argv++;
ok = true;
this->FixedImageResampleSpacing[0] = atof(argv[1]);
argc--; argv++;
this->FixedImageResampleSpacing[1] = atof(argv[1]);
argc--; argv++;
this->FixedImageResampleSpacing[2] = atof(argv[1]);
argc--; argv++;
this->fixed_resample = true;
//this->resolution = true;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-mres") == 0))
{
argc--; argv++;
ok = true;
this->MovingImageResampleSpacing[0] = atof(argv[1]);
argc--; argv++;
this->MovingImageResampleSpacing[1] = atof(argv[1]);
argc--; argv++;
this->MovingImageResampleSpacing[2] = atof(argv[1]);
argc--; argv++;
this->moving_resample = true;
//this->resolution = true;
continue;
}
//if ((this->ok == false) && (strcmp(argv[1], "-shrink") == 0))
//{
// argc--; argv++;
// ok = true;
// this->shrinkFactorsPerLevel. atof(argv[1]);
// argc--; argv++;
// this->FixedImageResampleSpacing[1] = atof(argv[1]);
// argc--; argv++;
// this->FixedImageResampleSpacing[2] = atof(argv[1]);
// argc--; argv++;
// this->fixed_resample = true;
// //this->resolution = true;
// continue;
//}
//if ((this->ok == false) && (strcmp(argv[1], "-smooth") == 0))
//{
// argc--; argv++;
// ok = true;
// this->smoothingSigmaPerLevel atof(argv[1]);
// argc--; argv++;
// this->FixedImageResampleSpacing[1] = atof(argv[1]);
// argc--; argv++;
// this->FixedImageResampleSpacing[2] = atof(argv[1]);
// argc--; argv++;
// this->fixed_resample = true;
// //this->resolution = true;
// continue;
//}
if ((this->ok == false) && (strcmp(argv[1], "-resample") == 0))
{
argc--; argv++;
this->ok = true;
this->shrinkFactor = atof(argv[1]);
this->shrinking = true;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-o") == 0))
{
argc--; argv++;
this->ok = true;
this->Outputfilename = argv[1];
argc--; argv++;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-par") == 0))
{
argc--; argv++;
this->ok = true;
this->OutputTransformfilename = argv[1];
argc--; argv++;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-mm") == 0))
{
argc--; argv++;
this->ok = true;
this->movingMaskfilename = argv[1];
this->moving_mask = true;
argc--; argv++;
continue;
}
if ((this->ok == false) && (strcmp(argv[1], "-mf") == 0))
{
argc--; argv++;
this->ok = true;
this->fixedMaskfilename = argv[1];
this->fixed_mask = true;
argc--; argv++;
continue;
}
if (ok == false)
{
if (!strcmp(argv[1], "1"))
{
std::cout << "Multimodality selected\n";
this->RegistrationMetric = MMI;
argc--;
argv++;
}
else if (!strcmp(argv[1], "2"))
{
std::cout << "Monomodality selected\n";
this->RegistrationMetric = MSE;
argc--;
argv++;
}
else if (this->fixedImagefilename.empty())
{
this->fixedImagefilename = argv[1];
argc--;
argv++;
}
else if (this->movingImagefilename.empty())
{
this->movingImagefilename = argv[1];
argc--;
argv++;
}
else
{
std::cerr << "ERROR: Cannot parse argument " << argv[1] << std::endl;
exe_usage();
}
}
}
if (this->RegistrationMetric == 0)
this->Initialize<_3DRegistration::MIMetricType>();
else
this->Initialize<_3DRegistration::MeanSquaresMetricType>();
}
_3DRegistration::~_3DRegistration()
{
//registration->Delete();
//metric->Delete();
//optimizer->Delete();
}
bool _3DRegistration::ReadIsocenter()
{
bool error_isocenter = EXIT_FAILURE;
unsigned int count_iso = 0;
double IsocenterBase[10][3];
if (error_isocenter = this->IsocenterSearch(this->RTplanFilename, count_iso, IsocenterBase))
{
this->RTplan = false;
std::cerr << "FAILED\n";
}
else
{
this->RTplan = true;
this->Isocenter[0] = IsocenterBase[0][0];
this->Isocenter[1] = IsocenterBase[0][1];
this->Isocenter[2] = IsocenterBase[0][2];
}
return error_isocenter;
}
bool _3DRegistration::StartRegistration()
{
//if (!this->Initialize())
//{
// if (verbose)
// std::cout << "Initialized correctly\n";
//}
//this->Initialize<MIMetricType>();
if (debug)
{
fixedImage->Print(std::cout);
movingImage->Print(std::cout);
}
try
{
fixedImage->Update();
}
catch (itk::ExceptionObject& error)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << error << std::endl;
return EXIT_FAILURE;
}
try
{
movingImage->Update();
}
catch (itk::ExceptionObject& error)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << error << std::endl;
return EXIT_FAILURE;
}
std::cout << "Updated\n";
try
{
if (debug)
{
metric->Print(std::cout);
}
std::cout << "Start Registration \n";
timer.Start("Registration");
registration->Update();
std::cout << "Optimizer stop condition: "
<< registration->GetOptimizer()->GetStopConditionDescription()
<< std::endl;
timer.Stop("Registration");
}
catch (itk::ExceptionObject& err)
{
std::cerr << "ExceptionObject caught - Registration !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::ofstream parametersFile;
//parametersFile.open(OutputTransformfilename, std::ofstream::out | std::ofstream::app);
parametersFile.open(OutputTransformfilename);
const TransformType::ParametersType finalParameters =
registration->GetOutput()->Get()->GetParameters();
const double versorX = finalParameters[0];
const double versorY = finalParameters[1];
const double versorZ = finalParameters[2];
const double finalTranslation[3] = { finalParameters[3], finalParameters[4], finalParameters[5] };
const unsigned int numberOfIterations = optimizer->GetCurrentIteration();
const double bestValue = optimizer->GetValue();
// Print out results
//
//TransformType::VersorType finalVersor;
//finalVersor.SetRotationAroundX(versorX);
//finalVersor.SetRotationAroundX(versorY);
//finalVersor.SetRotationAroundX(versorZ);
//finalVersor.GetAngle();
std::cout << std::endl << std::endl;
std::cout << "Result = " << std::endl;
//std::cout << " versor X = " << versorX << std::endl;
//std::cout << " versor Y = " << versorY << std::endl;
//std::cout << " versor Z = " << versorZ << std::endl;
std::cout << " angle around X = " << versorX/dtr << std::endl;
std::cout << " angle around Y = " << versorY/dtr << std::endl;
std::cout << " angle around Z = " << versorZ/dtr << std::endl;
std::cout << " Translation X = " << finalTranslation[0] << std::endl;
std::cout << " Translation Y = " << finalTranslation[1] << std::endl;
std::cout << " Translation Z = " << finalTranslation[2] << std::endl;
std::cout << " Iterations = " << numberOfIterations << std::endl;
std::cout << " Metric value = " << bestValue << std::endl;
TransformType::Pointer finalTransform = TransformType::New();
finalTransform->SetFixedParameters(registration->GetOutput()->Get()->GetFixedParameters());
finalTransform->SetParameters(finalParameters);
// Software Guide : BeginCodeSnippet
TransformType::MatrixType matrix = finalTransform->GetMatrix();
TransformType::OffsetType offset = finalTransform->GetOffset();
std::cout << "Matrix = " << std::endl << matrix << std::endl;
std::cout << "Offset = " << std::endl << offset << std::endl;
ResampleFilterType::Pointer resampler = ResampleFilterType::New();
resampler->SetTransform(finalTransform);
//resampler->SetInput(movingImage);
resampler->SetInput(movingImageReader->GetOutput());
/*MovingImageType::PointType*/ FinalMovingOrigin = movingImage->GetOrigin();
FinalMovingOrigin[0] = FinalMovingOrigin[0] - finalTranslation[0];
FinalMovingOrigin[1] = FinalMovingOrigin[1] - finalTranslation[1];
FinalMovingOrigin[2] = FinalMovingOrigin[2] - finalTranslation[2];
if (this->like)
{
//AGGIUNGI OFFSET PER RIPORTARE L'ORIGINE AL POSTO GIUSTO: TIPO ORIGINALFIXEDORIGIN - FINALMOVINGORIGIN
this->FinalMovingSpacing = this->OriginalFixedSpacing;
this->FinalMovingSize = this->OriginalFixedSize;
resampler->SetInput(movingImageReader->GetOutput());
}
else if (this->real)
{
this->FinalMovingSpacing = fixedImage->GetSpacing();
this->FinalMovingSize = movingImage->GetLargestPossibleRegion().GetSize(); //THIS GOES UNDER "REAL" OPTIONAL FLAG
}
else //Print out CBCT with original dimensions
{
//this->FinalMovingSpacing = movingImage->GetSpacing();
//this->FinalMovingSize = movingImage->GetLargestPossibleRegion().GetSize();
this->FinalMovingSpacing = OriginalMovingSpacing;
this->FinalMovingSize = OriginalMovingSize; //THIS GOES UNDER "REAL" OPTIONAL FLAG
}
resampler->SetOutputOrigin(FinalMovingOrigin);
resampler->SetDefaultPixelValue(this->DefaultPixelValue);
resampler->SetSize(this->FinalMovingSize);
resampler->SetOutputSpacing(this->FinalMovingSpacing);
resampler->SetOutputDirection(fixedImage->GetDirection());
WriterType::Pointer writer = WriterType::New();
//CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName(Outputfilename);
//caster->SetInput( resampler->GetOutput() );
writer->SetInput(resampler->GetOutput());
try
{
std::cout << "Writing registered Moving Image\n";
timer.Start("WriteCBCT");
writer->Update();
timer.Stop("WriteCBCT");
}
catch (itk::ExceptionObject& error)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << error << std::endl;
return EXIT_FAILURE;
}
//std::ofstream parametersFile;
//parametersFile.open(OutputTransformfilename);
parametersFile << std::endl << std::endl;
parametersFile << "Result = " << std::endl;
parametersFile << " Angle around X = " << versorX / dtr << std::endl;
parametersFile << " Angle around Y = " << versorY / dtr << std::endl;
parametersFile << " Angle around Z = " << versorZ / dtr << std::endl;
parametersFile << " Translation X = " << finalTranslation[0] << std::endl;
parametersFile << " Translation Y = " << finalTranslation[1] << std::endl;
parametersFile << " Translation Z = " << finalTranslation[2] << std::endl;
parametersFile << " Iterations = " << numberOfIterations << std::endl;
parametersFile << " Metric value = " << bestValue << std::endl;
parametersFile << "\nParameters :\n";
parametersFile << finalParameters << std::endl;
//parametersFile << "Timing :\n";
//parametersFile << timer.
//parametersFile << registration->GetOutput()->Get()->get
parametersFile.close();
//timer.ExpandedReport();
timer.Stop("Total");
timer.Report();
return EXIT_SUCCESS;
}
bool _3DRegistration::Resample(FixedImageType::Pointer InputImage, FixedImageType::SpacingType OutputSpacing , FixedImageType::Pointer &OutputImage)
{
ResampleFilterType::Pointer downsampler = ResampleFilterType::New();
using InterpolatorType = itk::BSplineResampleImageFunction<MovingImageType, double>;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
TransformType::Pointer IdentityTransform = TransformType::New();
IdentityTransform->SetIdentity();
downsampler->SetTransform(IdentityTransform);
FixedImageType::SizeType size = InputImage->GetLargestPossibleRegion().GetSize();
FixedImageType::SpacingType InputSpacing = InputImage->GetSpacing();
size[0] = size[0] / (OutputSpacing[0] / InputSpacing[0]);
size[1] = size[1] / (OutputSpacing[1] / InputSpacing[1]);
size[2] = size[2] / (OutputSpacing[2] / InputSpacing[2]);
downsampler->SetSize(size);
downsampler->SetInterpolator(interpolator);
//downsampler->SetSize(InputImage->GetLargestPossibleRegion().GetSize());
//downsampler->SetInterpolator()
downsampler->SetInput(InputImage);
downsampler->SetOutputOrigin(InputImage->GetOrigin());
downsampler->SetOutputSpacing(OutputSpacing);
downsampler->SetOutputDirection(InputImage->GetDirection());
downsampler->SetDefaultPixelValue(this->DefaultPixelValue);
OutputImage = downsampler->GetOutput();
try
{
if (verbose)
std::cout << "Resampling\n";
OutputImage->Update();
if (verbose)
std::cout << "Resampling done\n";
}
catch (itk::ExceptionObject& error)
{
std::cerr << "ExceptionObject caught during resampling !" << std::endl;
std::cerr << error << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool _3DRegistration::Crop(FixedImageType::Pointer Image2Crop, FixedImageType::Pointer ReferenceImage, FixedImageType::Pointer & OutputImage)
{
itk::ImageRegion<this->Dimension> FixedRegion = Image2Crop->GetLargestPossibleRegion();
itk::ImageRegion<this->Dimension> MovingRegion = ReferenceImage->GetLargestPossibleRegion();
FixedImageType::SizeType InputSize = FixedRegion.GetSize();
MovingImageType::SizeType ReferenceSize = MovingRegion.GetSize();
FixedImageType::SpacingType InputSpacing = Image2Crop->GetSpacing();
MovingImageType::SpacingType ReferenceSpacing = ReferenceImage->GetSpacing();
MovingImageType::SizeType OutputSize;
FixedImageType::SizeType LowerCrop{ 0 };
FixedImageType::SizeType UpperCrop{ 0 };
FixedImageType::PointType InputOrigin = Image2Crop->GetOrigin();
FixedImageType::PointType OutputOrigin = ReferenceImage->GetOrigin();
unsigned int padding_value[this->Dimension] = { 10, 10, 5 };
if (FixedRegion.IsInside(MovingRegion))
{
for (int kk = 0; kk < this->Dimension; kk++)
{
//OutputSize[kk] = ReferenceSize[kk] / (InputSpacing[kk] / ReferenceSpacing[kk]);
LowerCrop[kk] = (OutputOrigin[kk] - InputOrigin[kk]) / InputSpacing[kk]; // Check for positivity --> we need to make sure we're superimposing a subregion to the fixed image
UpperCrop[kk] = (InputSize[kk] - (LowerCrop[kk] + ReferenceSize[kk] / (InputSpacing[kk]/ReferenceSpacing[kk]))); // Check for positivity --> we need to make sure we're superimposing a subregion to the fixed image
OutputSize[kk] = InputSize[kk] - (LowerCrop[kk] + UpperCrop[kk]);
/* add some space around the cropped area to avoid losing info */
//if (LowerCrop[kk] <= 10)
// LowerCrop[kk] = 0;
//else
// LowerCrop[kk] -= padding_value[kk];
//if (UpperCrop[kk] <= 10)
// UpperCrop[kk] = 0;
//else
// UpperCrop[kk] -= padding_value[kk];
}
}
else
{
std::cerr << "Reference Image is not completely inside the Fixed one --> cropping is not supported\n";
return EXIT_FAILURE;
}
std::cout << "Reference Size " << ReferenceSize << std::endl;
std::cout << "Input Size " << InputSize << std::endl;
std::cout << "Output Size " << OutputSize << std::endl;
std::cout << "Lower crop " << LowerCrop << std::endl;
std::cout << "Upper crop " << UpperCrop << std::endl;
CropFixedFilterType::Pointer CropFixedFilter = CropFixedFilterType::New();
CropFixedFilter->SetInput(Image2Crop);
CropFixedFilter->SetLowerBoundaryCropSize(LowerCrop);
CropFixedFilter->SetUpperBoundaryCropSize(UpperCrop);
CropFixedFilter->SetExtractionRegion(FixedRegion); //valid only using extractimagefilter
CropFixedFilter->SetDirectionCollapseToIdentity();
try
{
if (verbose)
std::cout << "Cropping Fixed Image to Moving image size\n";
CropFixedFilter->Update();
}
catch(itk::ExceptionObject &err)
{
std::cerr << "Exception caught while cropping \n"
<< err << std::endl;
return EXIT_FAILURE;
}
OutputImage = CropFixedFilter->GetOutput();
return EXIT_SUCCESS;
}
bool _3DRegistration::ROICrop(FixedImageType::Pointer Image2Crop, FixedImageType::Pointer ReferenceImage, FixedImageType::Pointer & OutputImage)
{
double temp; //utility for calculation
itk::ImageRegion<this->Dimension> FixedRegion = Image2Crop->GetLargestPossibleRegion();
itk::ImageRegion<this->Dimension> MovingRegion = ReferenceImage->GetLargestPossibleRegion();
itk::ImageRegion<this->Dimension> OutputRegion;
const FixedImageType::DirectionType& FixedDirection = fixedImage->GetDirection();
MovingImageType::DirectionType& OutputDirection = MovingImageType::DirectionType::Matrix();
OutputDirection.SetIdentity(); // why setting RAI orientation?
using OrientationAdapterType = itk::SpatialOrientationAdapter;
itk::SpatialOrientation::ValidCoordinateOrientationFlags FixedOrientationFlag;
const MovingImageType::DirectionType& MovingDirection = movingImage->GetDirection();
OrientationAdapterType OrientationAdapter;
FixedOrientationFlag = OrientationAdapter.FromDirectionCosines(FixedDirection);
FixedImageType::SizeType InputSize = FixedRegion.GetSize();
MovingImageType::SizeType ReferenceSize = MovingRegion.GetSize();
FixedImageType::SpacingType InputSpacing = Image2Crop->GetSpacing();
MovingImageType::SpacingType ReferenceSpacing = ReferenceImage->GetSpacing();
//if (FixedOrientationFlag == itk::SpatialOrientation::ValidCoordinateOrientationFlags::ITK_COORDINATE_ORIENTATION_RAI)
//else if (OrientationFlag == itk::SpatialOrientation::ValidCoordinateOrientationFlags::ITK_COORDINATE_ORIENTATION_LPI)
MovingImageType::SizeType OutputSize;
FixedImageType::IndexType StartIndex{ 0 };
FixedImageType::SizeType LowerCrop{ 0 };
FixedImageType::SizeType UpperCrop{ 0 };
FixedImageType::PointType InputOrigin = Image2Crop->GetOrigin();
FixedImageType::PointType OutputOrigin = ReferenceImage->GetOrigin();
unsigned int padding_value[this->Dimension] = { 10, 10, 5 };
//if (FixedRegion.IsInside(MovingRegion))
//{
if (FixedOrientationFlag == itk::SpatialOrientation::ValidCoordinateOrientationFlags::ITK_COORDINATE_ORIENTATION_RAI)
{
for (int kk = 0; kk < this->Dimension; kk++)
{
temp = (OutputOrigin[kk] - InputOrigin[kk]) / InputSpacing[kk];
if (temp < 0) temp = 0;
StartIndex[kk] = temp;
LowerCrop[kk] = temp; // Check for positivity --> we need to make sure we're superimposing a subregion to the fixed image
temp = (InputSize[kk] - (LowerCrop[kk] + ReferenceSize[kk] / (InputSpacing[kk] / ReferenceSpacing[kk])));
if (temp < 0) temp = 0;
UpperCrop[kk] = temp; // Check for positivity --> we need to make sure we're superimposing a subregion to the fixed image
OutputSize[kk] = InputSize[kk] - (LowerCrop[kk] + UpperCrop[kk]);
//OutputSize[kk] = ReferenceSize[kk] * (ReferenceSpacing[kk] / InputSpacing[kk]);
/* add some space around the cropped area to avoid losing info */
//if (LowerCrop[kk] <= 10)
// LowerCrop[kk] = 0;
//else
// LowerCrop[kk] -= padding_value[kk];
//if (UpperCrop[kk] <= 10)
// UpperCrop[kk] = 0;
//else
// UpperCrop[kk] -= padding_value[kk];
}
}
else
{
temp = (-OutputOrigin[0] + InputOrigin[0]) / InputSpacing[0];
if (temp < 0) temp = 0;
StartIndex[0] = temp;
temp = (-OutputOrigin[1] + InputOrigin[1]) / InputSpacing[1];
if (temp < 0) temp = 0;
StartIndex[1] = temp;
temp = (OutputOrigin[2] - InputOrigin[2]) / InputSpacing[2];
if (temp < 0) temp = 0;
StartIndex[2] = temp;
for (int kk = 0; kk < this->Dimension; kk++)
{
LowerCrop[kk] = StartIndex[kk];
temp = (InputSize[kk] - (LowerCrop[kk] + ReferenceSize[kk] / (InputSpacing[kk] / ReferenceSpacing[kk]))); // Check for positivity --> we need to make sure we're superimposing a subregion to the fixed image
if (temp < 0) temp = 0;
UpperCrop[kk] = temp;
OutputSize[kk] = InputSize[kk] - (LowerCrop[kk] + UpperCrop[kk]);
}
}
//}
//else
//{
// std::cerr << "Reference Image is not completely inside the Fixed one --> cropping is not supported\n";
// return EXIT_FAILURE;
//}
std::cout << "Input Size " << InputSize << std::endl;
std::cout << "Reference Size " << ReferenceSize << std::endl;
std::cout << "Output Size " << OutputSize << std::endl;
std::cout << "Start Index " << StartIndex << std::endl;
std::cout << "Lower crop " << LowerCrop << std::endl;
std::cout << "Upper crop " << UpperCrop << std::endl;
//CropFixedFilterType::Pointer CropFixedFilter = CropFixedFilterType::New();
ROIFilterType::Pointer ROIFilter = ROIFilterType::New();
//CropFixedFilter->SetInput(Image2Crop);
//CropFixedFilter->SetLowerBoundaryCropSize(LowerCrop);
//CropFixedFilter->SetUpperBoundaryCropSize(UpperCrop);
//CropFixedFilter->SetExtractionRegion(FixedRegion); //valid only using extractimagefilter
//CropFixedFilter->SetDirectionCollapseToIdentity();
//try
//{
// if (verbose)
// std::cout << "Cropping Fixed Image to Moving image size\n";
// CropFixedFilter->Update();
//}
//catch(itk::ExceptionObject &err)
//{
// std::cerr << "Exception caught while cropping \n"
// << err << std::endl;
// return EXIT_FAILURE;
//}
OutputRegion.SetIndex(StartIndex);
OutputRegion.SetSize(OutputSize);
//FixedRegion.Crop(OutputRegion);
ROIFilter->SetRegionOfInterest(OutputRegion);
ROIFilter->SetInput(Image2Crop);
try
{
if (verbose)
std::cout << "Extracting Fixed Image region to Moving image size\n";
ROIFilter->Update();
}
catch (itk::ExceptionObject &err)
{
std::cerr << "Exception caught while extracting \n"
<< err << std::endl;
return EXIT_FAILURE;
}
//OutputImage = CropFixedFilter->GetOutput();
OutputImage = ROIFilter->GetOutput();
return EXIT_SUCCESS;
}
//bool _3DRegistration::Initialize(FixedImageType::Pointer &fixedImage, MovingImageType::Pointer &movingImage)
template<typename TMetricType>
bool _3DRegistration::Initialize()
{
timer.Start("Initialization");
/* Set Metric type to caller template */
metric = TMetricType::New();
/*Reading CT and CBCT images*/
fixedImageReader->SetFileName(fixedImagefilename);
movingImageReader->SetFileName(movingImagefilename);
try
{
std::cout << "Reading CT" << std::endl;
timer.Start("ReadCT");
fixedImageReader->Update();
std::cout << "Done\n";
timer.Stop("ReadCT");
}
catch (itk::ExceptionObject& err)
{
std::cerr << "Exception caught" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
try
{
std::cout << "Reading CBCT" << std::endl;
timer.Start("ReadCBCT");
movingImageReader->Update();
std::cout << "Done\n";