/
BRAINSABC.cxx
1664 lines (1497 loc) · 60.5 KB
/
BRAINSABC.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
#include "itkOutputWindow.h"
#include "itkTextOutput.h"
#include "itkTimeProbe.h"
#include <exception>
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <vector>
#include <algorithm>
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkCastImageFilter.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkWindowedSincInterpolateImageFunction.h"
#include "itkNumericTraits.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkVersion.h"
#include "itksys/SystemTools.hxx"
#include "PrettyPrintTable.h"
#include "DenoiseFiltering.h"
#include "itkImageDuplicator.h"
#include "itkBRAINSROIAutoImageFilter.h"
typedef itk::Image<float, 3> FloatImageType;
typedef itk::Image<unsigned char, 3> ByteImageType;
typedef itk::Image<short, 3> ShortImageType;
typedef FloatImageType::Pointer FloatImagePointer;
typedef ByteImageType::Pointer ByteImagePointer;
typedef ShortImageType::Pointer ShortImagePointer;
#include "mu.h"
#include "EMSParameters.h"
#include "AtlasDefinition.h"
#include <vector>
#include "Log.h"
#include <itksys/SystemTools.hxx>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <cstdlib>
#include <StandardizeMaskIntensity.h>
#include "BRAINSABCCLP.h"
#include "BRAINSThreadControl.h"
// Use manually instantiated classes for the big program chunks
#define MU_MANUAL_INSTANTIATION
#include "EMSegmentationFilter.h"
#include "AtlasRegistrationMethod.h"
#undef MU_MANUAL_INSTANTIATION
// From an inputVector create an outputVector that only contains the unique
// elements.
template <class T>
T RemoveDuplicates(T & origVect, const std::vector<bool> & dupsList)
{
T outVector(0);
outVector.reserve(origVect.size() );
for( size_t inlist = 0; inlist < origVect.size(); inlist++ )
{
if( dupsList[inlist] == false )
{
outVector.push_back(origVect[inlist]);
}
}
return outVector;
}
//
// Get a version of the filename that does not include the preceeding path, or
// the image file extensions.
static std::string GetStripedImageFileNameExtension(const std::string & ImageFileName)
{
std::vector<std::string> ExtensionsToRemove(6);
ExtensionsToRemove[0] = ".gz";
ExtensionsToRemove[1] = ".nii";
ExtensionsToRemove[2] = ".hdr";
ExtensionsToRemove[3] = ".img";
ExtensionsToRemove[4] = ".gipl";
ExtensionsToRemove[5] = ".nrrd";
std::string returnString = itksys::SystemTools::GetFilenameName( ImageFileName );
for( size_t s = 0; s < ExtensionsToRemove.size(); s++ )
{
size_t rfind_location = returnString.rfind(ExtensionsToRemove[s]);
if( ( rfind_location != std::string::npos )
&& ( rfind_location == ( returnString.size() - ExtensionsToRemove[s].size() ) )
)
{
returnString.replace(rfind_location, ExtensionsToRemove[s].size(), "");
}
}
return returnString;
}
static FloatImageType::Pointer CopyOutputImage(FloatImageType::Pointer img )
{
// muLogMacro(<< "CopyOutputImage" << std::endl );
FloatImageType::Pointer outimg = FloatImageType::New();
outimg->CopyInformation(img);
outimg->SetRegions( img->GetLargestPossibleRegion() );
outimg->Allocate();
typedef itk::ImageRegionIterator<FloatImageType> InternalIteratorType;
InternalIteratorType inputIter( img, img->GetLargestPossibleRegion() );
typedef itk::ImageRegionIterator<FloatImageType> OutputIteratorType;
OutputIteratorType outputIter( outimg, outimg->GetLargestPossibleRegion() );
inputIter.GoToBegin();
outputIter.GoToBegin();
while( !inputIter.IsAtEnd() )
{
outputIter.Set( static_cast<FloatImageType::PixelType>( inputIter.Get() ) );
++inputIter;
++outputIter;
}
return outimg;
}
// /////
//
//
//
static std::vector<FloatImageType::Pointer> ResampleImageList(
const std::string & resamplerInterpolatorType,
const std::vector<FloatImageType::Pointer> & inputImageList,
const std::vector<GenericTransformType::Pointer> & intraSubjectTransforms)
{
// Clear image list
std::vector<FloatImageType::Pointer> outputImageList;
outputImageList.clear();
outputImageList.resize( inputImageList.size() );
outputImageList[0] = CopyOutputImage(inputImageList[0]);
const FloatImageType::PixelType outsideFOVCode = vnl_huge_val( static_cast<FloatImageType::PixelType>( 1.0f ) );
// Resample the other images
for( unsigned int i = 1; i < inputImageList.size(); i++ )
{
muLogMacro(<< "Resampling input image " << i + 1 << "." << std::endl);
typedef itk::ResampleImageFilter<FloatImageType, FloatImageType> ResampleType;
typedef ResampleType::Pointer ResamplePointer;
ResamplePointer resampler = ResampleType::New();
resampler->SetInput(inputImageList[i]);
resampler->SetTransform(intraSubjectTransforms[i]);
if( resamplerInterpolatorType == "BSpline" )
{
typedef itk::BSplineInterpolateImageFunction<FloatImageType, double, double>
SplineInterpolatorType;
// Spline interpolation, only available for input images, not
// atlas
SplineInterpolatorType::Pointer splineInt
= SplineInterpolatorType::New();
splineInt->SetSplineOrder(5);
resampler->SetInterpolator(splineInt);
}
else if( resamplerInterpolatorType == "WindowedSinc" )
{
typedef itk::ConstantBoundaryCondition<FloatImageType>
BoundaryConditionType;
static const unsigned int WindowedSincHammingWindowRadius = 5;
typedef itk::Function::HammingWindowFunction<
WindowedSincHammingWindowRadius, double, double> WindowFunctionType;
typedef itk::WindowedSincInterpolateImageFunction
<FloatImageType,
WindowedSincHammingWindowRadius,
WindowFunctionType,
BoundaryConditionType,
double> WindowedSincInterpolatorType;
WindowedSincInterpolatorType::Pointer windowInt
= WindowedSincInterpolatorType::New();
resampler->SetInterpolator(windowInt);
}
else // Default to m_UseNonLinearInterpolation == "Linear"
{
typedef itk::LinearInterpolateImageFunction<FloatImageType, double>
LinearInterpolatorType;
LinearInterpolatorType::Pointer linearInt
= LinearInterpolatorType::New();
resampler->SetInterpolator(linearInt);
}
resampler->SetDefaultPixelValue(outsideFOVCode);
resampler->SetOutputParametersFromImage(inputImageList[0]);
resampler->Update();
// Zero the mask region outside FOV and also the intensities with
// outside
// FOV code
typedef itk::ImageRegionIterator<FloatImageType> InternalIteratorType;
FloatImageType::Pointer tmp = resampler->GetOutput();
InternalIteratorType tmpIt( tmp, tmp->GetLargestPossibleRegion() );
// HACK: We can probably remove the mask generation from here.
// The FOV mask, regions where intensities in all channels do not
// match FOV code
ByteImageType::Pointer intraSubjectFOVIntersectionMask = NULL;
intraSubjectFOVIntersectionMask = ByteImageType::New();
intraSubjectFOVIntersectionMask->CopyInformation(inputImageList[0]);
intraSubjectFOVIntersectionMask->SetRegions( inputImageList[0]->GetLargestPossibleRegion() );
intraSubjectFOVIntersectionMask->Allocate();
intraSubjectFOVIntersectionMask->FillBuffer(1);
typedef itk::ImageRegionIterator<ByteImageType> MaskIteratorType;
MaskIteratorType maskIt( intraSubjectFOVIntersectionMask,
intraSubjectFOVIntersectionMask->GetLargestPossibleRegion() );
maskIt.GoToBegin();
tmpIt.GoToBegin();
while( !maskIt.IsAtEnd() )
{
if( tmpIt.Get() == outsideFOVCode ) // Voxel came from outside
// the original FOV during
// registration, so
// invalidate it.
{
maskIt.Set(0); // Set it as an invalid voxel in
// intraSubjectFOVIntersectionMask
tmpIt.Set(0); // Set image intensity value to zero.
}
++maskIt;
++tmpIt;
}
// Add the image
outputImageList[i] = CopyOutputImage(tmp);
}
return outputImageList;
}
static void RescaleFunctionLocal( std::vector<FloatImageType::Pointer> & localList)
{
for( unsigned int i = 0; i < localList.size(); i++ )
{
typedef itk::RescaleIntensityImageFilter<FloatImageType, FloatImageType>
RescaleType;
RescaleType::Pointer rescaler = RescaleType::New();
rescaler->SetOutputMinimum(1);
rescaler->SetOutputMaximum(MAX_IMAGE_OUTPUT_VALUE);
#define INPLACE_RESCALER 0 // HACK Test this out
#if defined( INPLACE_RESCALER )
rescaler->SetInPlace(true);
#endif
FloatImageType::Pointer tmp = localList[i];
rescaler->SetInput(tmp);
rescaler->Update();
#if defined( INPLACE_RESCALER )
localList[i] = rescaler->GetOutput();
#else
FloatImageType::SizeType size = localList[0]->GetLargestPossibleRegion().GetSize();
FloatImagePointer rImg = rescaler->GetOutput();
FloatImageType::IndexType ind;
// T.O.D.O. This could be done in-place using the -inplace flag of the
// rescaleImageIntensityFilter.
{
#pragma omp parallel for
for( long kk = 0; kk < (long)size[2]; kk++ )
{
for( long jj = 0; jj < (long)size[1]; jj++ )
{
for( long ii = 0; ii < (long)size[0]; ii++ )
{
const ProbabilityImageIndexType currIndex = {{ii, jj, kk}};
tmp->SetPixel( currIndex, rImg->GetPixel(ind) );
}
}
}
}
#endif
}
}
static std::vector<bool> FindDuplicateImages(const std::vector<FloatImagePointer> candidateSameImageList )
{
// Images with higher correlation are considered soo much the same that they are duplicates.
const double IMAGES_SAME_CORRELATION_CUTOFF = 0.999;
typedef itk::IdentityTransform<double, FloatImageType::ImageDimension> IDTYPE;
IDTYPE::Pointer myID = IDTYPE::New();
typedef itk::LinearInterpolateImageFunction<FloatImageType, double> InterpType;
InterpType::Pointer myInterp = InterpType::New();
std::vector<bool> isDuplicated(candidateSameImageList.size(), false);
#if 1
typedef itk::SpatialObject<3> SOImageMaskType;
typedef itk::Image<unsigned char, 3> VolumeMaskType;
std::vector<SOImageMaskType::Pointer> candidateSameImageMaskList(candidateSameImageList.size());
for( unsigned int start = 0; start < candidateSameImageList.size(); start++ )
{
typedef itk::Image<signed int, 3> VolumeImageType;
const float otsuPercentileThreshold=0.01F;
const float thresholdCorrectionFactor = 1.0F;
const unsigned int closingSize=0; // These are just to make masking as fast as possible.
const unsigned int ROIAutoDilateSize=0; // These are just to make masking as fast as possible.
typedef itk::BRAINSROIAutoImageFilter<FloatImageType, VolumeMaskType> ROIAutoType;
ROIAutoType::Pointer ROIFilter = ROIAutoType::New();
ROIFilter->SetInput(candidateSameImageList[start]);
ROIFilter->SetOtsuPercentileThreshold(otsuPercentileThreshold);
ROIFilter->SetClosingSize(closingSize);
ROIFilter->SetThresholdCorrectionFactor(thresholdCorrectionFactor);
ROIFilter->SetDilateSize(ROIAutoDilateSize);
ROIFilter->Update();
//const SOImageMaskType::Pointer maskWrapper = ROIFilter->GetSpatialObjectROI();
//VolumeMaskType::Pointer MaskImage = ROIFilter->GetOutput();
//candidateSameImageMaskList[start]=ROIFilter->GetOutput();
candidateSameImageMaskList[start]=ROIFilter->GetSpatialObjectROI();
}
#endif
for( unsigned int start = 0; start < candidateSameImageList.size(); start++ )
{
for( unsigned int q = start + 1; q < candidateSameImageList.size(); q++ )
{
typedef itk::NormalizedCorrelationImageToImageMetric<FloatImageType, FloatImageType> NormalizerType;
NormalizerType::Pointer myNormalizer = NormalizerType::New();
myNormalizer->SetFixedImage(candidateSameImageList[start]);
myNormalizer->SetMovingImage(candidateSameImageList[q]);
#if 1
myNormalizer->SetFixedImageMask(candidateSameImageMaskList[start]);
myNormalizer->SetMovingImageMask(candidateSameImageMaskList[q]);
#endif
myNormalizer->SetTransform(myID);
myNormalizer->SetFixedImageRegion( candidateSameImageList[start]->GetBufferedRegion() );
myInterp->SetInputImage(candidateSameImageList[q]);
myNormalizer->SetInterpolator(myInterp);
myNormalizer->Initialize();
const double correlationValue = vcl_abs(myNormalizer->GetValue(myID->GetParameters() ) );
muLogMacro(<< "Correlation value between image " << start << " and image " << q << ": " << correlationValue << std::endl);
if( correlationValue > IMAGES_SAME_CORRELATION_CUTOFF )
{
isDuplicated[q] = true;
}
}
}
for( unsigned int q = 0; q < candidateSameImageList.size(); q++ )
{
if (isDuplicated[q] == true)
{
muLogMacro( << "Marking highly correlated image as duplicate :" << q << std::endl);
}
}
return isDuplicated;
}
class EmptyVectorException
{
public:
EmptyVectorException(const char* pStr = "The list of input images was empty. Nothing to averge.") :
pMessage(pStr) {}
const char * what() const {return pMessage;}
private:
const char * pMessage;
};
// Take a list of coregistered images, all of the same type (T1,T2) and return the average image.
static FloatImageType::Pointer AverageImageList(
const std::vector<FloatImageType::Pointer> & inputImageList)
{
if(inputImageList.size() == 0)
{
// No images, something went wrong.
throw EmptyVectorException();
}
if(inputImageList.size() == 1)
{
// Only one image, nothing to average.
return inputImageList[0];
}
// Create an image iterator over the first image. Use that iterator to get an index into the other
// images, sum each of the voxel values and divide by the number of input images and set the output
// voxel at this index to that value.
// Duplicate the first input image to use as an output image.
typedef itk::ImageDuplicator< FloatImageType > DuplicatorType;
DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage(inputImageList[0]);
duplicator->Update();
FloatImageType::Pointer averageImage = duplicator->GetOutput();
// Create an image iterator over the first image.
typedef itk::ImageRegionIterator< FloatImageType > ImageRegionIteratorType;
ImageRegionIteratorType imgItr( inputImageList[0],inputImageList[0]->GetRequestedRegion() );
// Loop over the voxels calculating the averages.
for ( imgItr.GoToBegin(); !imgItr.IsAtEnd(); ++imgItr)
{
const FloatImageType::IndexType &idx = imgItr.GetIndex();
FloatImageType::PixelType avgValue = 0;
const unsigned int inputListSize = inputImageList.size();
const float invListSize = 1.0F/static_cast<float>(inputListSize);
for (unsigned int j=0; j<inputImageList.size(); ++j)
{
avgValue += inputImageList[j]->GetPixel(idx);
}
averageImage->SetPixel(idx,static_cast<FloatImageType::PixelType>(avgValue*invListSize));
}
return averageImage;
}
int main(int argc, char * *argv)
{
PARSE_ARGS;
const BRAINSUtils::StackPushITKDefaultNumberOfThreads TempDefaultNumberOfThreadsHolder(numberOfThreads);
// TODO: Need to figure out how to conserve memory better during the running
// of this application: itk::DataObject::GlobalReleaseDataFlagOn();
itk::OutputWindow::SetInstance( itk::TextOutput::New() );
typedef EMSegmentationFilter<FloatImageType, FloatImageType> SegFilterType;
// Check the parameters for valid values
bool AllSimpleParameterChecksValid = true;
if( maxIterations < 1 )
{
muLogMacro( << "Warning: "
<< "--maxIterations set to 0, so only initialization with priors will be completed." << std::endl );
}
if( inputVolumes.size() == 0 )
{
muLogMacro( << "ERROR: "
<< "Must specify --inputVolumes" << std::endl );
AllSimpleParameterChecksValid = false;
}
if(outputVolumes.size() != 1 && outputVolumes.size() != inputVolumes.size())
{
std::cerr << inputVolumes.size() << " images in input volumeslist, but "
<< outputVolumes.size() << " names in output volumes list"
<< "OR it must be exactly 1, and be the template for writing files."
<< std::endl;
return EXIT_FAILURE;
}
if( inputVolumeTypes.size() != inputVolumes.size() )
{
muLogMacro( << "ERROR: "
<< "--inputVolumeTypes and --inputVolumes must"
<< " have the same number of elements" << std::endl );
AllSimpleParameterChecksValid = false;
}
if( atlasDefinition == "" )
{
muLogMacro( << "Error: "
<< "--atlasDefinition <xml atlas def> required"
<< std::endl );
AllSimpleParameterChecksValid = false;
}
if( outputDir == "" )
{
muLogMacro( << "ERROR: "
<< "outputDir must be specified" << std::endl );
AllSimpleParameterChecksValid = false;
}
if( AllSimpleParameterChecksValid == false )
{
muLogMacro( << "ERROR: Commanline arguments are not valid." << std::endl );
GENERATE_ECHOARGS;
return EXIT_FAILURE;
}
AtlasDefinition atlasDefinitionParser;
try
{
atlasDefinitionParser.InitFromXML(atlasDefinition);
}
catch( ... )
{
muLogMacro( << "Error reading Atlas Definition from "
<< atlasDefinition
<< std::endl );
return EXIT_FAILURE;
}
;
atlasDefinitionParser.DebugPrint();
// Create and start a new timer (for the whole process)
// EMSTimer* timer = new EMSTimer();
itk::TimeProbe timer;
timer.Start();
// Directory separator string
std::string separator = std::string("/");
// separator[0] = MU_DIR_SEPARATOR; // always a '/' -- windows can handle
// that fine...
// Make sure last character in output directory string is a separator
if( outputDir[outputDir.size() - 1] != '/' /* MU_DIR_SEPARATOR */ )
{
outputDir += separator;
}
// Create the output directory, stop if it does not exist
// if(!mu::create_dir(outputDir.c_str()))
if( !itksys::SystemTools::MakeDirectory( outputDir.c_str() ) )
{
muLogMacro( << "ERROR: Could not create requested output directory " << outputDir << std::endl );
return EXIT_FAILURE;
}
// Set up the logger
{
const std::string logfn = outputDir + defaultSuffix + ".log";
( mu::Log::GetInstance() )->EchoOn();
( mu::Log::GetInstance() )->SetOutputFileName( logfn.c_str() );
}
// Set up suffix string for images
std::string fmt = outputFormat;
std::string outext = ".mha";
if( itksys::SystemTools::Strucmp(fmt.c_str(), "Nrrd") == 0 )
{
outext = ".nrrd";
}
else if( itksys::SystemTools::Strucmp(fmt.c_str(), "Meta") == 0 )
{
outext = ".mha";
}
else if( itksys::SystemTools::Strucmp(fmt.c_str(), "NIFTI") == 0 )
{
outext = ".nii.gz";
}
else
{
muLogMacro(<< "WARNING: output format unrecognized, using Meta format\n");
}
const std::string suffstr
= std::string("_") + std::string(defaultSuffix) + outext;
muLogMacro(<< "mu::brainseg\n");
muLogMacro(<< "========================================\n");
muLogMacro(<< "Program compiled on: " << __DATE__ << std::endl );
muLogMacro(<< std::endl );
muLogMacro(
<< "Hans J. Johnson - hans-johnson@uiowa.edu, has made significant"
<< " edits to this front end of the BRAINSABC system.\n");
muLogMacro(
<< "Original application was written by Marcel Prastawa - "
<< "prastawa@sci.utah.edu, and is maintained as a separate program.\n");
muLogMacro(<< "This software is provided for research purposes only\n");
muLogMacro(<< std::endl );
muLogMacro(<< "Using ITK version "
<< itk::Version::GetITKMajorVersion() << "."
<< itk::Version::GetITKMinorVersion() << "."
<< itk::Version::GetITKBuildVersion() << std::endl );
muLogMacro(<< std::endl );
// Write input parameters
muLogMacro(<< "=== Parameters ===\n");
muLogMacro(<< "Suffix: " << defaultSuffix << std::endl );
muLogMacro(<< "Output Directory: " << outputDir << std::endl );
muLogMacro(<< "Output Format: " << outputFormat << std::endl );
muLogMacro(<< "Input images: \n");
muLogMacro(
<< "Non-linear filtering, method: " << filterMethod << ", "
<< filterIteration
<< " iterations, dt = " << filterTimeStep << std::endl );
const AtlasDefinition::TissueTypeVector & PriorNames
= atlasDefinitionParser.TissueTypes();
PrettyPrintTable AtlasDefTable;
AtlasDefTable.add(0, 0, "Prior Names");
AtlasDefTable.add(0, 1, ": [");
AtlasDefTable.add(0, PriorNames.size() + 2 + 1, "]");
SegFilterType::VectorType priorsWeightList;
priorsWeightList.set_size( PriorNames.size() );
AtlasDefTable.add(1, 0, "Prior weight scales");
AtlasDefTable.add(1, 1, ": [");
AtlasDefTable.add(1, PriorNames.size() + 2 + 1, "]");
unsigned int currentRow = 0;
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
AtlasDefTable.add(currentRow, 2 + pwi, PriorNames[pwi]);
}
currentRow++;
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
priorsWeightList[pwi] = atlasDefinitionParser.GetWeight(PriorNames[pwi]);
AtlasDefTable.add(currentRow, 2 + pwi, priorsWeightList[pwi], "%4.2f");
}
currentRow++;
SegFilterType::IntVectorType priorLabelCodeVector;
priorLabelCodeVector.set_size( PriorNames.size() );
AtlasDefTable.add(currentRow, 0, "Prior Label Codes");
AtlasDefTable.add(currentRow, 1, ": [");
AtlasDefTable.add(currentRow, PriorNames.size() + 2 + 1, "]");
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
priorLabelCodeVector[pwi] = atlasDefinitionParser.GetLabelCode(PriorNames[pwi]);
AtlasDefTable.add(currentRow, 2 + pwi, priorLabelCodeVector[pwi], "%d");
}
currentRow++;
SegFilterType::BoolVectorType priorIsForegroundPriorVector;
priorIsForegroundPriorVector.resize( PriorNames.size() );
AtlasDefTable.add(currentRow, 0, "Prior IsForeground");
AtlasDefTable.add(currentRow, 1, ": [");
AtlasDefTable.add(currentRow, PriorNames.size() + 2 + 1, "]");
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
priorIsForegroundPriorVector[pwi] = atlasDefinitionParser.GetIsForegroundPrior(PriorNames[pwi]);
AtlasDefTable.add(currentRow, 2 + pwi, priorIsForegroundPriorVector[pwi], "%d");
}
currentRow++;
SegFilterType::IntVectorType priorGaussianClusterCountVector;
priorGaussianClusterCountVector.set_size( PriorNames.size() );
AtlasDefTable.add(currentRow, 0, "Prior Clusters");
AtlasDefTable.add(currentRow, 1, ": [");
AtlasDefTable.add(currentRow, PriorNames.size() + 2 + 1, "]");
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
priorGaussianClusterCountVector[pwi] = atlasDefinitionParser.GetGaussianClusterCount(PriorNames[pwi]);
AtlasDefTable.add(currentRow, 2 + pwi, priorGaussianClusterCountVector[pwi], "%d");
}
currentRow++;
SegFilterType::BoolVectorType priorUseForBiasVector;
priorUseForBiasVector.resize( PriorNames.size() );
AtlasDefTable.add(currentRow, 0, "Prior For Bias");
AtlasDefTable.add(currentRow, 1, ": [");
AtlasDefTable.add(currentRow, PriorNames.size() + 2 + 1, "]");
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
priorUseForBiasVector[pwi] = atlasDefinitionParser.GetUseForBias(PriorNames[pwi]);
AtlasDefTable.add(currentRow, 2 + pwi, priorUseForBiasVector[pwi], "%d");
}
{ // Print out the ranges.
currentRow++;
for( unsigned int pwi = 0; pwi < PriorNames.size(); pwi++ )
{
std::map<std::string, AtlasDefinition::BoundsType> temp_range_List;
for( unsigned int tt = 0; tt < inputVolumeTypes.size(); tt++ )
{
AtlasDefTable.add(currentRow + tt * 2 + 0, 0, std::string(inputVolumeTypes[tt]) + std::string(" Lower") );
AtlasDefTable.add(currentRow + tt * 2 + 0, 1, ": [");
AtlasDefTable.add(currentRow + tt * 2 + 0, PriorNames.size() + 2 + 1, "]");
AtlasDefTable.add(currentRow + tt * 2 + 1, 0, std::string(inputVolumeTypes[tt]) + std::string(" Upper") );
AtlasDefTable.add(currentRow + tt * 2 + 1, 1, ": [");
AtlasDefTable.add(currentRow + tt * 2 + 1, PriorNames.size() + 2 + 1, "]");
temp_range_List[inputVolumeTypes[tt]] = atlasDefinitionParser.GetBounds(PriorNames[pwi], inputVolumeTypes[tt]);
AtlasDefTable.add(currentRow + tt * 2 + 0, 2 + pwi, temp_range_List[inputVolumeTypes[tt]].GetLower(), "%4.2f");
AtlasDefTable.add(currentRow + tt * 2 + 1, 2 + pwi, temp_range_List[inputVolumeTypes[tt]].GetUpper(), "%4.2f");
}
}
}
{
std::ostringstream oss;
AtlasDefTable.Print(oss);
muLogMacro( << oss.str() );
}
muLogMacro(
<< "Max bias polynomial degree: " << maxBiasDegree << std::endl );
muLogMacro(<< "Atlas warping: " << !atlasWarpingOff << std::endl );
muLogMacro(
<< "Atlas warp spline grid size: " << gridSize[0] << " X "
<< gridSize[1] << " X "
<< gridSize[2] << std::endl );
muLogMacro(<< std::endl );
muLogMacro(<< "=== Start ===\n");
muLogMacro(<< "Registering images using affine transform...\n");
GenericTransformType::Pointer atlasToSubjectPreSegmentationTransform = NULL;
std::vector<FloatImagePointer> atlasOriginalImageList;
ByteImagePointer atlasBrainMask;
{ // Read template images needed for atlas registration
// muLogMacro(<< "Read template mask");
const std::string templateMask = atlasDefinitionParser.GetTemplateBrainMask();
if( templateMask.size() < 1 )
{
muLogMacro( << "No template mask specified" << std::endl );
return EXIT_FAILURE;
}
typedef itk::ImageFileReader<ByteImageType> ReaderType;
typedef ReaderType::Pointer ReaderPointer;
muLogMacro( << "Reading mask : " << templateMask << "...\n");
ReaderPointer imgreader = ReaderType::New();
imgreader->SetFileName( templateMask.c_str() );
try
{
imgreader->Update();
}
catch( ... )
{
muLogMacro( << "ERROR: Could not read image " << templateMask << "." << std::endl );
return EXIT_FAILURE;
}
atlasBrainMask = imgreader->GetOutput();
}
std::vector<FloatImagePointer> intraSubjectRegisteredImageList;
std::vector<FloatImagePointer> intraSubjectRegisteredRawImageList;
std::vector<std::string> priorfnlist;
std::vector<std::string> templateVolumes( inputVolumeTypes.size() );
for( unsigned int q = 0; q < inputVolumeTypes.size(); q++ )
{
const AtlasDefinition::TemplateMap & tm = atlasDefinitionParser.GetTemplateVolumes();
AtlasDefinition::TemplateMap::const_iterator ti = tm.find(inputVolumeTypes[q]);
if(ti != tm.end() )
{
std::string temp = ti->second;
std::cerr << "STATUS: Atlas image of type: " << inputVolumeTypes[q] << " added with filename: " << temp << std::endl;
templateVolumes[q] = temp;
}
else
{
std::cerr << "ERROR: Atlas image of type: " << inputVolumeTypes[q] << " not found in xml file." << std::endl;
throw;
}
}
std::vector<bool> candidateDuplicatesList;
{
typedef AtlasRegistrationMethod<float, float> AtlasRegType;
AtlasRegType::Pointer atlasreg = AtlasRegType::New();
if( debuglevel > 0 )
{
atlasreg->DebugOn();
atlasreg->SetDebugLevel(debuglevel);
}
atlasreg->SetSuffix(defaultSuffix);
// Compute list of file names for the atlasOriginalPriors
for( unsigned int q = 0; q < PriorNames.size(); q++ )
{
priorfnlist.push_back( atlasDefinitionParser.GetPriorFilename( PriorNames[q] ) );
}
{
std::vector<FloatImagePointer> intraSubjectRawImageList;
intraSubjectRawImageList.clear();
intraSubjectRawImageList.resize(inputVolumes.size(), 0);
std::vector<FloatImagePointer> intraSubjectNoiseRemovedImageList;
intraSubjectNoiseRemovedImageList.clear();
intraSubjectNoiseRemovedImageList.resize(inputVolumes.size(), 0);
{ // StartOriginalImagesList
const std::string suffixstr = "";
{ // Read subject images needed for atlas registration
// muLogMacro(<< "Read subject images");
if( inputVolumes.size() < 1 )
{
muLogMacro( << "No data images specified" << std::endl );
return EXIT_FAILURE;
}
typedef itk::ImageFileReader<FloatImageType> ReaderType;
typedef ReaderType::Pointer ReaderPointer;
std::vector<std::string> intraSubjectTransformFileNames( inputVolumes.size() );
for( unsigned int i = 0; i < inputVolumes.size(); i++ )
{
muLogMacro(
<< "Reading image " << i + 1 << ": " << inputVolumes[i] << "...\n");
ReaderPointer imgreader = ReaderType::New();
imgreader->SetFileName( inputVolumes[i].c_str() );
try
{
imgreader->Update();
}
catch( ... )
{
muLogMacro( << "ERROR: Could not read image " << inputVolumes[i] << "." << std::endl );
return EXIT_FAILURE;
}
// Initialize with file read in
FloatImageType::Pointer typewiseEqualizedToFirstImage = imgreader->GetOutput();
#if 0 // This needs more testing.
// Now go looking to see if this image type has already been found,
// and equalize to the first image of this type if found.
for( unsigned int prevImageIndex = 0; prevImageIndex < i; prevImageIndex++ )
{
if( inputVolumeTypes[i] == inputVolumeTypes[prevImageIndex] )
// If it matches a previous found image type,
// then histogram equalize
{
muLogMacro( << "Equalizing image (" << i << ") to image (" << prevImageIndex << ")" << std::endl );
typedef itk::HistogramMatchingImageFilter<FloatImageType,
FloatImageType> HistogramMatchingFilterType;
HistogramMatchingFilterType::Pointer histogramfilter
= HistogramMatchingFilterType::New();
histogramfilter->SetInput( imgreader->GetOutput() );
histogramfilter->SetReferenceImage( intraSubjectNoiseRemovedImageList[prevImageIndex] );
histogramfilter->SetNumberOfHistogramLevels( 128 );
histogramfilter->SetNumberOfMatchPoints( 16 );
// histogramfilter->ThresholdAtMeanIntensityOn();
histogramfilter->Update();
// Overwrite if necessary.
typewiseEqualizedToFirstImage = histogramfilter->GetOutput();
break;
}
}
#endif
// Normalize Image Intensities:
muLogMacro( << "Standardizing Intensities: ...\n" );
intraSubjectRawImageList[i] = StandardizeMaskIntensity<FloatImageType, ByteImageType>(
typewiseEqualizedToFirstImage,
NULL,
0.0005, 1.0 - 0.0005,
1, 0.95 * MAX_IMAGE_OUTPUT_VALUE,
0, MAX_IMAGE_OUTPUT_VALUE);
muLogMacro( << "done.\n" );
#if 1
{
std::vector<unsigned int> unused_gridSize;
double localFilterTimeStep=filterTimeStep;
if (localFilterTimeStep <= 0 )
{
FloatImageType::SpacingType::ValueType minPixelSize=
vcl_numeric_limits<FloatImageType::SpacingType::ValueType>::max();
const FloatImageType::SpacingType &imageSpacing=intraSubjectRawImageList[i]->GetSpacing();
for(int is=0; is < FloatImageType::ImageDimension; ++is)
{
minPixelSize = vcl_min( minPixelSize,imageSpacing[is]);
}
localFilterTimeStep=
( (minPixelSize - vcl_numeric_limits<FloatImageType::SpacingType::ValueType>::epsilon() )
/ ( vcl_pow(2.0, FloatImageType::ImageDimension+1 ) )
);
}
intraSubjectNoiseRemovedImageList[i] =
DenoiseFiltering<FloatImageType>(intraSubjectRawImageList[i], filterMethod, filterIteration,
localFilterTimeStep,
unused_gridSize);
if( debuglevel > 1 )
{
// DEBUG: This code is for debugging purposes only;
typedef itk::ImageFileWriter<FloatImageType> WriterType;
WriterType::Pointer writer = WriterType::New();
writer->UseCompressionOn();
std::stringstream template_index_stream("");
template_index_stream << i;
const std::string fn = outputDir + "/DENOISED_INDEX_" + template_index_stream.str() + ".nii.gz";
writer->SetInput(intraSubjectNoiseRemovedImageList[i]);
writer->SetFileName(fn.c_str() );
writer->Update();
muLogMacro( << "DEBUG: Wrote image " << fn << std::endl);
}
}
#else
intraSubjectNoiseRemovedImageList[i] = intraSubjectRawImageList[i];
#endif
intraSubjectTransformFileNames[i] = outputDir
+ GetStripedImageFileNameExtension(inputVolumes[i]) + std::string(
"_to_")
+ GetStripedImageFileNameExtension(inputVolumes[0]) + suffixstr
+ std::string(".mat");
}
atlasreg->SetIntraSubjectOriginalImageList(intraSubjectNoiseRemovedImageList);
atlasreg->SetIntraSubjectTransformFileNames(intraSubjectTransformFileNames);
}
{ // Read template images needed for atlas registration
// muLogMacro(<< "Read template images");
if( templateVolumes.size() < 1 )
{
muLogMacro( << "No data images specified" << std::endl );
return EXIT_FAILURE;
}
typedef itk::ImageFileReader<FloatImageType> ReaderType;
typedef ReaderType::Pointer ReaderPointer;
atlasOriginalImageList.clear();
atlasOriginalImageList.resize(templateVolumes.size(), 0);
for( unsigned int atlasIndex = 0; atlasIndex < templateVolumes.size(); atlasIndex++ )
{
//KENT: HACK: This currently just checks one previous location in the list to
// determine if the image was already loaded, It should check the
// entire list and avoid loading duplicate images into the list
// of atlas images.
if( ( atlasIndex > 0 ) && ( templateVolumes[atlasIndex] == templateVolumes[atlasIndex - 1] ) )
{ // If they are the same name, then just use same reference
muLogMacro(
<< "Referencing previous image " << atlasIndex + 1 << ": " << templateVolumes[atlasIndex] << "...\n");
atlasOriginalImageList[atlasIndex] = atlasOriginalImageList[atlasIndex - 1];
}
else
{
muLogMacro(
<< "Reading image " << atlasIndex + 1 << ": " << templateVolumes[atlasIndex] << "...\n");
ReaderPointer imgreader = ReaderType::New();
imgreader->SetFileName( templateVolumes[atlasIndex].c_str() );
try
{
imgreader->Update();
}
catch( ... )
{
muLogMacro( << "ERROR: Could not read image " << templateVolumes[atlasIndex] << "." << std::endl );
return EXIT_FAILURE;
}
muLogMacro( << "Standardizing Intensities: ..." );
FloatImagePointer img_i = StandardizeMaskIntensity<FloatImageType, ByteImageType>(
imgreader->GetOutput(),
atlasBrainMask,
0.0005, 1.0 - 0.0005,
1, 0.95 * MAX_IMAGE_OUTPUT_VALUE,
0, MAX_IMAGE_OUTPUT_VALUE);
muLogMacro( << "done." << std::endl );
atlasOriginalImageList[atlasIndex] = img_i;
if( debuglevel > 7 )
{
typedef itk::ImageFileWriter<FloatImageType> FloatWriterType;
FloatWriterType::Pointer writer = FloatWriterType::New();
std::stringstream write_atlas_index_stream("");
write_atlas_index_stream << atlasIndex;
const std::string fn
= outputDir + std::string("RenormalizedAtlasTemplate_") + write_atlas_index_stream.str() + suffstr;
writer->SetInput(atlasOriginalImageList[atlasIndex] );
writer->SetFileName( fn.c_str() );
writer->UseCompressionOn();
writer->Update();
}
}
}
atlasreg->SetAtlasOriginalImageList(atlasOriginalImageList);
atlasreg->SetInputVolumeTypes(inputVolumeTypes);
const std::string atlasTransformFileName = outputDir
+ GetStripedImageFileNameExtension(templateVolumes[0])
+ std::string("_to_")
+ GetStripedImageFileNameExtension(inputVolumes[0]) + suffixstr
+ std::string("PreSegmentation.mat");
atlasreg->SetAtlasToSubjectTransformFileName(atlasTransformFileName);
}
// atlasreg->SetOutputDebugDir(outputDir);
if( !( ( atlasToSubjectTransformType.compare("Identity") == 0 )
|| ( atlasToSubjectTransformType.compare("Rigid") == 0 )
|| ( atlasToSubjectTransformType.compare("Affine") == 0 )
|| ( atlasToSubjectTransformType.compare("BSpline") == 0 ) )
)
{
muLogMacro(
"ERROR: Invalid atlasToSubjectTransformType specified" << atlasToSubjectTransformType << std::endl);
return EXIT_FAILURE;
}
if( !( ( subjectIntermodeTransformType.compare("Identity") == 0 )
|| ( subjectIntermodeTransformType.compare("Rigid") == 0 )
|| ( subjectIntermodeTransformType.compare("Affine") == 0 )
|| ( subjectIntermodeTransformType.compare("BSpline") == 0 ) )
)
{
muLogMacro(
"ERROR: Invalid subjectIntermodeTransformType specified" << subjectIntermodeTransformType << std::endl);
return EXIT_FAILURE;
}
if( atlasToSubjectInitialTransform != "")
{
muLogMacro(<< "atlasToSubjectInitialTransform specified." << std::endl)
if( atlasToSubjectTransformType.compare("Identity") == 0 )
{
// Error because we're applying an identity transform by an initial transform was supplied.
muLogMacro(<< "ERROR: atlasToSubjectTransformType is Identity but an initial transform supplied." << std::endl);
return EXIT_FAILURE;
}
try