-
-
Notifications
You must be signed in to change notification settings - Fork 666
/
itkNiftiImageIO.cxx
2293 lines (2155 loc) · 76.6 KB
/
itkNiftiImageIO.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
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkNiftiImageIO.h"
#include "itkIOCommon.h"
#include "itkMetaDataObject.h"
#include "itkSpatialOrientationAdapter.h"
#include <nifti1_io.h>
#include "itkNiftiImageIOConfigurePrivate.h"
namespace itk
{
//#define ITK_USE_VERY_VERBOSE_NIFTI_DEBUGGING
#if defined(ITK_USE_VERY_VERBOSE_NIFTI_DEBUGGING)
namespace
{
static int
print_hex_vals(char const * const data, const int nbytes, FILE * const fp)
{
if (!data || nbytes < 1 || !fp)
{
return -1;
}
fputs("0x", fp);
for (int c = 0; c < nbytes; c++)
{
fprintf(fp, " %x", data[c]);
}
return 0;
}
static const char * const
str_intent(const unsigned int intent)
{
switch (intent)
{
case NIFTI_INTENT_NONE:
return "NIFTI_INTENT_NONE";
case NIFTI_INTENT_CORREL:
return "NIFTI_INTENT_CORREL";
case NIFTI_INTENT_TTEST:
return "NIFTI_INTENT_TTEST";
case NIFTI_INTENT_FTEST:
return "NIFTI_INTENT_FTEST";
case NIFTI_INTENT_ZSCORE:
return "NIFTI_INTENT_ZSCORE";
case NIFTI_INTENT_CHISQ:
return "NIFTI_INTENT_CHISQ";
case NIFTI_INTENT_BETA:
return "NIFTI_INTENT_BETA";
case NIFTI_INTENT_BINOM:
return "NIFTI_INTENT_BINOM";
case NIFTI_INTENT_GAMMA:
return "NIFTI_INTENT_GAMMA";
case NIFTI_INTENT_POISSON:
return "NIFTI_INTENT_POISSON";
case NIFTI_INTENT_NORMAL:
return "NIFTI_INTENT_NORMAL";
case NIFTI_INTENT_FTEST_NONC:
return "NIFTI_INTENT_FTEST_NONC";
case NIFTI_INTENT_CHISQ_NONC:
return "NIFTI_INTENT_CHISQ_NONC";
case NIFTI_INTENT_LOGISTIC:
return "NIFTI_INTENT_LOGISTIC";
case NIFTI_INTENT_LAPLACE:
return "NIFTI_INTENT_LAPLACE";
case NIFTI_INTENT_UNIFORM:
return "NIFTI_INTENT_UNIFORM";
case NIFTI_INTENT_TTEST_NONC:
return "NIFTI_INTENT_TTEST_NONC";
case NIFTI_INTENT_WEIBULL:
return "NIFTI_INTENT_WEIBULL";
case NIFTI_INTENT_CHI:
return "NIFTI_INTENT_CHI";
case NIFTI_INTENT_INVGAUSS:
return "NIFTI_INTENT_INVGAUSS";
case NIFTI_INTENT_EXTVAL:
return "NIFTI_INTENT_EXTVAL";
case NIFTI_INTENT_PVAL:
return "NIFTI_INTENT_PVAL";
case NIFTI_INTENT_LOGPVAL:
return "NIFTI_INTENT_LOGPVAL";
case NIFTI_INTENT_LOG10PVAL:
return "NIFTI_INTENT_LOG10PVAL";
case NIFTI_INTENT_ESTIMATE:
return "NIFTI_INTENT_ESTIMATE";
case NIFTI_INTENT_LABEL:
return "NIFTI_INTENT_LABEL";
case NIFTI_INTENT_NEURONAME:
return "NIFTI_INTENT_NEURONAME";
case NIFTI_INTENT_GENMATRIX:
return "NIFTI_INTENT_GENMATRIX";
case NIFTI_INTENT_SYMMATRIX:
return "NIFTI_INTENT_SYMMATRIX";
case NIFTI_INTENT_DISPVECT:
return "NIFTI_INTENT_DISPVECT";
case NIFTI_INTENT_VECTOR:
return "NIFTI_INTENT_VECTOR";
case NIFTI_INTENT_POINTSET:
return "NIFTI_INTENT_POINTSET";
case NIFTI_INTENT_TRIANGLE:
return "NIFTI_INTENT_TRIANGLE";
case NIFTI_INTENT_QUATERNION:
return "NIFTI_INTENT_QUATERNION";
case NIFTI_INTENT_DIMLESS:
return "NIFTI_INTENT_DIMLESS";
default:
return "UNKNOWN_INTENT";
}
}
//--------------------------------------------------------------------
// display the contents of the nifti_1_header (send to stdout)
//--------------------------------------------------------------------
static int
DumpNiftiHeader(const std::string & fname)
{
int swap;
nifti_1_header * hp = nifti_read_header(fname.c_str(), &swap, true);
fputs("-------------------------------------------------------\n", stderr);
if (!hp)
{
fputs(" ** no nifti_1_header to display!\n", stderr);
return 1;
}
fprintf(stderr,
" nifti_1_header :\n"
" sizeof_hdr = %d\n"
" data_type[10] = ",
hp->sizeof_hdr);
print_hex_vals(hp->data_type, 10, stderr);
fprintf(stderr,
"\n"
" db_name[18] = ");
print_hex_vals(hp->db_name, 18, stderr);
fprintf(stderr,
"\n"
" extents = %d\n"
" session_error = %d\n"
" regular = 0x%x\n"
" dim_info = 0x%x\n",
hp->extents,
hp->session_error,
hp->regular,
hp->dim_info);
fprintf(stderr, " dim[8] =");
for (int c = 0; c < 8; c++)
{
fprintf(stderr, " %d", hp->dim[c]);
}
fprintf(stderr,
"\n"
" intent_p1 = %f\n"
" intent_p2 = %f\n"
" intent_p3 = %f\n"
" intent_code = %s\n"
" datatype = %d\n"
" bitpix = %d\n"
" slice_start = %d\n"
" pixdim[8] =",
hp->intent_p1,
hp->intent_p2,
hp->intent_p3,
str_intent(hp->intent_code),
hp->datatype,
hp->bitpix,
hp->slice_start);
// break pixdim over 2 lines
for (int c = 0; c < 4; c++)
{
fprintf(stderr, " %f", hp->pixdim[c]);
}
fprintf(stderr, "\n ");
for (int c = 4; c < 8; c++)
{
fprintf(stderr, " %f", hp->pixdim[c]);
}
fprintf(stderr,
"\n"
" vox_offset = %f\n"
" scl_slope = %f\n"
" scl_inter = %f\n"
" slice_end = %d\n"
" slice_code = %d\n"
" xyzt_units = 0x%x\n"
" cal_max = %f\n"
" cal_min = %f\n"
" slice_duration = %f\n"
" toffset = %f\n"
" glmax = %d\n"
" glmin = %d\n",
hp->vox_offset,
hp->scl_slope,
hp->scl_inter,
hp->slice_end,
hp->slice_code,
hp->xyzt_units,
hp->cal_max,
hp->cal_min,
hp->slice_duration,
hp->toffset,
hp->glmax,
hp->glmin);
fprintf(stderr,
" descrip = '%.80s'\n"
" aux_file = '%.24s'\n"
" qform_code = %d\n"
" sform_code = %d\n"
" quatern_b = %f\n"
" quatern_c = %f\n"
" quatern_d = %f\n"
" qoffset_x = %f\n"
" qoffset_y = %f\n"
" qoffset_z = %f\n"
" srow_x[4] = %f, %f, %f, %f\n"
" srow_y[4] = %f, %f, %f, %f\n"
" srow_z[4] = %f, %f, %f, %f\n"
" intent_name = '%-.16s'\n"
" magic = '%-.4s'\n",
hp->descrip,
hp->aux_file,
hp->qform_code,
hp->sform_code,
hp->quatern_b,
hp->quatern_c,
hp->quatern_d,
hp->qoffset_x,
hp->qoffset_y,
hp->qoffset_z,
hp->srow_x[0],
hp->srow_x[1],
hp->srow_x[2],
hp->srow_x[3],
hp->srow_y[0],
hp->srow_y[1],
hp->srow_y[2],
hp->srow_y[3],
hp->srow_z[0],
hp->srow_z[1],
hp->srow_z[2],
hp->srow_z[3],
hp->intent_name,
hp->magic);
fputs("-------------------------------------------------------\n", stderr);
fflush(stderr);
free(hp);
return 0;
}
static void
dumpdata(const void * x)
{
std::cerr << "----------------------" << std::endl;
const float * a = (const float *)x;
for (unsigned int i = 0; i < 24; i++) // t
{
std::cerr << a[i] << std::endl;
}
}
} // namespace
#else
# define dumpdata(x)
#endif // #if defined(ITK_USE_VERY_VERBOSE_NIFTI_DEBUGGING)
namespace
{
static unsigned int
str_xform2code(const std::string & codeName)
{
if (codeName == "NIFTI_XFORM_SCANNER_ANAT")
{
return NIFTI_XFORM_SCANNER_ANAT;
}
else if (codeName == "NIFTI_XFORM_ALIGNED_ANAT")
{
return NIFTI_XFORM_ALIGNED_ANAT;
}
else if (codeName == "NIFTI_XFORM_TALAIRACH")
{
return NIFTI_XFORM_TALAIRACH;
}
else if (codeName == "NIFTI_XFORM_MNI_152")
{
return NIFTI_XFORM_MNI_152;
}
// If no matches, then return UNKNOWN
return NIFTI_XFORM_UNKNOWN;
}
static const char *
str_xform(unsigned int xform)
{
switch (xform)
{
case NIFTI_XFORM_UNKNOWN:
return "NIFTI_XFORM_UNKNOWN";
case NIFTI_XFORM_SCANNER_ANAT:
return "NIFTI_XFORM_SCANNER_ANAT";
case NIFTI_XFORM_ALIGNED_ANAT:
return "NIFTI_XFORM_ALIGNED_ANAT";
case NIFTI_XFORM_TALAIRACH:
return "NIFTI_XFORM_TALAIRACH";
case NIFTI_XFORM_MNI_152:
return "NIFTI_XFORM_MNI_152";
}
return str_xform(NIFTI_XFORM_UNKNOWN);
}
} // namespace
// returns an ordering array for converting upper triangular symmetric matrix
// to lower triangular symmetric matrix
int *
UpperToLowerOrder(int dim)
{
auto ** mat = new int *[dim];
for (int i = 0; i < dim; i++)
{
mat[i] = new int[dim];
}
// fill in
int index(0);
for (int i = 0; i < dim; i++)
{
for (int j = i; j < dim; j++)
{
mat[i][j] = index;
mat[j][i] = index;
index++;
}
}
auto * rval = new int[index + 1];
int index2(0);
for (int i = 0; i < dim; i++)
{
for (int j = 0; j <= i; j++, index2++)
{
rval[index2] = mat[i][j];
}
}
rval[index2] = -1;
for (int i = 0; i < dim; i++)
{
delete[] mat[i];
}
delete[] mat;
return rval;
}
// returns an ordering array for converting lower triangular symmetric matrix
// to upper triangular symmetric matrix
int *
LowerToUpperOrder(int dim)
{
auto ** mat = new int *[dim];
for (int i = 0; i < dim; i++)
{
mat[i] = new int[dim];
}
// fill in
int index(0);
for (int i = 0; i < dim; i++)
{
for (int j = 0; j <= i; j++, index++)
{
mat[i][j] = index;
mat[j][i] = index;
}
}
auto * rval = new int[index + 1];
int index2(0);
for (int i = 0; i < dim; i++)
{
for (int j = i; j < dim; j++, index2++)
{
rval[index2] = mat[i][j];
}
}
rval[index2] = -1;
for (int i = 0; i < dim; i++)
{
delete[] mat[i];
}
delete[] mat;
return rval;
}
// compute the rank of the symmetric matrix from
// the count of the triangular matrix elements
int
SymMatDim(int count)
{
int dim = 0;
int row = 1;
while (count > 0)
{
count -= row;
dim++;
row++;
}
return dim;
}
ImageIORegion
NiftiImageIO ::GenerateStreamableReadRegionFromRequestedRegion(const ImageIORegion & requestedRegion) const
{
return requestedRegion;
}
// This internal proxy class provides a pointer-like interface to a nifti_image*, by supporting
// conversions between proxy and nifti_image pointer and arrow syntax (e.g., m_NiftiImage->data).
class NiftiImageIO::NiftiImageProxy
{
nifti_image * m_ptr;
public:
NiftiImageProxy(nifti_image * ptr)
: m_ptr(ptr)
{}
operator nifti_image *() { return m_ptr; }
nifti_image * operator->() { return m_ptr; }
};
NiftiImageIO::NiftiImageIO()
: m_NiftiImageHolder(new NiftiImageProxy(nullptr))
, m_NiftiImage(*m_NiftiImageHolder.get())
, m_LegacyAnalyze75Mode{ ITK_NIFTI_IO_ANALYZE_FLAVOR_DEFAULT }
{
this->SetNumberOfDimensions(3);
nifti_set_debug_level(0); // suppress error messages
const char * extensions[] = { ".nia", ".nii", ".nii.gz", ".hdr", ".img", ".img.gz" };
for (auto ext : extensions)
{
this->AddSupportedWriteExtension(ext);
this->AddSupportedReadExtension(ext);
}
}
NiftiImageIO::~NiftiImageIO()
{
nifti_image_free(this->m_NiftiImage);
}
void
NiftiImageIO ::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "LegacyAnalyze75Mode: " << this->m_LegacyAnalyze75Mode << std::endl;
}
bool
NiftiImageIO ::CanWriteFile(const char * FileNameToWrite)
{
const bool ValidFileNameFound = nifti_is_complete_filename(FileNameToWrite) > 0;
return ValidFileNameFound;
}
bool
NiftiImageIO::MustRescale() const
{
return std::abs(this->m_RescaleSlope) > std::numeric_limits<double>::epsilon() &&
(std::abs(this->m_RescaleSlope - 1.0) > std::numeric_limits<double>::epsilon() ||
std::abs(this->m_RescaleIntercept) > std::numeric_limits<double>::epsilon());
}
// Internal function to rescale pixel according to Rescale Slope/Intercept
template <typename TBuffer>
void
RescaleFunction(TBuffer * buffer, double slope, double intercept, size_t size)
{
for (size_t i = 0; i < size; i++)
{
double tmp = static_cast<double>(buffer[i]) * slope;
tmp += intercept;
buffer[i] = static_cast<TBuffer>(tmp);
}
}
template <typename PixelType>
void
CastCopy(float * to, const void * from, size_t pixelcount)
{
const auto * _from = static_cast<const PixelType *>(from);
for (size_t i = 0; i < pixelcount; i++)
{
to[i] = static_cast<float>(_from[i]);
}
}
void
NiftiImageIO::Read(void * buffer)
{
void * data = nullptr;
ImageIORegion regionToRead = this->GetIORegion();
ImageIORegion::SizeType size = regionToRead.GetSize();
ImageIORegion::IndexType start = regionToRead.GetIndex();
size_t numElts = 1;
int _origin[7];
int _size[7];
unsigned int i;
for (i = 0; i < start.size(); i++)
{
_origin[i] = static_cast<int>(start[i]);
_size[i] = static_cast<int>(size[i]);
numElts *= _size[i];
}
for (; i < 7; i++)
{
_origin[i] = 0;
_size[i] = 1;
}
unsigned int numComponents = this->GetNumberOfComponents();
//
// special case for images of vector pixels
if (numComponents > 1 && this->GetPixelType() != IOPixelEnum::COMPLEX)
{
// nifti always sticks vec size in dim 4, so have to shove
// other dims out of the way
_size[6] = _size[5];
_size[5] = _size[4];
// sizes = x y z t vecsize
_size[4] = numComponents;
}
// Free memory if any was occupied already (incase of re-using the IO filter).
nifti_image_free(this->m_NiftiImage);
//
// allocate nifti image...
this->m_NiftiImage = nifti_image_read(this->GetFileName(), false);
if (this->m_NiftiImage == nullptr)
{
itkExceptionMacro(<< "nifti_image_read (just header) failed for file: " << this->GetFileName());
}
//
// decide whether to read whole region or subregion, by stepping
// thru dims and comparing them to requested sizes
for (i = 0; i < this->GetNumberOfDimensions(); i++)
{
if (this->m_NiftiImage->dim[i + 1] != _size[i])
{
break;
}
}
// if all dimensions match requested size, just read in
// all data as a block
if (i == this->GetNumberOfDimensions())
{
if (nifti_image_load(this->m_NiftiImage) == -1)
{
itkExceptionMacro(<< "nifti_image_load failed for file: " << this->GetFileName());
}
data = this->m_NiftiImage->data;
}
else
{
// read in a subregion
if (nifti_read_subregion_image(this->m_NiftiImage, _origin, _size, &data) == -1)
{
itkExceptionMacro(<< "nifti_read_subregion_image failed for file: " << this->GetFileName());
}
}
unsigned int pixelSize = this->m_NiftiImage->nbyper;
//
// if we're going to have to rescale pixels, and the on-disk
// pixel type is different than the pixel type reported to
// ImageFileReader, we have to up-promote the data to float
// before doing the rescale.
//
if (this->MustRescale() && this->m_ComponentType != this->m_OnDiskComponentType)
{
pixelSize = static_cast<unsigned int>(this->GetNumberOfComponents()) * static_cast<unsigned int>(sizeof(float));
// allocate new buffer for floats. Malloc instead of new to
// be consistent with allocation used in niftilib
auto * _data = static_cast<float *>(malloc(numElts * sizeof(float)));
switch (this->m_OnDiskComponentType)
{
case IOComponentEnum::CHAR:
CastCopy<char>(_data, data, numElts);
break;
case IOComponentEnum::UCHAR:
CastCopy<unsigned char>(_data, data, numElts);
break;
case IOComponentEnum::SHORT:
CastCopy<short>(_data, data, numElts);
break;
case IOComponentEnum::USHORT:
CastCopy<unsigned short>(_data, data, numElts);
break;
case IOComponentEnum::INT:
CastCopy<int>(_data, data, numElts);
break;
case IOComponentEnum::UINT:
CastCopy<unsigned int>(_data, data, numElts);
break;
case IOComponentEnum::LONG:
CastCopy<long>(_data, data, numElts);
break;
case IOComponentEnum::ULONG:
CastCopy<unsigned long>(_data, data, numElts);
break;
case IOComponentEnum::LONGLONG:
CastCopy<long long>(_data, data, numElts);
break;
case IOComponentEnum::ULONGLONG:
CastCopy<unsigned long long>(_data, data, numElts);
break;
case IOComponentEnum::FLOAT:
itkExceptionMacro(<< "FLOAT pixels do not need Casting to float");
case IOComponentEnum::DOUBLE:
itkExceptionMacro(<< "DOUBLE pixels do not need Casting to float");
case IOComponentEnum::LDOUBLE:
itkExceptionMacro(<< "LDOUBLE pixels do not need Casting to float");
case IOComponentEnum::UNKNOWNCOMPONENTTYPE:
itkExceptionMacro(<< "Bad OnDiskComponentType UNKNOWNCOMPONENTTYPE");
}
//
// we're replacing the data pointer, so if it was allocated
// in nifti_read_subregion_image, free the old data here
if (data != this->m_NiftiImage->data)
{
free(data);
}
data = _data;
}
//
// if single or complex, nifti layout == itk layout
if (numComponents == 1 || this->GetPixelType() == IOPixelEnum::COMPLEX || this->GetPixelType() == IOPixelEnum::RGB ||
this->GetPixelType() == IOPixelEnum::RGBA)
{
const size_t NumBytes = numElts * pixelSize;
memcpy(buffer, data, NumBytes);
//
// if read_subregion was called it allocates a buffer that needs to be
// freed.
if (data != this->m_NiftiImage->data)
{
free(data);
}
}
else
{
// otherwise nifti is x y z t vec l m 0, itk is
// vec x y z t l m o
const auto * niftibuf = (const char *)data;
auto * itkbuf = (char *)buffer;
const size_t rowdist = this->m_NiftiImage->dim[1];
const size_t slicedist = rowdist * this->m_NiftiImage->dim[2];
const size_t volumedist = slicedist * this->m_NiftiImage->dim[3];
const size_t seriesdist = volumedist * this->m_NiftiImage->dim[4];
//
// as per ITK bug 0007485
// NIfTI is lower triangular, ITK is upper triangular.
int * vecOrder;
if (this->GetPixelType() == IOPixelEnum::DIFFUSIONTENSOR3D ||
this->GetPixelType() == IOPixelEnum::SYMMETRICSECONDRANKTENSOR)
{
// vecOrder = LowerToUpperOrder(SymMatDim(numComponents));
vecOrder = UpperToLowerOrder(SymMatDim(numComponents));
}
else
{
vecOrder = new int[numComponents];
for (i = 0; i < numComponents; i++)
{
vecOrder[i] = i;
}
}
for (int t = 0; t < this->m_NiftiImage->dim[4]; t++)
{
for (int z = 0; z < this->m_NiftiImage->dim[3]; z++)
{
for (int y = 0; y < this->m_NiftiImage->dim[2]; y++)
{
for (int x = 0; x < this->m_NiftiImage->dim[1]; x++)
{
for (unsigned int c = 0; c < numComponents; c++)
{
const size_t nifti_index =
(c * seriesdist + volumedist * t + slicedist * z + rowdist * y + x) * pixelSize;
const size_t itk_index =
((volumedist * t + slicedist * z + rowdist * y + x) * numComponents + vecOrder[c]) * pixelSize;
for (unsigned int b = 0; b < pixelSize; ++b)
{
itkbuf[itk_index + b] = niftibuf[nifti_index + b];
}
}
}
}
}
}
delete[] vecOrder;
dumpdata(data);
dumpdata(buffer);
// if read_subregion was called it allocates a buffer that needs to be
// freed.
if (data != this->m_NiftiImage->data)
{
free(data);
}
}
// If the scl_slope field is nonzero, then rescale each voxel value in the
// dataset.
// Complete description of can be found in nifti1.h under "DATA SCALING"
if (this->MustRescale())
{
switch (this->m_ComponentType)
{
case IOComponentEnum::CHAR:
RescaleFunction(static_cast<char *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::UCHAR:
RescaleFunction(static_cast<unsigned char *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::SHORT:
RescaleFunction(static_cast<short *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::USHORT:
RescaleFunction(static_cast<unsigned short *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::INT:
RescaleFunction(static_cast<int *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::UINT:
RescaleFunction(static_cast<unsigned int *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::LONG:
RescaleFunction(static_cast<long *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::ULONG:
RescaleFunction(static_cast<unsigned long *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::LONGLONG:
RescaleFunction(static_cast<long long *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::ULONGLONG:
RescaleFunction(
static_cast<unsigned long long *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::FLOAT:
RescaleFunction(static_cast<float *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
case IOComponentEnum::DOUBLE:
RescaleFunction(static_cast<double *>(buffer), this->m_RescaleSlope, this->m_RescaleIntercept, numElts);
break;
default:
if (this->GetPixelType() == IOPixelEnum::SCALAR)
{
itkExceptionMacro(<< "Datatype: " << this->GetComponentTypeAsString(this->m_ComponentType)
<< " not supported");
}
}
}
}
NiftiImageIO::FileType
NiftiImageIO::DetermineFileType(const char * FileNameToRead)
{
// is_nifti_file returns
// == 2 for a nifti file (header+data in 2 files)
// == 1 for a nifti file (header+data in 1 file)
// == 0 for an analyze 7.5 file,
// == -1 for an error,
const int imageFTYPE = is_nifti_file(FileNameToRead);
return static_cast<NiftiImageIO::FileType>(imageFTYPE);
}
// This method will only test if the header looks like an
// Nifti Header. Some code is redundant with ReadImageInformation
// a StateMachine could provide a better implementation
bool
NiftiImageIO ::CanReadFile(const char * FileNameToRead)
{
// is_nifti_file returns
// == 2 for a nifti file (header+data in 2 files)
// == 1 for a nifti file (header+data in 1 file)
// == 0 for an analyze 7.5 file,
// == -1 for an error,
const int imageFTYPE = is_nifti_file(FileNameToRead);
if (imageFTYPE > 0)
{
return true;
}
else if (imageFTYPE == 0 && (this->GetLegacyAnalyze75Mode() != Analyze75Flavor::AnalyzeReject))
{
return true;
}
return false;
}
// This method adds information to the metadata dictionary.
void
NiftiImageIO::SetImageIOMetadataFromNIfTI()
{
auto & nim = this->m_NiftiImage;
// Encapsulate as much information as possible.
MetaDataDictionary & thisDic = this->GetMetaDataDictionary();
// Necessary to clear dict if ImageIO object is re-used
thisDic.Clear();
std::ostringstream nifti_type;
nifti_type << nim->nifti_type;
EncapsulateMetaData<std::string>(thisDic, "nifti_type", nifti_type.str());
std::ostringstream dim_info;
dim_info << FPS_INTO_DIM_INFO(nim->freq_dim, nim->phase_dim, nim->slice_dim);
EncapsulateMetaData<std::string>(thisDic, "dim_info", dim_info.str());
for (int idx = 0; idx < 8; idx++)
{
std::ostringstream dim;
dim << nim->dim[idx];
std::ostringstream dimKey;
dimKey << "dim[" << idx << "]";
EncapsulateMetaData<std::string>(thisDic, dimKey.str(), dim.str());
}
std::ostringstream intent_p1;
intent_p1 << nim->intent_p1;
EncapsulateMetaData<std::string>(thisDic, "intent_p1", intent_p1.str());
std::ostringstream intent_p2;
intent_p2 << nim->intent_p2;
EncapsulateMetaData<std::string>(thisDic, "intent_p2", intent_p2.str());
std::ostringstream intent_p3;
intent_p3 << nim->intent_p3;
EncapsulateMetaData<std::string>(thisDic, "intent_p3", intent_p3.str());
std::ostringstream intent_code;
intent_code << nim->intent_code;
EncapsulateMetaData<std::string>(thisDic, "intent_code", intent_code.str());
std::ostringstream datatype;
datatype << nim->datatype;
EncapsulateMetaData<std::string>(thisDic, "datatype", datatype.str());
std::ostringstream bitpix;
bitpix << (8 * nim->nbyper);
EncapsulateMetaData<std::string>(thisDic, "bitpix", bitpix.str());
std::ostringstream slice_start;
slice_start << nim->slice_start;
EncapsulateMetaData<std::string>(thisDic, "slice_start", slice_start.str());
for (int idx = 0; idx < 8; idx++)
{
std::ostringstream pixdim;
pixdim << nim->pixdim[idx];
std::ostringstream pixdimKey;
pixdimKey << "pixdim[" << idx << "]";
EncapsulateMetaData<std::string>(thisDic, pixdimKey.str(), pixdim.str());
}
std::ostringstream vox_offset;
vox_offset << nim->iname_offset;
EncapsulateMetaData<std::string>(thisDic, "vox_offset", vox_offset.str());
std::ostringstream scl_slope;
scl_slope << nim->scl_slope;
EncapsulateMetaData<std::string>(thisDic, "scl_slope", scl_slope.str());
std::ostringstream scl_inter;
scl_inter << nim->scl_inter;
EncapsulateMetaData<std::string>(thisDic, "scl_inter", scl_inter.str());
std::ostringstream slice_end;
slice_end << nim->slice_end;
EncapsulateMetaData<std::string>(thisDic, "slice_end", slice_end.str());
std::ostringstream slice_code;
slice_code << nim->slice_code;
EncapsulateMetaData<std::string>(thisDic, "slice_code", slice_code.str());
std::ostringstream xyzt_units;
xyzt_units << SPACE_TIME_TO_XYZT(nim->xyz_units, nim->time_units);
EncapsulateMetaData<std::string>(thisDic, "xyzt_units", xyzt_units.str());
std::ostringstream cal_max;
cal_max << nim->cal_max;
EncapsulateMetaData<std::string>(thisDic, "cal_max", cal_max.str());
std::ostringstream cal_min;
cal_min << nim->cal_min;
EncapsulateMetaData<std::string>(thisDic, "cal_min", cal_min.str());
std::ostringstream slice_duration;
slice_duration << nim->slice_duration;
EncapsulateMetaData<std::string>(thisDic, "slice_duration", slice_duration.str());
std::ostringstream toffset;
toffset << nim->toffset;
EncapsulateMetaData<std::string>(thisDic, "toffset", toffset.str());
std::ostringstream descrip;
descrip << nim->descrip;
EncapsulateMetaData<std::string>(thisDic, "descrip", descrip.str());
std::ostringstream aux_file;
aux_file << nim->aux_file;
EncapsulateMetaData<std::string>(thisDic, "aux_file", aux_file.str());
std::ostringstream qform_code;
qform_code << nim->qform_code;
EncapsulateMetaData<std::string>(thisDic, "qform_code", qform_code.str());
EncapsulateMetaData<std::string>(thisDic, "qform_code_name", std::string(str_xform(nim->qform_code)));
std::ostringstream sform_code;
sform_code << nim->sform_code;
EncapsulateMetaData<std::string>(thisDic, "sform_code", sform_code.str());
EncapsulateMetaData<std::string>(thisDic, "sform_code_name", std::string(str_xform(nim->sform_code)));
std::ostringstream quatern_b;
quatern_b << nim->quatern_b;
EncapsulateMetaData<std::string>(thisDic, "quatern_b", quatern_b.str());
std::ostringstream quatern_c;
quatern_c << nim->quatern_c;
EncapsulateMetaData<std::string>(thisDic, "quatern_c", quatern_c.str());
std::ostringstream quatern_d;
quatern_d << nim->quatern_d;
EncapsulateMetaData<std::string>(thisDic, "quatern_d", quatern_d.str());
std::ostringstream qoffset_x;
qoffset_x << nim->qoffset_x;
EncapsulateMetaData<std::string>(thisDic, "qoffset_x", qoffset_x.str());
std::ostringstream qoffset_y;
qoffset_y << nim->qoffset_y;
EncapsulateMetaData<std::string>(thisDic, "qoffset_y", qoffset_y.str());
std::ostringstream qoffset_z;
qoffset_z << nim->qoffset_z;
EncapsulateMetaData<std::string>(thisDic, "qoffset_z", qoffset_z.str());
std::ostringstream srow_x;
srow_x << nim->sto_xyz.m[0][0] << " " << nim->sto_xyz.m[0][1] << " " << nim->sto_xyz.m[0][2] << " "
<< nim->sto_xyz.m[0][3];
EncapsulateMetaData<std::string>(thisDic, "srow_x", srow_x.str());
std::ostringstream srow_y;
srow_y << nim->sto_xyz.m[1][0] << " " << nim->sto_xyz.m[1][1] << " " << nim->sto_xyz.m[1][2] << " "
<< nim->sto_xyz.m[1][3];
EncapsulateMetaData<std::string>(thisDic, "srow_y", srow_y.str());
std::ostringstream srow_z;
srow_z << nim->sto_xyz.m[2][0] << " " << nim->sto_xyz.m[2][1] << " " << nim->sto_xyz.m[2][2] << " "
<< nim->sto_xyz.m[2][3];
EncapsulateMetaData<std::string>(thisDic, "srow_z", srow_z.str());
std::ostringstream intent_name;
intent_name << nim->intent_name;
EncapsulateMetaData<std::string>(thisDic, "intent_name", intent_name.str());
}
void
NiftiImageIO ::ReadImageInformation()
{
const int image_FTYPE = is_nifti_file(this->GetFileName());
if (image_FTYPE == 0)
{
if (this->GetLegacyAnalyze75Mode() == Analyze75Flavor::AnalyzeReject)