-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathvtkNIFTIReader.cxx
1356 lines (1204 loc) · 36.8 KB
/
vtkNIFTIReader.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
/*=========================================================================
Program: Visualization Toolkit
Module: vtkNIFTIReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkNIFTIReader.h"
#include "vtkObjectFactory.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkDataArray.h"
#include "vtkByteSwap.h"
#include "vtkMatrix4x4.h"
#include "vtkMath.h"
#include "vtkCommand.h"
#include "vtkErrorCode.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkStringArray.h"
#include "vtkVersion.h"
#ifdef _WIN32
// To allow use of wchar_t paths on Windows
#include "vtkDICOMFilePath.h"
#endif
#include "vtkDICOMFile.h"
// Header for NIFTI
#include "vtkNIFTIHeader.h"
#include "vtkNIFTIPrivate.h"
#include "vtkDICOMConfig.h"
// Header for zlib
#ifdef DICOM_USE_VTKZLIB
#include "vtk_zlib.h"
#else
#include "zlib.h"
#endif
#include <ctype.h>
#include <string.h>
#include <string>
#ifdef _WIN32
// To allow use of wchar_t paths on Windows
#include "vtkDICOMFilePath.h"
#if VTK_MAJOR_VERSION >= 7
#ifdef gzopen
#undef gzopen
#endif
#define gzopen gzopen_w
#endif
#endif
vtkStandardNewMacro(vtkNIFTIReader);
//----------------------------------------------------------------------------
vtkNIFTIReader::vtkNIFTIReader()
{
for (int i = 0; i < 8; i++)
{
this->Dim[i] = 0;
}
for (int i = 0; i < 8; i++)
{
this->PixDim[i] = 1.0;
}
this->TimeAsVector = 0;
this->RescaleSlope = 1.0;
this->RescaleIntercept = 0.0;
this->QFac = 1.0;
this->QFormMatrix = nullptr;
this->SFormMatrix = nullptr;
this->NIFTIHeader = nullptr;
this->PlanarRGB = false;
}
//----------------------------------------------------------------------------
vtkNIFTIReader::~vtkNIFTIReader()
{
if (this->QFormMatrix)
{
this->QFormMatrix->Delete();
}
if (this->SFormMatrix)
{
this->SFormMatrix->Delete();
}
if (this->NIFTIHeader)
{
this->NIFTIHeader->Delete();
}
}
//----------------------------------------------------------------------------
vtkNIFTIHeader *vtkNIFTIReader::GetNIFTIHeader()
{
if (!this->NIFTIHeader)
{
this->NIFTIHeader = vtkNIFTIHeader::New();
}
return this->NIFTIHeader;
}
//----------------------------------------------------------------------------
void vtkNIFTIReader::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "TimeAsVector: "
<< (this->TimeAsVector ? "On\n" : "Off\n");
os << indent << "TimeDimension: " << this->GetTimeDimension() << "\n";
os << indent << "TimeSpacing: " << this->GetTimeSpacing() << "\n";
os << indent << "RescaleSlope: " << this->RescaleSlope << "\n";
os << indent << "RescaleIntercept: " << this->RescaleIntercept << "\n";
os << indent << "QFac: " << this->QFac << "\n";
os << indent << "QFormMatrix:";
if (this->QFormMatrix)
{
double mat[16];
vtkMatrix4x4::DeepCopy(mat, this->QFormMatrix);
for (int i = 0; i < 16; i++)
{
os << " " << mat[i];
}
os << "\n";
}
else
{
os << " (none)\n";
}
os << indent << "SFormMatrix:";
if (this->SFormMatrix)
{
double mat[16];
vtkMatrix4x4::DeepCopy(mat, this->SFormMatrix);
for (int i = 0; i < 16; i++)
{
os << " " << mat[i];
}
os << "\n";
}
else
{
os << " (none)\n";
}
os << indent << "NIFTIHeader:" << (this->NIFTIHeader ? "\n" : " (none)\n");
os << indent << "PlanarRGB: " << (this->PlanarRGB ? "On\n" : "Off\n");
}
//----------------------------------------------------------------------------
bool vtkNIFTIReader::CheckExtension(
const char *filename, const char *ext)
{
if (strlen(ext) == 4 && ext[0] == '.')
{
size_t n = strlen(filename);
if (n > 2 && filename[n-3] == '.' &&
tolower(filename[n-2]) == 'g' &&
tolower(filename[n-1]) == 'z')
{
n -= 3;
}
if (n > 3 && filename[n-4] == '.' &&
tolower(filename[n-3]) == tolower(ext[1]) &&
tolower(filename[n-2]) == tolower(ext[2]) &&
tolower(filename[n-1]) == tolower(ext[3]))
{
return true;
}
}
return false;
}
//----------------------------------------------------------------------------
char *vtkNIFTIReader::ReplaceExtension(
const char *filename, const char *ext1, const char *ext2)
{
char *newname = nullptr;
if (strlen(ext1) == 4 && ext1[0] == '.' &&
strlen(ext2) == 4 && ext2[0] == '.')
{
size_t n = strlen(filename);
size_t m = n;
newname = new char[n+4];
strcpy(newname, filename);
// check for trailing .gz
if (n > 2 && filename[n-3] == '.' &&
tolower(filename[n-2]) == 'g' &&
tolower(filename[n-1]) == 'z')
{
m = n - 3;
}
if (vtkNIFTIReader::CheckExtension(filename, ext1))
{
// replace the extension
if (isupper(filename[m-3]))
{
newname[m-3] = toupper(ext2[1]);
newname[m-2] = toupper(ext2[2]);
newname[m-1] = toupper(ext2[3]);
}
else
{
newname[m-3] = tolower(ext2[1]);
newname[m-2] = tolower(ext2[2]);
newname[m-1] = tolower(ext2[3]);
}
}
// existence of file
for (int i = 0; i < 2; i++)
{
int code = vtkDICOMFile::Access(newname, vtkDICOMFile::In);
if (code != vtkDICOMFile::FileNotFound)
{
return newname;
}
if (i == 0)
{
if (m < n)
{
// try again without the ".gz"
newname[m] = '\0';
n = m;
}
else
{
// try again with the ".gz"
newname[m] = '.';
newname[m+1] = (isupper(newname[m-3]) ? 'G' : 'g');
newname[m+2] = (isupper(newname[m-3]) ? 'Z' : 'z');
newname[m+3] = '\0';
}
}
}
delete [] newname;
newname = nullptr;
}
return newname;
}
//----------------------------------------------------------------------------
int vtkNIFTIReader::CheckNIFTIVersion(const nifti_1_header *hdr)
{
int version = 0;
// Check for NIFTIv2. The NIFTIv2 magic number is stored where
// the data_type appears in the NIFTIv1 header.
if (hdr->data_type[0] == 'n' &&
(hdr->data_type[1] == '+' || hdr->data_type[1] == 'i') &&
(hdr->data_type[2] >= '2' && hdr->data_type[2] <= '9') &&
hdr->data_type[3] == '\0')
{
version = (hdr->data_type[2] - '0');
if (hdr->data_type[4] != '\r' ||
hdr->data_type[5] != '\n' ||
hdr->data_type[6] != '\032' ||
hdr->data_type[7] != '\n')
{
// Indicate that file was corrupted by newline conversion
version = -version;
}
}
// Check for NIFTIv1
else if (hdr->magic[0] == 'n' &&
(hdr->magic[1] == '+' || hdr->magic[1] == 'i') &&
hdr->magic[2] == '1' &&
hdr->magic[3] == '\0')
{
version = 1;
}
return version;
}
//----------------------------------------------------------------------------
bool vtkNIFTIReader::CheckAnalyzeHeader(const nifti_1_header *hdr)
{
if (hdr->sizeof_hdr == 348 || // Analyze 7.5 header size
hdr->sizeof_hdr == 1543569408) // byte-swapped 348
{
return true;
}
return false;
}
//----------------------------------------------------------------------------
int vtkNIFTIReader::CanReadFile(const char *filename)
{
vtkDebugMacro("Opening NIFTI file " << filename);
char *hdrname = vtkNIFTIReader::ReplaceExtension(
filename, ".img", ".hdr");
if (hdrname == nullptr)
{
return 0;
}
#ifdef _WIN32
vtkDICOMFilePath fp(hdrname);
#if VTK_MAJOR_VERSION < 7
// convert to the local character set
const char *uhdrname = fp.Local();
#else
// use wide character
const wchar_t *uhdrname = fp.Wide();
#endif
#else
const char *uhdrname = hdrname;
#endif
// try opening file
gzFile file = gzopen(uhdrname, "rb");
delete [] hdrname;
if (!file)
{
return 0;
}
// read and check the header
bool canRead = false;
nifti_1_header hdr;
int hsize = vtkNIFTIHeader::Nifti1HeaderSize; // nifti_1 header size
int rsize = gzread(file, &hdr, hsize);
if (rsize == hsize)
{
int version = vtkNIFTIReader::CheckNIFTIVersion(&hdr);
if (version > 0)
{
// NIFTI file
canRead = true;
}
else if (version == 0)
{
// Analyze 7.5 file
canRead = vtkNIFTIReader::CheckAnalyzeHeader(&hdr);
}
}
gzclose(file);
return canRead;
}
//----------------------------------------------------------------------------
int vtkNIFTIReader::RequestInformation(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector)
{
// Clear the error indicator.
this->SetErrorCode(vtkErrorCode::NoError);
// Create the header object
if (!this->NIFTIHeader)
{
this->NIFTIHeader = vtkNIFTIHeader::New();
}
// default byte order is native byte order
#ifdef VTK_WORDS_BIGENDIAN
bool isLittleEndian = false;
#else
bool isLittleEndian = true;
#endif
const char *filename = nullptr;
char *hdrname = nullptr;
if (this->FileNames)
{
vtkIdType n = this->FileNames->GetNumberOfValues();
int headers = 0;
for (int i = 0; i < 2; i++)
{
filename = this->FileNames->GetValue(i).c_str();
// this checks for .hdr and .hdr.gz, case insensitive
if (vtkNIFTIReader::CheckExtension(filename, ".hdr"))
{
headers++;
hdrname = new char[strlen(filename) + 1];
strcpy(hdrname, filename);
}
}
if (n != 2 || headers != 1)
{
vtkErrorMacro("There must be two files and one must be a .hdr file.");
return 0;
}
}
else
{
filename = this->GetFileName();
}
if (filename == nullptr)
{
vtkErrorMacro("A FileName must be provided");
this->SetErrorCode(vtkErrorCode::NoFileNameError);
return 0;
}
if (hdrname == nullptr)
{
hdrname = vtkNIFTIReader::ReplaceExtension(
filename, ".img", ".hdr");
}
if (hdrname == nullptr)
{
vtkErrorMacro("Unable to locate header for file " << filename);
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
vtkDebugMacro("Opening NIFTI file " << hdrname);
#ifdef _WIN32
vtkDICOMFilePath fph(hdrname);
#if VTK_MAJOR_VERSION < 7
// convert to the local character set
const char *uhdrname = fph.Local();
#else
// use wide character
const wchar_t *uhdrname = fph.Wide();
#endif
#else
const char *uhdrname = hdrname;
#endif
// try opening file
gzFile file = nullptr;
if (uhdrname)
{
file = gzopen(uhdrname, "rb");
}
if (!file)
{
vtkErrorMacro("Cannot open file " << hdrname);
delete [] hdrname;
this->SetErrorCode(vtkErrorCode::CannotOpenFileError);
return 0;
}
// read and check the header
bool canRead = false;
int niftiVersion = 0;
nifti_1_header *hdr1 = new nifti_1_header;
nifti_2_header hdr2obj;
nifti_2_header *hdr2 = &hdr2obj;
const int hsize = vtkNIFTIHeader::Nifti1HeaderSize;
int rsize = gzread(file, hdr1, hsize);
if (rsize == hsize)
{
niftiVersion = vtkNIFTIReader::CheckNIFTIVersion(hdr1);
if (niftiVersion >= 2)
{
// the header was a NIFTIv2 header
const int h2size = vtkNIFTIHeader::Nifti2HeaderSize;
// copy what was read into the NIFTIv1 header
memcpy(hdr2, hdr1, hsize);
// read the remainder of the NIFTIv2 header
rsize = gzread(file, reinterpret_cast<char *>(hdr2)+hsize, h2size-hsize);
if (rsize == h2size-hsize)
{
canRead = true;
}
}
else if (niftiVersion == 1)
{
// the header was a NIFTIv1 header
canRead = true;
}
else if (niftiVersion == 0)
{
// Analyze 7.5 file
canRead = vtkNIFTIReader::CheckAnalyzeHeader(hdr1);
}
}
if (canRead)
{
if (niftiVersion >= 2)
{
if (NIFTI_NEEDS_SWAP(*hdr2))
{
vtkNIFTIHeader::ByteSwapHeader(hdr2);
isLittleEndian = !isLittleEndian;
}
this->NIFTIHeader->SetHeader(hdr2);
}
else
{
if (NIFTI_NEEDS_SWAP(*hdr1))
{
vtkNIFTIHeader::ByteSwapHeader(hdr1);
isLittleEndian = !isLittleEndian;
}
// convert NIFTIv1 header into NIFTIv2
this->NIFTIHeader->SetHeader(hdr1);
this->NIFTIHeader->GetHeader(hdr2);
}
}
gzclose(file);
// delete the NIFTIv1 header, use the NIFTIv2 header
delete hdr1;
hdr1 = nullptr;
if (!canRead)
{
const char *message = (niftiVersion <= -2 ?
"NIfTI header has newline corruption " :
"Bad NIfTI header in file ");
vtkErrorMacro(<< message << hdrname);
this->SetErrorCode(vtkErrorCode::UnrecognizedFileTypeError);
delete [] hdrname;
return 0;
}
delete [] hdrname;
// number of dimensions
int ndim = hdr2->dim[0];
if (ndim < 0 || ndim > 7)
{
vtkErrorMacro("NIfTI image has illegal ndim of " << ndim);
this->SetErrorCode(vtkErrorCode::FileFormatError);
return 0;
}
// sanity checks
for (int i = 0; i < 8; i++)
{
// voxel spacing cannot be zero
if (hdr2->pixdim[i] == 0)
{
hdr2->pixdim[i] = 1.0;
}
if (i > ndim)
{
// dimensions greater than ndim have size of 1
hdr2->dim[i] = 1;
}
else if (hdr2->dim[i] < 0)
{
vtkErrorMacro("NIfTI image dimension " << i << " is negative");
this->SetErrorCode(vtkErrorCode::FileFormatError);
return 0;
}
else if ((hdr2->dim[i] & 0x7fffffff) != hdr2->dim[i])
{
// dimension does not fit in signed int
vtkErrorMacro("NIfTI image dimension " << i << " is larger than int32");
this->SetErrorCode(vtkErrorCode::FileFormatError);
return 0;
}
}
if (niftiVersion > 0)
{
// pass rescale info to user (do not rescale in the reader)
this->RescaleSlope = hdr2->scl_slope;
this->RescaleIntercept = hdr2->scl_inter;
}
else
{
// rescale information not available for Analyze 7.5
this->RescaleSlope = 1.0;
this->RescaleIntercept = 0.0;
}
// header might be extended, vox_offset says where data starts
this->SetHeaderSize(static_cast<unsigned long>(hdr2->vox_offset));
// endianness of data
if (isLittleEndian)
{
this->SetDataByteOrderToLittleEndian();
}
else
{
this->SetDataByteOrderToBigEndian();
}
// NIFTI images are stored in a single file, not one file per slice
this->SetFileDimensionality(3);
// NIFTI uses a lower-left-hand origin
this->FileLowerLeftOn();
// dim
this->SetDataExtent(0, hdr2->dim[1]-1,
0, hdr2->dim[2]-1,
0, hdr2->dim[3]-1);
// pixdim
this->SetDataSpacing(hdr2->pixdim[1],
hdr2->pixdim[2],
hdr2->pixdim[3]);
// offset is part of the transform, so set origin to zero
this->SetDataOrigin(0.0, 0.0, 0.0);
// map the NIFTI type to a VTK type and number of components
static const int typeMap[][3] = {
{ NIFTI_TYPE_INT8, VTK_TYPE_INT8, 1},
{ NIFTI_TYPE_UINT8, VTK_TYPE_UINT8, 1 },
{ NIFTI_TYPE_INT16, VTK_TYPE_INT16, 1 },
{ NIFTI_TYPE_UINT16, VTK_TYPE_UINT16, 1 },
{ NIFTI_TYPE_INT32, VTK_TYPE_INT32, 1 },
{ NIFTI_TYPE_UINT32, VTK_TYPE_UINT32, 1 },
{ NIFTI_TYPE_INT64, VTK_TYPE_INT64, 1 },
{ NIFTI_TYPE_UINT64, VTK_TYPE_UINT64, 1 },
{ NIFTI_TYPE_FLOAT32, VTK_TYPE_FLOAT32, 1 },
{ NIFTI_TYPE_FLOAT64, VTK_TYPE_FLOAT64, 1 },
{ NIFTI_TYPE_COMPLEX64, VTK_TYPE_FLOAT32, 2 },
{ NIFTI_TYPE_COMPLEX128, VTK_TYPE_FLOAT64, 2 },
{ NIFTI_TYPE_RGB24, VTK_TYPE_UINT8, 3 },
{ NIFTI_TYPE_RGBA32, VTK_TYPE_UINT8, 4 },
{ 0, 0, 0 }
};
int scalarType = 0;
int numComponents = 0;
for (int i = 0; typeMap[i][2] != 0; i++)
{
if (hdr2->datatype == typeMap[i][0])
{
scalarType = typeMap[i][1];
numComponents = typeMap[i][2];
break;
}
}
// if loop finished without finding a match
if (numComponents == 0)
{
vtkErrorMacro("Unrecognized NIFTI data type: " << hdr2->datatype);
this->SetErrorCode(vtkErrorCode::FileFormatError);
return 0;
}
// vector planes become vector components
if (ndim >= 5)
{
numComponents *= hdr2->dim[5];
}
if (ndim >= 4 && this->TimeAsVector)
{
numComponents *= hdr2->dim[4];
}
this->SetDataScalarType(scalarType);
this->SetNumberOfScalarComponents(numComponents);
// Set the output information.
vtkInformation* outInfo = outputVector->GetInformationObject(0);
vtkDataObject::SetPointDataActiveScalarInfo(
outInfo, this->DataScalarType, this->NumberOfScalarComponents);
outInfo->Set(vtkDataObject::SPACING(), this->DataSpacing, 3);
outInfo->Set(vtkDataObject::ORIGIN(), this->DataOrigin, 3);
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(),
this->DataExtent, 6);
// copy dim for when RequestData is called
for (int j = 0; j < 8; j++)
{
this->Dim[j] = hdr2->dim[j];
this->PixDim[j] = hdr2->pixdim[j];
}
// === Image Orientation in NIfTI files ===
//
// The vtkImageData class does not provide a way of storing image
// orientation. So when we read a NIFTI file, we should also provide
// the user with a 4x4 matrix that can transform VTK's data coordinates
// into NIFTI's intended coordinate system for the image. NIFTI defines
// these coordinate systems as:
// 1) NIFTI_XFORM_SCANNER_ANAT - coordinate system of the imaging device
// 2) NIFTI_XFORM_ALIGNED_ANAT - result of registration to another image
// 3) NIFTI_XFORM_TALAIRACH - a brain-specific coordinate system
// 4) NIFTI_XFORM_MNI_152 - a similar brain-specific coordinate system
//
// NIFTI images can store orientation in two ways:
// 1) via a quaternion (orientation and offset, i.e. rigid-body)
// 2) via a matrix (used to store e.g. the results of registration)
//
// A NIFTI file can have both a quaternion (qform) and matrix (sform)
// stored in the same file. The NIFTI documentation recommends that
// the qform be used to record the "scanner anatomical" coordinates
// and that the sform, if present, be used to define a secondary
// coordinate system, e.g. a coordinate system derived through
// registration to a template.
//
// -- Quaternion Representation --
//
// If the "quaternion" form is used, then the following equation
// defines the transformation from voxel indices to NIFTI's world
// coordinates, where R is the rotation matrix computed from the
// quaternion components:
//
// [ x ] [ R11 R12 R13 ] [ pixdim[1] * i ] [ qoffset_x ]
// [ y ] = [ R21 R22 R23 ] [ pixdim[2] * j ] + [ qoffset_y ]
// [ z ] [ R31 R32 R33 ] [ pixdim[3] * k * qfac ] [ qoffset_z ]
//
// qfac is stored in pixdim[0], if it is equal to -1 then the slices
// are stacked in reverse: VTK will have to reorder the slices in order
// to maintain a right-handed coordinate transformation between indices
// and coordinates.
//
// Let's call VTK data coordinates X,Y,Z to distinguish them from
// the NIFTI coordinates x,y,z. The relationship between X,Y,Z and
// x,y,z is expressed by a 4x4 matrix M:
//
// [ x ] [ M11 M12 M13 M14 ] [ X ]
// [ y ] = [ M21 M22 M23 M24 ] [ Y ]
// [ z ] [ M31 M32 M33 M34 ] [ Z ]
// [ 1 ] [ 0 0 0 1 ] [ 1 ]
//
// where the VTK data coordinates X,Y,Z are related to the
// VTK structured coordinates IJK (i.e. point indices) by:
//
// X = I*Spacing[0] + Origin[0]
// Y = J*Spacing[1] + Origin[1]
// Z = K*Spacing[2] + Origin[2]
//
// Now let's consider: when we read a NIFTI image, how should we set
// the Spacing, the Origin, and the matrix M? Let's consider the
// cases:
//
// 1) If there is no qform, then R is identity and qoffset is zero,
// and qfac will be 1 (never -1). So:
// I,J,K = i,j,k, Spacing = pixdim, Origin = 0, M = Identity
//
// 2) If there is a qform, and qfac is 1, then:
//
// I,J,K = i,j,k (i.e. voxel order in VTK same as in NIFTI)
//
// Spacing[0] = pixdim[1]
// Spacing[1] = pixdim[2]
// Spacing[2] = pixdim[3]
//
// Origin[0] = 0.0
// Origin[1] = 0.0
// Origin[2] = 0.0
//
// [ R11 R12 R13 qoffset_x ]
// M = [ R21 R22 R23 qoffset_y ]
// [ R31 R32 R33 qoffset_z ]
// [ 0 0 0 1 ]
//
// Note that we cannot store qoffset in the origin. That would
// be mathematically incorrect. It would only give us the right
// offset when R is the identity matrix.
//
// 3) If there is a qform and qfac is -1, then the situation is more
// complicated. We have three choices, each of which is a compromise:
// a) we can use Spacing[2] = qfac*pixdim[3], i.e. use a negative
// slice spacing, which might cause some VTK algorithms to
// misbehave (the VTK tests only use images with positive spacing).
// b) we can use M13 = -R13, M23 = -R23, M33 = -R33 i.e. introduce
// a flip into the matrix, which is very bad for VTK rendering
// algorithms and should definitely be avoided.
// c) we can reverse the order of the slices in VTK relative to
// NIFTI, which allows us to preserve positive spacing and retain
// a well-behaved rotation matrix, by using these equations:
//
// K = number_of_slices - k - 1
//
// M14 = qoffset_x - (number_of_slices - 1)*pixdim[3]*R13
// M24 = qoffset_y - (number_of_slices - 1)*pixdim[3]*R23
// M34 = qoffset_z - (number_of_slices - 1)*pixdim[3]*R33
//
// This will give us data that will be well-behaved in VTK, at
// the expense of making VTK slice numbers not match with
// the original NIFTI slice numbers. NIFTI slice 0 will become
// VTK slice N-1, and the order will be reversed.
//
// -- Matrix Representation --
//
// If the "matrix" form is used, then pixdim[] is ignored, and the
// voxel spacing is implicitly stored in the matrix. In addition,
// the matrix may have a negative determinant, there is no "qfac"
// flip-factor as there is in the quaternion representation.
//
// Let S be the matrix stored in the NIFTI header, and let M be our
// desired coordinate transformation from VTK data coordinates X,Y,Z
// to NIFTI data coordinates x,y,z (see discussion above for more
// information). Let's consider the cases where the determinant
// is positive, or negative.
//
// 1) If the determinant is positive, we will factor the spacing
// (but not the origin) out of the matrix.
//
// Spacing[0] = pixdim[1]
// Spacing[1] = pixdim[2]
// Spacing[2] = pixdim[3]
//
// Origin[0] = 0.0
// Origin[1] = 0.0
// Origin[2] = 0.0
//
// [ S11/pixdim[1] S12/pixdim[2] S13/pixdim[3] S14 ]
// M = [ S21/pixdim[1] S22/pixdim[2] S23/pixdim[3] S24 ]
// [ S31/pixdim[1] S32/pixdim[2] S33/pixdim[3] S34 ]
// [ 0 0 0 1 ]
//
// 2) If the determinant is negative, then we face the same choices
// as when qfac is -1 for the quaternion transformation. We can:
// a) use a negative Z spacing and multiply the 3rd column of M by -1
// b) keep the matrix as is (with a negative determinant)
// c) reorder the slices, multiply the 3rd column by -1, and adjust
// the 4th column of the matrix:
//
// M14 = S14 + (number_of_slices - 1)*S13
// M24 = S24 + (number_of_slices - 1)*S23
// M34 = S34 + (number_of_slices - 1)*S33
//
// The third choice will provide a VTK image that has positive
// spacing and a matrix with a positive determinant.
//
// -- Analyze 7.5 Orientation --
//
// This reader provides only bare-bones backwards compatibility with
// the Analyze 7.5 file header. We do not orient these files.
// Initialize
this->QFac = 1.0;
if (this->QFormMatrix)
{
this->QFormMatrix->Delete();
this->QFormMatrix = nullptr;
}
if (this->SFormMatrix)
{
this->SFormMatrix->Delete();
this->SFormMatrix = nullptr;
}
// Set the QFormMatrix from the quaternion data in the header.
// See the long discussion above for more information.
if (niftiVersion > 0 && hdr2->qform_code > 0)
{
double mmat[16];
double rmat[3][3];
double quat[4];
quat[1] = hdr2->quatern_b;
quat[2] = hdr2->quatern_c;
quat[3] = hdr2->quatern_d;
quat[0] = 1.0 - quat[1]*quat[1] - quat[2]*quat[2] - quat[3]*quat[3];
if (quat[0] > 0.0)
{
quat[0] = sqrt(quat[0]);
}
else
{
quat[0] = 0.0;
}
vtkMath::QuaternionToMatrix3x3(quat, rmat);
// If any matrix values are close to zero, then they should actually
// be zero but aren't due to limited numerical precision in the
// quaternion-to-matrix conversion.
const double tol = 2.384185791015625e-07; // 2**-22
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (fabs(rmat[i][j]) < tol)
{
rmat[i][j] = 0.0;
}
}
vtkMath::Normalize(rmat[i]);
}
// first row
mmat[0] = rmat[0][0];
mmat[1] = rmat[0][1];
mmat[2] = rmat[0][2];
mmat[3] = hdr2->qoffset_x;
// second row
mmat[4] = rmat[1][0];
mmat[5] = rmat[1][1];
mmat[6] = rmat[1][2];
mmat[7] = hdr2->qoffset_y;
// third row
mmat[8] = rmat[2][0];
mmat[9] = rmat[2][1];
mmat[10] = rmat[2][2];
mmat[11] = hdr2->qoffset_z;
mmat[12] = 0.0;
mmat[13] = 0.0;
mmat[14] = 0.0;
mmat[15] = 1.0;
this->QFac = ((hdr2->pixdim[0] < 0) ? -1.0 : 1.0);
if (this->QFac < 0)
{
// We will be reversing the order of the slices, so the first VTK
// slice will be at the position of the last NIfTI slice, and we
// must adjust the offset to compensate for this.
mmat[3] -= rmat[0][2]*hdr2->pixdim[3]*(hdr2->dim[3] - 1);
mmat[7] -= rmat[1][2]*hdr2->pixdim[3]*(hdr2->dim[3] - 1);
mmat[11] -= rmat[2][2]*hdr2->pixdim[3]*(hdr2->dim[3] - 1);
}
this->QFormMatrix = vtkMatrix4x4::New();
this->QFormMatrix->DeepCopy(mmat);
}
// Set the SFormMatrix from the matrix information in the header.
// See the long discussion above for more information.
if (niftiVersion > 0 && hdr2->sform_code > 0)
{
double mmat[16];
// first row
mmat[0] = hdr2->srow_x[0]/hdr2->pixdim[1];
mmat[1] = hdr2->srow_x[1]/hdr2->pixdim[2];
mmat[2] = hdr2->srow_x[2]/hdr2->pixdim[3];
mmat[3] = hdr2->srow_x[3];
// second row
mmat[4] = hdr2->srow_y[0]/hdr2->pixdim[1];
mmat[5] = hdr2->srow_y[1]/hdr2->pixdim[2];
mmat[6] = hdr2->srow_y[2]/hdr2->pixdim[3];
mmat[7] = hdr2->srow_y[3];
// third row
mmat[8] = hdr2->srow_z[0]/hdr2->pixdim[1];
mmat[9] = hdr2->srow_z[1]/hdr2->pixdim[2];
mmat[10] = hdr2->srow_z[2]/hdr2->pixdim[3];
mmat[11] = hdr2->srow_z[3];
mmat[12] = 0.0;
mmat[13] = 0.0;
mmat[14] = 0.0;
mmat[15] = 1.0;
// Set QFac to -1 if the determinant is negative, unless QFac
// has already been set by the qform information.
if (vtkMatrix4x4::Determinant(mmat) < 0 && hdr2->qform_code == 0)
{
this->QFac = -1.0;
}
if (this->QFac < 0)
{
// If QFac is set to -1 then the slices will be reversed, and we must
// reverse the slice orientation vector (the third column of the matrix)
// to compensate.
// reverse the slice orientation vector
mmat[2] = -mmat[2];
mmat[6] = -mmat[6];
mmat[10] = -mmat[10];
// adjust the offset to compensate for changed slice ordering
mmat[3] += hdr2->srow_x[2]*(hdr2->dim[3] - 1);
mmat[7] += hdr2->srow_y[2]*(hdr2->dim[3] - 1);
mmat[11] += hdr2->srow_z[2]*(hdr2->dim[3] - 1);
}