forked from BRAINSia/BRAINSTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDWIConverter.cxx
761 lines (694 loc) · 26.8 KB
/
DWIConverter.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
//
// Created by Johnson, Hans J on 12/3/16.
//
#include "DWIConverter.h"
#include "itkFlipImageFilter.h"
DWIConverter::DWIConverter( const FileNamesContainer & inputFileNames )
: m_InputFileNames( inputFileNames )
, m_SlicesPerVolume( 0 )
, m_NSlice( 0 )
, m_NVolume( 0 )
, m_NRRDSpaceDefinition( "left-posterior-superior" )
{
this->m_MeasurementFrame.SetIdentity();
m_thickness = 0;
}
DWIConverter::~DWIConverter() {}
DWIConverter::RotationMatrixType
DWIConverter::GetSpacingMatrix() const
{
RotationMatrixType SpacingMatrix;
SpacingMatrix.Fill( 0.0 );
SpacingMatrix[0][0] = this->m_Volume->GetSpacing()[0];
SpacingMatrix[1][1] = this->m_Volume->GetSpacing()[1];
SpacingMatrix[2][2] = this->m_Volume->GetSpacing()[2];
return SpacingMatrix;
}
const DWIMetaDataDictionaryValidator::GradientTableType &
DWIConverter::GetDiffusionVectors() const
{
return this->m_DiffusionVectors;
}
void
DWIConverter::ConvertToSingleBValueScaledDiffusionVectors()
{
const double maxBvalue = this->GetMaxBValue();
{
DWIMetaDataDictionaryValidator::GradientTableType BvalueScaledDiffusionVectors( 0 );
BvalueScaledDiffusionVectors.reserve( m_DiffusionVectors.size() );
for ( unsigned int k = 0; k < m_DiffusionVectors.size(); ++k )
{
vnl_vector_fixed< double, 3 > vec( 0.0 );
const float scaleFactor = ( maxBvalue > 0 ) ? ( sqrt( this->m_BValues[k] / maxBvalue ) ) : 0.0F;
std::cout << "Scale Factor for Multiple BValues: " << k << " -- sqrt( " << this->m_BValues[k] << " / "
<< maxBvalue << " ) = " << scaleFactor << std::endl;
for ( unsigned ind = 0; ind < 3; ++ind )
{
vec[ind] = this->m_DiffusionVectors[k][ind] * scaleFactor;
}
BvalueScaledDiffusionVectors.push_back( vec );
this->m_BValues[k] = maxBvalue;
}
this->m_DiffusionVectors = BvalueScaledDiffusionVectors;
}
}
void
DWIConverter::ConvertToMutipleBValuesUnitScaledBVectors()
{
const double maxBvalue = this->GetMaxBValue();
{
for ( unsigned int k = 0; k < m_DiffusionVectors.size(); ++k )
{
double mag = m_DiffusionVectors[k].magnitude();
m_DiffusionVectors[k].normalize();
this->m_BValues[k] = itk::Math::Round< double >( maxBvalue * mag * mag );
}
}
}
Volume4DType::Pointer
DWIConverter::OrientForFSLConventions( const bool toFSL )
{
static const double FSLDesiredDirectionFlipsWRTLPS[4] = { 1, -1, 1, 1 };
static const double DicomDesiredDirectionFlipsWRTLPS[4] = { 1, 1, 1, 1 };
this->ConvertBVectorsToIdentityMeasurementFrame();
Volume4DType::Pointer image4D = ThreeDToFourDImage( this->GetDiffusionVolume() );
Volume4DType::DirectionType direction = image4D->GetDirection();
direction.GetVnlMatrix().get_row( 0 ).magnitude();
// LPS to RAI as FSL desires images to be formatted for viewing purposes.
// This conversion makes FSLView display the images in
// a way that is most easily interpretable.
using FlipperType = itk::FlipImageFilter< Volume4DType >;
FlipperType::Pointer myFlipper = FlipperType::New();
myFlipper->SetInput( image4D );
FlipperType::FlipAxesArrayType arrayAxisFlip;
for ( size_t i = 0; i < Volume4DType::ImageDimension; ++i )
{
if ( toFSL )
{
arrayAxisFlip[i] =
( FSLDesiredDirectionFlipsWRTLPS[i] * direction( i, i ) < -0.5 ); // i.e. a negative magnitude greater than 0.5
}
else
{
arrayAxisFlip[i] = ( DicomDesiredDirectionFlipsWRTLPS[i] * direction( i, i ) <
-0.5 ); // i.e. a negative magnitude greater than 0.5
}
// This is necesssary to ensure that the BVEC file is consistent with FSL orientation assumptions
for ( size_t g = 0; g < this->m_DiffusionVectors.size(); ++g )
{
this->m_DiffusionVectors[g][i] *= ( arrayAxisFlip[i] ? -1 : 1 );
}
}
/* Debugging information for identifying orientation!
std::cout << "arrayAxisFlip" << std::endl;
for(int i =0; i < 11; ++i)
{
std::cout << arrayAxisFlip << std::endl;
std::cout << m_IsInterleaved << std::endl;
std::cout << m_SliceOrderIS << std::endl;
}
*/
//
// FSL wants the second and third dimensions flipped with regards to LPS orientation
// FSL wants the second and third dimeinsions flipped with regards to LPS orientation
myFlipper->SetFlipAxes( arrayAxisFlip );
myFlipper->FlipAboutOriginOff(); // Flip the image and direction cosignes
// this is similar to a transform of [1 0 0; 0 -1 0; 0 0 -1]
myFlipper->Update();
Volume4DType::Pointer temp = myFlipper->GetOutput();
temp->SetMetaDataDictionary( image4D->GetMetaDataDictionary() );
this->m_Volume = FourDToThreeDImage( temp );
return temp;
}
const std::vector< double > &
DWIConverter::GetBValues() const
{
return this->m_BValues;
}
void
DWIConverter::SetBValues( const std::vector< double > & inBValues )
{
this->m_BValues = inBValues;
}
double
DWIConverter::GetMaxBValue() const
{
return ComputeMaxBvalue( this->m_BValues );
}
DWIConverter::Volume3DUnwrappedType::Pointer
DWIConverter::GetDiffusionVolume() const
{
return this->m_Volume;
}
DWIConverter::SpacingType
DWIConverter::GetSpacing() const
{
return this->m_Volume->GetSpacing();
}
double
DWIConverter::GetThickness() const
{
return m_thickness;
}
void
DWIConverter::SetThicknessFromSpacing()
{
m_thickness = this->m_Volume->GetSpacing()[2];
}
DWIConverter::Volume3DUnwrappedType::PointType
DWIConverter::GetOrigin() const
{
return this->m_Volume->GetOrigin();
}
void
DWIConverter::SetOrigin( DWIConverter::Volume3DUnwrappedType::PointType origin )
{
return this->m_Volume->SetOrigin( origin );
}
DWIConverter::RotationMatrixType
DWIConverter::GetLPSDirCos() const
{
return this->m_Volume->GetDirection();
}
DWIConverter::RotationMatrixType
DWIConverter::GetMeasurementFrame() const
{
return this->m_MeasurementFrame;
}
DWIConverter::RotationMatrixType
DWIConverter::GetNRRDSpaceDirection() const
{
return this->m_Volume->GetDirection() * this->GetSpacingMatrix();
}
unsigned int
DWIConverter::GetSlicesPerVolume() const
{
return m_SlicesPerVolume;
}
unsigned int
DWIConverter::GetNVolume() const
{
return this->m_NVolume;
}
std::string
DWIConverter::GetNRRDSpaceDefinition() const
{
return this->m_NRRDSpaceDefinition;
}
unsigned short
DWIConverter::GetRows() const
{
return this->m_Volume->GetLargestPossibleRegion().GetSize()[0];
}
unsigned short
DWIConverter::GetCols() const
{
return this->m_Volume->GetLargestPossibleRegion().GetSize()[1];
}
void
DWIConverter::ReadGradientInformation( const std::string & inputBValues, const std::string & inputBVectors,
const std::string & inputVolumeNameTemplate )
{ // override gradients embedded in file with an external FSL Formatted files
std::string _inputBValues = inputBValues;
std::string baseDirectory = itksys::SystemTools::GetParentDirectory( inputVolumeNameTemplate );
if ( CheckArg< std::string >( "B Values", inputBValues, "" ) == EXIT_FAILURE )
{
std::vector< std::string > pathElements;
if ( !baseDirectory.empty() )
{
pathElements.push_back( baseDirectory );
pathElements.push_back( "/" );
}
pathElements.push_back( itksys::SystemTools::GetFilenameWithoutExtension( inputVolumeNameTemplate ) + ".bval" );
_inputBValues = itksys::SystemTools::JoinPath( pathElements );
std::cout << " From template " << inputVolumeNameTemplate << std::endl;
std::cout << " defaulting to: " << _inputBValues << std::endl;
}
std::string _inputBVectors = inputBVectors;
if ( CheckArg< std::string >( "B Vectors", inputBVectors, "" ) == EXIT_FAILURE )
{
std::vector< std::string > pathElements;
if ( !baseDirectory.empty() )
{
pathElements.push_back( baseDirectory );
pathElements.push_back( "/" );
}
pathElements.push_back( itksys::SystemTools::GetFilenameWithoutExtension( inputVolumeNameTemplate ) + ".bvec" );
_inputBVectors = itksys::SystemTools::JoinPath( pathElements );
std::cout << " From template " << inputVolumeNameTemplate << std::endl;
std::cout << " defaulting to: " << _inputBVectors << std::endl;
}
unsigned int bValCount = 0;
std::vector< double > BVals;
if ( ReadBVals( BVals, bValCount, _inputBValues ) != EXIT_SUCCESS )
{
itkGenericExceptionMacro( << "ERROR reading BValue " << _inputBValues );
}
DWIMetaDataDictionaryValidator::GradientTableType BVecs;
unsigned int bVecCount = 0;
if ( ReadBVecs( BVecs, bVecCount, _inputBVectors ) != EXIT_SUCCESS )
{
itkGenericExceptionMacro( << "ERROR reading BVector " << _inputBVectors );
}
if ( bValCount != bVecCount )
{
itkGenericExceptionMacro( << "Mismatch between count of B Vectors (" << bVecCount << ") and B Values (" << bValCount
<< ")" << std::endl );
}
size_t numGradients = BVals.size();
if ( numGradients != this->GetNVolume() )
{
itkGenericExceptionMacro( << "number of Gradients doesn't match number of volumes:" << numGradients
<< " != " << this->GetNVolume() << std::endl );
}
// We need to zero out BVecs for Zero BVals
for ( size_t i = 0; i < bValCount; ++i )
{
if ( BVals[i] < 1 )
{
BVecs[i][0] = 0;
BVecs[i][1] = 0;
BVecs[i][2] = 0;
}
else
{
BVecs[i].normalize(); // Ensure that they are unit vectors as required FSL.
}
}
this->m_DiffusionVectors = BVecs;
this->m_BValues = BVals;
return;
}
void
DWIConverter::ConvertBVectorsToIdentityMeasurementFrame()
{
DWIMetaDataDictionaryValidator::GradientTableType gradientVectors;
const vnl_matrix_fixed< double, 3, 3 > InverseMeasurementFrame = this->GetMeasurementFrame().GetInverse();
// grab the diffusion vectors.
for ( unsigned int k = 0; k < this->m_DiffusionVectors.size(); ++k )
{
DWIMetaDataDictionaryValidator::GradientDirectionType vec;
// For scanners, the measurement frame for the gradient directions is the same as the
// Excerpt from http://teem.sourceforge.net/nrrd/format.html definition of "measurement frame:"
// There is also the possibility that a measurement frame
// should be recorded for an image even though it is storing
// only scalar values (e.g., a sequence of diffusion-weighted MR
// images has a measurement frame for the coefficients of
// the diffusion-sensitizing gradient directions, and
// the measurement frame field is the logical store
// this information).
// It was noticed on oblique Philips DTI scans that the prescribed protocol directions were
// rotated by the ImageOrientationPatient amount and recorded in the DICOM header.
// In order to compare two different scans to determine if the same protocol was prosribed,
// it is necessary to multiply each of the recorded diffusion gradient directions by
// the inverse of the LPSDirCos.
vnl_vector_fixed< double, 3 > RotatedScaledDiffusionVectors =
InverseMeasurementFrame * ( this->m_DiffusionVectors[k] );
for ( unsigned ind = 0; ind < 3; ++ind )
{
vec[ind] = RotatedScaledDiffusionVectors[ind];
}
gradientVectors.push_back( vec );
}
this->m_DiffusionVectors = gradientVectors;
this->m_MeasurementFrame.SetIdentity();
}
std::string
DWIConverter::MakeFileComment( const std::string & version, bool useBMatrixGradientDirections,
bool useIdentityMeaseurementFrame, double smallGradientThreshold,
const std::string inputFileType ) const
{
std::stringstream commentSection;
{
commentSection << "#" << std::endl << "#" << std::endl;
commentSection << "# This file was created by DWIConvert version " << version << std::endl
<< "# https://github.com/BRAINSia/BRAINSTools" << std::endl
<< "# part of the BRAINSTools package." << std::endl
<< "# Command line options:" << std::endl
<< "# --inputFileType " << inputFileType << std::endl;
if ( std::abs( smallGradientThreshold - 0.2 ) > 1e-4 )
{
commentSection << "# --smallGradientThreshold " << smallGradientThreshold << std::endl;
}
if ( useIdentityMeaseurementFrame )
{
commentSection << "# --useIdentityMeasurementFrame" << std::endl;
}
if ( useBMatrixGradientDirections )
{
commentSection << "# --useBMatrixGradientDirections" << std::endl;
}
}
return commentSection.str();
}
void
DWIConverter::ManualWriteNRRDFile( const std::string & outputVolumeHeaderName, const std::string commentstring ) const
{
const size_t extensionPos = outputVolumeHeaderName.find( ".nhdr" );
const bool nrrdSingleFileFormat = ( extensionPos != std::string::npos ) ? false : true;
std::string outputVolumeDataName;
if ( extensionPos != std::string::npos )
{
outputVolumeDataName = outputVolumeHeaderName.substr( 0, extensionPos );
outputVolumeDataName += ".raw";
}
itk::NumberToString< double > DoubleConvert;
std::ofstream header;
// std::string headerFileName = outputDir + "/" + outputFileName;
const double maxBvalue = this->GetMaxBValue();
header.open( outputVolumeHeaderName.c_str(), std::ios_base::out | std::ios_base::binary );
header << "NRRD0005" << std::endl << std::setprecision( 17 ) << std::scientific;
header << commentstring;
// stamp with DWIConvert branding
if ( !nrrdSingleFileFormat )
{
header << "content: exists(" << itksys::SystemTools::GetFilenameName( outputVolumeDataName ) << ",0)" << std::endl;
}
header << "type: short" << std::endl;
header << "dimension: 4" << std::endl;
header << "space: " << this->GetNRRDSpaceDefinition() << "" << std::endl;
const DWIConverter::RotationMatrixType & NRRDSpaceDirection = this->GetNRRDSpaceDirection();
header << "sizes: " << this->GetRows() << " " << this->GetCols() << " " << this->GetSlicesPerVolume() << " "
<< this->GetNVolume() << std::endl;
header << "thicknesses: NaN NaN " << DoubleConvert( GetThickness() ) << " NaN" << std::endl;
// need to check
header << "space directions: "
<< "(" << DoubleConvert( NRRDSpaceDirection[0][0] ) << "," << DoubleConvert( NRRDSpaceDirection[1][0] ) << ","
<< DoubleConvert( NRRDSpaceDirection[2][0] ) << ") "
<< "(" << DoubleConvert( NRRDSpaceDirection[0][1] ) << "," << DoubleConvert( NRRDSpaceDirection[1][1] ) << ","
<< DoubleConvert( NRRDSpaceDirection[2][1] ) << ") "
<< "(" << DoubleConvert( NRRDSpaceDirection[0][2] ) << "," << DoubleConvert( NRRDSpaceDirection[1][2] ) << ","
<< DoubleConvert( NRRDSpaceDirection[2][2] ) << ") none" << std::endl;
header << "centerings: cell cell cell ???" << std::endl;
header << "kinds: space space space list" << std::endl;
header << "endian: little" << std::endl;
header << "encoding: raw" << std::endl;
header << "space units: \"mm\" \"mm\" \"mm\"" << std::endl;
const DWIConverter::Volume3DUnwrappedType::PointType ImageOrigin = this->GetOrigin();
header << "space origin: "
<< "(" << DoubleConvert( ImageOrigin[0] ) << "," << DoubleConvert( ImageOrigin[1] ) << ","
<< DoubleConvert( ImageOrigin[2] ) << ") " << std::endl;
if ( !nrrdSingleFileFormat )
{
header << "data file: " << itksys::SystemTools::GetFilenameName( outputVolumeDataName ) << std::endl;
}
{
DWIConverter::RotationMatrixType MeasurementFrame = this->GetMeasurementFrame();
header << "measurement frame: "
<< "(" << DoubleConvert( MeasurementFrame[0][0] ) << "," << DoubleConvert( MeasurementFrame[1][0] ) << ","
<< DoubleConvert( MeasurementFrame[2][0] ) << ") "
<< "(" << DoubleConvert( MeasurementFrame[0][1] ) << "," << DoubleConvert( MeasurementFrame[1][1] ) << ","
<< DoubleConvert( MeasurementFrame[2][1] ) << ") "
<< "(" << DoubleConvert( MeasurementFrame[0][2] ) << "," << DoubleConvert( MeasurementFrame[1][2] ) << ","
<< DoubleConvert( MeasurementFrame[2][2] ) << ")" << std::endl;
}
for ( std::map< std::string, std::string >::const_iterator it = this->m_CommonDicomFieldsMap.begin();
it != this->m_CommonDicomFieldsMap.end();
++it )
{
header << it->first << ":=" << it->second << std::endl;
}
header << "modality:=DWMRI" << std::endl;
// this is the norminal BValue, i.e. the largest one.
header << "DWMRI_b-value:=" << DoubleConvert( maxBvalue ) << std::endl;
// the following three lines are for older NRRD format, where
// baseline images are always in the begining.
// header << "DWMRI_gradient_0000:=0 0 0" << std::endl;
// header << "DWMRI_NEX_0000:=" << nBaseline << std::endl;
// need to check
{
const DWIMetaDataDictionaryValidator::GradientTableType & gradientVectors = this->m_DiffusionVectors;
unsigned int gradientVecIndex = 0;
for ( unsigned int k = 0; k < gradientVectors.size(); ++k )
{
header << "DWMRI_gradient_" << std::setw( 4 ) << std::setfill( '0' ) << k
<< ":=" << DoubleConvert( gradientVectors[gradientVecIndex][0] ) << " "
<< DoubleConvert( gradientVectors[gradientVecIndex][1] ) << " "
<< DoubleConvert( gradientVectors[gradientVecIndex][2] ) << std::endl;
++gradientVecIndex;
}
}
// write data in the same file is .nrrd was chosen
header << std::endl;
;
if ( nrrdSingleFileFormat )
{
unsigned long nVoxels = this->GetDiffusionVolume()->GetBufferedRegion().GetNumberOfPixels();
header.write( reinterpret_cast< char * >( this->GetDiffusionVolume()->GetBufferPointer() ),
nVoxels * sizeof( short ) );
}
else
{
// if we're writing out NRRD, and the split header/data NRRD
// format is used, write out the image as a raw volume.
itk::ImageFileWriter< DWIConverter::Volume3DUnwrappedType >::Pointer rawWriter =
itk::ImageFileWriter< DWIConverter::Volume3DUnwrappedType >::New();
itk::RawImageIO< PixelValueType, 3 >::Pointer rawIO = itk::RawImageIO< PixelValueType, 3 >::New();
rawWriter->SetImageIO( rawIO );
rawIO->SetByteOrderToLittleEndian();
rawWriter->SetFileName( outputVolumeDataName.c_str() );
rawWriter->SetInput( this->GetDiffusionVolume() );
try
{
rawWriter->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown while writing the series to" << outputVolumeDataName << " " << excp << std::endl;
std::cerr << excp << std::endl;
}
}
header.close();
return;
}
Volume4DType::Pointer
DWIConverter::ThreeDToFourDImage( Volume3DUnwrappedType::Pointer img ) const
{
const int nVolumes = this->GetNVolume();
DWIConverter::Volume3DUnwrappedType::SizeType size3D( img->GetLargestPossibleRegion().GetSize() );
DWIConverter::Volume3DUnwrappedType::DirectionType direction3D( img->GetDirection() );
DWIConverter::Volume3DUnwrappedType::SpacingType spacing3D( img->GetSpacing() );
DWIConverter::Volume3DUnwrappedType::PointType origin3D( img->GetOrigin() );
Volume4DType::RegionType region4D;
{
Volume4DType::SizeType size4D;
size4D[0] = size3D[0];
size4D[1] = size3D[1];
size4D[2] = size3D[2] / nVolumes;
size4D[3] = nVolumes;
Volume4DType::IndexType index4D;
index4D.Fill( 0 );
region4D.SetIndex( index4D );
region4D.SetSize( size4D );
if ( ( size4D[2] * nVolumes ) != size3D[2] )
{
itkGenericExceptionMacro( << "#of slices in volume not evenly divisible by"
<< " the number of volumes: slices = " << size3D[2] << " volumes = " << nVolumes
<< " left-over slices = " << size3D[2] % nVolumes << std::endl );
}
}
Volume4DType::DirectionType direction4D;
direction4D.SetIdentity();
Volume4DType::SpacingType spacing4D;
spacing4D.Fill( 1.0 );
Volume4DType::PointType origin4D;
origin4D.Fill( 0.0 );
for ( unsigned i = 0; i < 3; ++i )
{
for ( unsigned j = 0; j < 3; ++j )
{
direction4D[i][j] = direction3D[i][j];
}
spacing4D[i] = spacing3D[i];
origin4D[i] = origin3D[i];
}
Volume4DType::Pointer img4D = Volume4DType::New();
img4D->SetRegions( region4D );
img4D->SetDirection( direction4D );
img4D->SetSpacing( spacing4D );
img4D->SetOrigin( origin4D );
img4D->Allocate();
{
img4D->SetMetaDataDictionary( img->GetMetaDataDictionary() );
// Set the qform and sfrom codes for the MetaDataDictionary.
itk::MetaDataDictionary & thisDic = img4D->GetMetaDataDictionary();
itk::EncapsulateMetaData< std::string >( thisDic, "qform_code_name", "NIFTI_XFORM_SCANNER_ANAT" );
itk::EncapsulateMetaData< std::string >( thisDic, "sform_code_name", "NIFTI_XFORM_SCANNER_ANAT" );
itk::EncapsulateMetaData< double >( thisDic, "NRRD_thicknesses", GetThickness() );
}
const size_t bytecount = img4D->GetLargestPossibleRegion().GetNumberOfPixels() * sizeof( PixelValueType );
memcpy( img4D->GetBufferPointer(), img->GetBufferPointer(), bytecount );
return img4D;
}
DWIConverter::Volume3DUnwrappedType::Pointer
DWIConverter::FourDToThreeDImage( Volume4DType::Pointer img4D ) const
{
Volume4DType::SizeType size4D( img4D->GetLargestPossibleRegion().GetSize() );
Volume4DType::DirectionType direction4D( img4D->GetDirection() );
Volume4DType::SpacingType spacing4D( img4D->GetSpacing() );
Volume4DType::PointType origin4D( img4D->GetOrigin() );
Volume3DUnwrappedType::RegionType region3D;
{
Volume3DUnwrappedType::SizeType size3D;
size3D[0] = size4D[0];
size3D[1] = size4D[1];
const int nVolumes = img4D->GetLargestPossibleRegion().GetSize()[3];
size3D[2] = size4D[2] * nVolumes;
Volume3DUnwrappedType::IndexType index3D;
index3D.Fill( 0 );
region3D.SetIndex( index3D );
region3D.SetSize( size3D );
if ( ( size4D[2] * nVolumes ) != size3D[2] )
{
itkGenericExceptionMacro( << "#of slices in volume not evenly divisible by"
<< " the number of volumes: slices = " << size3D[2] << " volumes = " << nVolumes
<< " left-over slices = " << size3D[2] % nVolumes << std::endl );
}
}
Volume3DUnwrappedType::DirectionType direction3D;
direction3D.SetIdentity();
Volume3DUnwrappedType::SpacingType spacing3D;
spacing3D.Fill( 1.0 );
Volume3DUnwrappedType::PointType origin3D;
origin3D.Fill( 0.0 );
for ( unsigned i = 0; i < 3; ++i )
{
for ( unsigned j = 0; j < 3; ++j )
{
direction3D[i][j] = direction4D[i][j];
}
spacing3D[i] = spacing4D[i];
origin3D[i] = origin4D[i];
}
Volume3DUnwrappedType::Pointer img = Volume3DUnwrappedType::New();
img->SetRegions( region3D );
img->SetDirection( direction3D );
img->SetSpacing( spacing3D );
img->SetOrigin( origin3D );
img->Allocate();
{
img->SetMetaDataDictionary( img4D->GetMetaDataDictionary() );
// Set the qform and sfrom codes for the MetaDataDictionary.
itk::MetaDataDictionary & thisDic = img->GetMetaDataDictionary();
itk::EncapsulateMetaData< std::string >( thisDic, "qform_code_name", "NIFTI_XFORM_SCANNER_ANAT" );
itk::EncapsulateMetaData< std::string >( thisDic, "sform_code_name", "NIFTI_XFORM_SCANNER_ANAT" );
itk::EncapsulateMetaData< double >( thisDic, "NRRD_thicknesses", GetThickness() );
}
const size_t bytecount = img->GetLargestPossibleRegion().GetNumberOfPixels() * sizeof( PixelValueType );
memcpy( img->GetBufferPointer(), img4D->GetBufferPointer(), bytecount );
return img;
}
void
DWIConverter::WriteFSLFormattedFileSet( const std::string & outputVolumeHeaderName, const std::string outputBValues,
const std::string outputBVectors, Volume4DType::Pointer img4D ) const
{
const double trace = this->m_MeasurementFrame[0][0] * this->m_MeasurementFrame[1][1] * this->m_MeasurementFrame[2][2];
if ( std::abs( trace - 1.0 ) > 1e-4 )
{
itkGenericExceptionMacro( << "ERROR: Only identity measurement frame allow for writing FSL formatted files "
<< std::endl );
}
{
// Set the qform and sfrom codes for the MetaDataDictionary.
itk::MetaDataDictionary & thisDic = img4D->GetMetaDataDictionary();
itk::EncapsulateMetaData< std::string >( thisDic, "qform_code_name", "NIFTI_XFORM_SCANNER_ANAT" );
itk::EncapsulateMetaData< std::string >( thisDic, "sform_code_name", "NIFTI_XFORM_SCANNER_ANAT" );
}
itk::ImageFileWriter< Volume4DType >::Pointer imgWriter = itk::ImageFileWriter< Volume4DType >::New();
imgWriter->SetInput( img4D );
imgWriter->SetFileName( outputVolumeHeaderName.c_str() );
try
{
imgWriter->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown while writing " << outputVolumeHeaderName << std::endl;
std::cerr << excp << std::endl;
throw;
}
// FSL output of gradients & BValues
std::string outputFSLBValFilename;
//
const size_t extensionPos = this->has_valid_nifti_extension( outputVolumeHeaderName );
if ( outputBValues == "" )
{
outputFSLBValFilename = outputVolumeHeaderName.substr( 0, extensionPos );
outputFSLBValFilename += ".bval";
}
else
{
outputFSLBValFilename = outputBValues;
}
std::string outputFSLBVecFilename;
if ( outputBVectors == "" )
{
outputFSLBVecFilename = outputVolumeHeaderName.substr( 0, extensionPos );
outputFSLBVecFilename += ".bvec";
}
else
{
outputFSLBVecFilename = outputBVectors;
}
// write out in FSL format
if ( WriteBValues< double >( this->m_BValues, outputFSLBValFilename ) != EXIT_SUCCESS )
{
itkGenericExceptionMacro( << "Failed to write FSL BVal File: " << outputFSLBValFilename << std::endl; );
}
if ( WriteBVectors( this->m_DiffusionVectors, outputFSLBVecFilename ) != EXIT_SUCCESS )
{
itkGenericExceptionMacro( << "Failed to write FSL BVec File: " << outputFSLBVecFilename << std::endl; );
}
}
void
DWIConverter::SetAllowLossyConversion( const bool newValue )
{
this->m_allowLossyConversion = newValue;
}
double
DWIConverter::ComputeMaxBvalue( const std::vector< double > & bValues ) const
{
double maxBvalue( 0.0 );
for ( unsigned int k = 0; k < bValues.size(); ++k )
{
if ( bValues[k] > maxBvalue )
{
maxBvalue = bValues[k];
}
}
return maxBvalue;
}
size_t
DWIConverter::has_valid_nifti_extension( std::string outputVolumeHeaderName ) const
{
constexpr size_t NUMEXT = 2;
const char * const extList[NUMEXT] = { ".nii.gz", ".nii" };
for ( size_t i = 0; i < NUMEXT; ++i )
{
const size_t extensionPos = outputVolumeHeaderName.find( extList[i] );
if ( extensionPos != std::string::npos )
{
return extensionPos;
}
}
{
std::cerr << "FSL Format output chosen, "
<< "but output Volume not a recognized "
<< "NIfTI filename " << outputVolumeHeaderName << std::endl;
exit( 1 );
}
return std::string::npos;
}
DWIConverter::Volume3DUnwrappedType::Pointer
DWIConverter::getVolumePointer()
{
return m_Volume;
}
double
DWIConverter::readThicknessFromDict()
{
DWIMetaDataDictionaryValidator myValidator;
myValidator.SetMetaDataDictionary( m_Volume->GetMetaDataDictionary() );
m_thickness = myValidator.GetThicknesses().at( 2 );
return m_thickness;
}