forked from ANTsX/ANTs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReadWriteImage.h
552 lines (469 loc) · 16.6 KB
/
ReadWriteImage.h
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
#ifndef __ReadWriteImage_h_
#define __ReadWriteImage_h_
#include <iostream>
#include <fstream>
#include <stdio.h>
#include "itkVector.h"
#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkWarpImageFilter.h"
// #include "itkInverseWarpImageFilter.h"
#include "itkAffineTransform.h"
#include "itkImageRegionIterator.h"
#include "itkResampleImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkLogTensorImageFilter.h"
#include "itkExpTensorImageFilter.h"
#include <sys/stat.h>
bool ANTSFileExists(std::string strFilename)
{
struct stat stFileInfo;
bool blnReturn;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(), &stFileInfo);
if( intStat == 0 )
{
// We were able to get the file attributes
// so the file obviously exists.
blnReturn = true;
}
else
{
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
blnReturn = false;
}
return blnReturn;
}
// Nifti stores DTI values in lower tri format but itk uses upper tri
// currently, nifti io does nothing to deal with this. if this changes
// the function below should be modified/eliminated.
template <class TImageType>
void NiftiDTICheck(itk::SmartPointer<TImageType> & target, const char *file, bool makeLower)
{
typedef typename TImageType::PixelType PixType;
return;
// typedef itk::ImageFileWriter<TImageType> Writer;
// typename Writer::Pointer writer = Writer::New();
// writer->SetInput( target );
// writer->SetFileName( "testdt.nii" );
// writer->Update();
// Check for nifti file
std::string filename = file;
std::string::size_type pos1 = filename.find( ".nii" );
std::string::size_type pos2 = filename.find( ".nia" );
if( (pos1 == std::string::npos) && (pos2 == std::string::npos) )
{
return;
}
if( PixType::Length != 6 )
{
return;
}
std::cout << "Performing lower/upper triangular format check for Nifti DTI" << std::endl;
// swap elements 2 and 3 for lower<->upper conversion
itk::ImageRegionIteratorWithIndex<TImageType>
iter(target, target->GetLargestPossibleRegion() );
unsigned int looksLikeLower = 0;
unsigned int looksLikeUpper = 0;
unsigned int nBadVoxels = 0;
unsigned int count = 0;
unsigned int el2Neg = 0;
unsigned int el3Neg = 0;
while( !iter.IsAtEnd() )
{
bool isValid = true;
for( unsigned int i = 0; i < 6; i++ )
{
if( iter.Get()[i] != iter.Get()[i] )
{
++nBadVoxels;
isValid = false;
}
}
double el2 = iter.Get()[2];
double el3 = iter.Get()[3];
if( el2 < 0 )
{
++el2Neg;
}
if( el3 < 0 )
{
++el3Neg;
}
if( isValid )
{
if( el2 > el3 )
{
++looksLikeLower;
}
else
{
++looksLikeUpper;
}
}
++count;
++iter;
}
// std::cout << "Invalid: " << nBadVoxels << "/" << count << std::endl;
// std::cout << "Lower: " << looksLikeLower << ", Upper: " << looksLikeUpper << std::endl;
// std::cout << "el2Neg: " << el2Neg << ", el3Neg: " << el3Neg << std::endl;
if( ( (looksLikeUpper > looksLikeLower) && makeLower) || ( (looksLikeLower > looksLikeUpper) && !makeLower) )
{
std::cout << "Performing lower/upper triangular format swap for Nifti DTI" << std::endl;
iter.GoToBegin();
while( !iter.IsAtEnd() )
{
PixType pix = iter.Get();
typename PixType::ValueType temp;
temp = pix[2];
pix[2] = pix[3];
pix[3] = temp;
iter.Set(pix);
++iter;
}
}
}
template <class TImageType>
void ReadTensorImage(itk::SmartPointer<TImageType> & target, const char *file, bool takelog = true)
{
if( !ANTSFileExists(std::string(file) ) )
{
std::cout << " file " << std::string(file) << " does not exist . " << std::endl; return;
}
// Read the image files begin
typedef TImageType ImageType;
typedef itk::ImageFileReader<ImageType> FileSourceType;
typedef typename ImageType::PixelType PixType;
typedef itk::LogTensorImageFilter<ImageType, ImageType> LogFilterType;
typename FileSourceType::Pointer reffilter = FileSourceType::New();
reffilter->SetFileName( file );
try
{
reffilter->Update();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception caught during reference file reading " << std::endl;
std::cout << e << " file " << file << std::endl;
target = NULL;
return;
}
target = reffilter->GetOutput();
NiftiDTICheck<ImageType>(target, file, false);
if( takelog )
{
typename LogFilterType::Pointer logFilter = LogFilterType::New();
logFilter->SetInput( reffilter->GetOutput() );
logFilter->Update();
target = logFilter->GetOutput();
std::cout << "Returning Log(D) for log-euclidean math ops" << std::endl;
}
}
template <class TImageType>
// void ReadImage(typename TImageType::Pointer target, const char *file)
void ReadImage(itk::SmartPointer<TImageType> & target, const char *file)
{
if( std::string(file).length() < 3 )
{
std::cout << " bad file name " << std::string(file) << std::endl; target = NULL; return;
}
if( !ANTSFileExists(std::string(file) ) )
{
std::cout << " file " << std::string(file) << " does not exist . " << std::endl; target = NULL; return;
}
/*// std::cout << " reading b " << std::string(file) << std::endl;
typedef itk::ImageFileReader<TImageType> readertype;
typename readertype::Pointer reader = readertype::New();
reader->SetFileName(file);
reader->Update();
target=(reader->GetOutput());
*/
// std::cout << " Entering Read " << file << std::endl;
// Read the image files begin
typedef TImageType ImageType;
typedef itk::ImageFileReader<ImageType> FileSourceType;
typedef typename ImageType::PixelType PixType;
// const unsigned int ImageDimension=ImageType::ImageDimension;
typename FileSourceType::Pointer reffilter = FileSourceType::New();
reffilter->SetFileName( file );
try
{
reffilter->Update();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception caught during reference file reading " << std::endl;
std::cout << e << " file " << file << std::endl;
target = NULL;
exit(1);
return;
}
// typename ImageType::DirectionType dir;
// dir.SetIdentity();
// reffilter->GetOutput()->SetDirection(dir);
// std::cout << " setting pointer " << std::endl;
target = reffilter->GetOutput();
// reffilter->GetOutput()->Print( std::cout );
// std::cout << " read direction " << << std::endl;
// if (reffilter->GetImageIO()->GetNumberOfComponents() == 6)
// NiftiDTICheck<ImageType>(target,file);
}
template <class ImageType>
typename ImageType::Pointer ReadImage(char* fn )
{
// Read the image files begin
typedef itk::ImageFileReader<ImageType> FileSourceType;
typedef typename ImageType::PixelType PixType;
// const unsigned int ImageDimension=ImageType::ImageDimension;
typename FileSourceType::Pointer reffilter = FileSourceType::New();
reffilter->SetFileName( fn );
try
{
reffilter->Update();
}
catch( itk::ExceptionObject & e )
{
std::cerr << "Exception caught during reference file reading " << std::endl;
std::cerr << e << std::endl;
return NULL;
}
typename ImageType::DirectionType dir;
dir.SetIdentity();
// reffilter->GetOutput()->SetDirection(dir);
typename ImageType::Pointer target = reffilter->GetOutput();
// if (reffilter->GetImageIO->GetNumberOfComponents() == 6)
// NiftiDTICheck<ImageType>(target,fn);
return target;
}
template <class ImageType>
typename ImageType::Pointer ReadTensorImage(char* fn, bool takelog = true )
{
// Read the image files begin
typedef itk::ImageFileReader<ImageType> FileSourceType;
typedef typename ImageType::PixelType PixType;
typedef itk::LogTensorImageFilter<ImageType, ImageType> LogFilterType;
// const unsigned int ImageDimension=ImageType::ImageDimension;
typename FileSourceType::Pointer reffilter = FileSourceType::New();
reffilter->SetFileName( fn );
try
{
reffilter->Update();
}
catch( itk::ExceptionObject & e )
{
std::cerr << "Exception caught during reference file reading " << std::endl;
std::cerr << e << std::endl;
return NULL;
}
typename ImageType::Pointer target = reffilter->GetOutput();
NiftiDTICheck<ImageType>(target, fn, false);
if( takelog )
{
typename LogFilterType::Pointer logFilter = LogFilterType::New();
logFilter->SetInput( target->GetOutput() );
logFilter->Update();
target = logFilter->GetOutput();
}
return target;
}
template <class TImageType>
void WriteImage(itk::SmartPointer<TImageType> image, const char *file)
{
if( std::string(file).length() < 3 )
{
return;
}
typename itk::ImageFileWriter<TImageType>::Pointer writer =
itk::ImageFileWriter<TImageType>::New();
writer->SetFileName(file);
if( !image )
{
std::cout << " file " << file << " does not exist " << std::endl;
exit(1);
}
// typename TImageType::DirectionType dir;
// dir.SetIdentity();
// image->SetDirection(dir);
// std::cout << " now Write direction " << image->GetOrigin() << std::endl;
// if (writer->GetImageIO->GetNumberOfComponents() == 6)
// NiftiDTICheck<TImageType>(image,file);
writer->SetInput(image);
writer->Update();
}
template <class TImageType>
void WriteTensorImage(itk::SmartPointer<TImageType> image, const char *file, bool takeexp = true)
{
typedef typename TImageType::PixelType PixType;
typedef itk::ExpTensorImageFilter<TImageType, TImageType> ExpFilterType;
typename itk::ImageFileWriter<TImageType>::Pointer writer =
itk::ImageFileWriter<TImageType>::New();
writer->SetFileName(file);
typename TImageType::Pointer writeImage = image;
if( takeexp )
{
typename ExpFilterType::Pointer expFilter = ExpFilterType::New();
expFilter->SetInput( image );
expFilter->Update();
writeImage = expFilter->GetOutput();
std::cout << "Taking Exp(D) before writing" << std::endl;
}
// convert from upper tri to lower tri
NiftiDTICheck<TImageType>(writeImage, file, true); // BA May 30 2009 -- remove b/c ITK fixed NIFTI reader
writer->SetInput(writeImage);
writer->Update();
}
template <class TImage, class TField>
typename TField::Pointer
ReadWarpFromFile( std::string warpfn, std::string ext)
{
typedef TField FieldType;
typedef typename FieldType::PixelType VectorType;
enum { ImageDimension = FieldType::ImageDimension };
typedef itk::Image<float, ImageDimension> RealImageType;
typedef RealImageType ImageType;
// typedef itk::Vector<float,itkGetStaticConstMacro(ImageDimension)> VectorType;
// typedef itk::Image<VectorType,itkGetStaticConstMacro(ImageDimension)> FieldType;
// std::cout << " warp file name " << warpfn + ext << std::endl;
std::string fn = "";
// First - read the vector fields
// NOTE : THE FIELD SHOULD WARP INPUT1 TO INPUT2, THUS SHOULD POINT
// FROM INPUT2 TO INPUT1
fn = warpfn + "x" + ext;
typename RealImageType::Pointer xvec = ReadImage<ImageType>( (char *)fn.c_str() );
// std::cout << " done reading " << fn << std::endl;
fn = warpfn + "y" + ext;
typename RealImageType::Pointer yvec = ReadImage<ImageType>( (char *)fn.c_str() );
// std::cout << " done reading " << fn << std::endl;
fn = warpfn + "z" + ext;
typename RealImageType::Pointer zvec = NULL;
// std::cout << " done reading " << fn << std::endl;
if( ImageDimension == 3 )
{
zvec = ReadImage<ImageType>( (char *)fn.c_str() );
}
typename FieldType::Pointer field = FieldType::New();
field->SetLargestPossibleRegion( xvec->GetLargestPossibleRegion() );
field->SetBufferedRegion( xvec->GetLargestPossibleRegion() );
field->SetLargestPossibleRegion( xvec->GetLargestPossibleRegion() );
field->SetOrigin(xvec->GetOrigin() );
field->SetDirection(xvec->GetDirection() );
field->Allocate();
itk::ImageRegionIteratorWithIndex<RealImageType>
it( xvec, xvec->GetLargestPossibleRegion() );
// std::cout << " spacing xv " << xvec->GetSpacing()[0]
// << " field " << field->GetSpacing()[0] << std::endl;
field->SetSpacing(xvec->GetSpacing() );
field->SetOrigin(xvec->GetOrigin() );
unsigned int ct = 0;
for( it.GoToBegin(); !it.IsAtEnd(); ++it )
{
ct++;
typename ImageType::IndexType index = it.GetIndex();
VectorType disp;
disp[0] = xvec->GetPixel(index);
disp[1] = yvec->GetPixel(index);
if( ImageDimension == 3 )
{
disp[2] = zvec->GetPixel(index);
}
field->SetPixel(index, disp);
// if (ct == 10000) std::cout << " 10000th pix " << disp << std::endl;
}
return field;
}
template <class TImage>
typename TImage::Pointer
MakeNewImage(typename TImage::Pointer image1, typename TImage::PixelType initval )
{
typedef itk::ImageRegionIteratorWithIndex<TImage> Iterator;
typename TImage::Pointer varimage = TImage::New();
varimage->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
varimage->SetBufferedRegion( image1->GetLargestPossibleRegion() );
varimage->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
varimage->Allocate();
varimage->SetSpacing(image1->GetSpacing() );
varimage->SetOrigin(image1->GetOrigin() );
varimage->SetDirection(image1->GetDirection() );
Iterator vfIter2( varimage, varimage->GetLargestPossibleRegion() );
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
if( initval >= 0 )
{
vfIter2.Set(initval);
}
else
{
vfIter2.Set(image1->GetPixel(vfIter2.GetIndex() ) );
}
}
return varimage;
}
template <class TField>
void
WriteDisplacementField(TField* field, std::string filename)
{
typedef TField FieldType;
typedef typename FieldType::PixelType VectorType;
enum { ImageDimension = FieldType::ImageDimension };
typedef itk::Image<float, ImageDimension> RealImageType;
// Initialize the caster to the displacement field
typedef itk::VectorIndexSelectionCastImageFilter<FieldType, RealImageType> IndexSelectCasterType;
for( unsigned int dim = 0; dim < ImageDimension; dim++ )
{
typename IndexSelectCasterType::Pointer fieldCaster = IndexSelectCasterType::New();
fieldCaster->SetInput( field );
fieldCaster->SetIndex( dim );
fieldCaster->Update();
// Set up the output filename
std::string outfile = filename + static_cast<char>('x' + dim) + std::string("vec.nii.gz");
std::cout << "Writing displacements to " << outfile << " spacing "
<< field->GetSpacing()[0] << std::endl;
typename RealImageType::Pointer fieldcomponent = fieldCaster->GetOutput();
fieldcomponent->SetSpacing(field->GetSpacing() );
fieldcomponent->SetOrigin(field->GetOrigin() );
fieldcomponent->SetDirection(field->GetDirection() );
WriteImage<RealImageType>(fieldcomponent, outfile.c_str() );
}
std::cout << "...done" << std::endl;
return;
}
template <class TField>
void
WriteDisplacementField2(TField* field, std::string filename, std::string app)
{
typedef TField FieldType;
typedef typename FieldType::PixelType VectorType;
enum { ImageDimension = FieldType::ImageDimension };
typedef itk::Image<float, ImageDimension> RealImageType;
// Initialize the caster to the displacement field
typedef itk::VectorIndexSelectionCastImageFilter<FieldType, RealImageType> IndexSelectCasterType;
for( unsigned int dim = 0; dim < ImageDimension; dim++ )
{
typename IndexSelectCasterType::Pointer fieldCaster = IndexSelectCasterType::New();
fieldCaster->SetInput( field );
fieldCaster->SetIndex( dim );
fieldCaster->Update();
// Set up the output filename
std::string outfile = filename + static_cast<char>('x' + dim) + std::string(app);
std::cout << "Writing displacements to " << outfile << " spacing "
<< field->GetSpacing()[0] << std::endl;
typename RealImageType::Pointer fieldcomponent = fieldCaster->GetOutput();
fieldcomponent->SetSpacing(field->GetSpacing() );
fieldcomponent->SetOrigin(field->GetOrigin() );
WriteImage<RealImageType>(fieldcomponent, outfile.c_str() );
}
std::cout << "...done" << std::endl;
return;
}
#endif