-
Notifications
You must be signed in to change notification settings - Fork 23
/
nifti_foreign.pas
executable file
·5988 lines (5841 loc) · 209 KB
/
nifti_foreign.pas
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
unit nifti_foreign;
//{$DEFINE MRIcron}
interface
//{$mode objfpc} //test
{$mode Delphi}
{$H+}
{$DEFINE GZIP}
{$Include isgui.inc}//<- {$DEFINE GUI}
//{$DEFINE GL10} //define for MRIcroGL1.0, comment for MRIcroGL1.2 and later
{$H+}
{$IFDEF GL10}
{$Include isgui.inc}
{$ENDIF}
uses
{$IFDEF Surfice}define_types,{$ENDIF}
{$IFDEF MRIcron}define_types,{$ENDIF}
{$IFDEF GL10} define_types, {$IFNDEF FPC}gziod,{$ELSE}gzio2,{$ENDIF}{$ENDIF}
{$IFDEF GZIP}zstream, {$ENDIF}
{$IFDEF GUI}
dialogs,
{$ELSE}
dialogsx,
{$ENDIF}
//ClipBrd,
nifti_types, sysutils, classes, StrUtils, math;//2015! dialogsx
const
kIVers = ' i2nii v1.0.0707';
{$IFDEF GL10}
procedure NII_Clear (out lHdr: TNIFTIHdr);
procedure NII_SetIdentityMatrix (var lHdr: TNIFTIHdr); //create neutral rotation matrix
{$ELSE}
const
//seee README.attributes.html and parser_int.c
//FUNC_FIM_TYPE = 0; // 1 value
//FUNC_THR_TYPE = 1; //obsolete
kFUNC_NOT_STAT =0;
kFUNC_COR_TYPE =2;// Correlation Coeff # Samples, # Fit Param, # Orts
kFUNC_TT_TYPE = 3;// Student t Degrees-of-Freedom (DOF)
kFUNC_FT_TYPE = 4;// F ratio Numerator DOF, Denominator DOF
kFUNC_ZT_TYPE = 5;// Standard Normal -- none --
kFUNC_CT_TYPE = 6;// Chi-Squared DOF
kFUNC_BT_TYPE = 7;// Incomplete Beta Parameters "a" and "b"
kFUNC_BN_TYPE = 8;// Binomial # Trials, Probability per trial
kFUNC_GT_TYPE = 9;// Gamma Shape, Scale
kFUNC_PT_TYPE = 10;// Poisson Mean
kFUNC_NO_STAT_AUX = 13;
type
TFloatVec = record
ar: array of single;
dx: single;
x0: single;
function nar: integer; inline;
end;
type
TAFNI = record
jv: integer; //statistical code
nv: integer; //number of parameters that follow (may be 0)
param: array [0..2] of single;
scl_slopex: single;
minVal, maxVal, maxAbsVal: single;
nam: string[64];
FDRcurv: TFloatVec;
end;
TAFNIs = array of TAFNI;
type
mat44 = array [0..3, 0..3] of Single;
{$IFNDEF MRIcron}
ByteRA = array [1..1] of byte;
Bytep = ^ByteRA;
procedure UnGZip(const FileName: string; buffer: bytep; offset, sz: integer);
{$ENDIF}
{$ENDIF}
function readAFNIHeader(var fname: string; var nhdr: TNIFTIhdr; var gzBytes: int64; var swapEndian, isAllVolumesSame: boolean; var AFNIs: TAFNIs; var fLabels: TStringList): boolean; overload;
function readAFNIHeader(var fname: string; var nhdr: TNIFTIhdr; var gzBytes: int64; var swapEndian: boolean): boolean; overload;
function isINTERFILE(var fname: string): boolean;
function readForeignHeader(var lFilename: string; var lHdr: TNIFTIhdr; var gzBytes: int64; var swapEndian, isDimPermute2341: boolean; out xDim64: int64): boolean; overload;
function readForeignHeader(var lFilename: string; var lHdr: TNIFTIhdr; var gzBytes: int64; var swapEndian, isDimPermute2341: boolean): boolean; overload;
function IsReadable(fnm: string): boolean;
procedure convertForeignToNifti(var nhdr: TNIFTIhdr);
function FSize (lFName: String): Int64;
function isTIFF(fnm: string): boolean;
procedure nifti_mat44_to_quatern( lR :mat44; out qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac : single);
implementation
const
kNaNSingle : single = 1/0;
Type
vect4 = array [0..3] of Single;
mat33 = array [0..2, 0..2] of Single;
vect3 = array [0..2] of Single;
ivect3 = array [0..2] of integer;
procedure printf(str: string);
begin
{$IFDEF Windows}
if IsConsole then //'System' in uses
writeln(str);
{$ENDIF}
{$IFDEF UNIX} writeln(str);{$ENDIF}
end;
function IsReadable(fnm: string): boolean;
//https://wiki.freepascal.org/macOS_Programming_Tips#Determining_if_a_file_is_readable
{$IFDEF Darwin}
var
f: file;
b: byte;
{$ENDIF}
begin
result := false;
if not fileexists(fnm) then exit;
if FSize(fnm) < 2 then exit;
{$IFDEF Darwin}
AssignFile(f, fnm);
{$I+}
try
FileMode := fmOpenRead; //Set file access to read only
Reset(f, 1);
if ioresult <> 0 then
exit;
b := 0;
BlockRead(f, b, sizeof(b)); //Byte-order Identifier
CloseFile(f);
result := true;
except
result := false;
end;
{$ELSE}
result := true;
{$ENDIF}
end;
{$IFDEF GL10}
procedure NII_SetIdentityMatrix (var lHdr: TNIFTIHdr); //create neutral rotation matrix
var lInc: integer;
begin
with lHdr do begin
for lInc := 0 to 3 do
srow_x[lInc] := 0;
for lInc := 0 to 3 do
srow_y[lInc] := 0;
for lInc := 0 to 3 do
srow_z[lInc] := 0;
for lInc := 1 to 16 do
intent_name[lInc] := chr(0);
//next: create identity matrix: if code is switched on there will not be a problem
srow_x[0] := 1;
srow_y[1] := 1;
srow_z[2] := 1;
end;
end; //proc NIFTIhdr_IdentityMatrix
procedure NII_Clear (out lHdr: TNIFTIHdr);
var
lInc: integer;
begin
with lHdr do begin
HdrSz := sizeof(TNIFTIhdr);
for lInc := 1 to 10 do
Data_Type[lInc] := chr(0);
for lInc := 1 to 18 do
db_name[lInc] := chr(0);
extents:=0;
session_error:= 0;
regular:='r'{chr(0)};
dim_info:=(0);
dim[0] := 4;
for lInc := 1 to 7 do
dim[lInc] := 0;
intent_p1 := 0;
intent_p2 := 0;
intent_p3 := 0;
intent_code:=0;
datatype:=0 ;
bitpix:=0;
slice_start:=0;
for lInc := 1 to 7 do
pixdim[linc]:= 1.0;
vox_offset:= 0.0;
scl_slope := 1.0;
scl_inter:= 0.0;
slice_end:= 0;
slice_code := 0;
xyzt_units := 10;
cal_max:= 0.0;
cal_min:= 0.0;
slice_duration:=0;
toffset:= 0;
glmax:= 0;
glmin:= 0;
for lInc := 1 to 80 do
descrip[lInc] := chr(0);{80 spaces}
for lInc := 1 to 24 do
aux_file[lInc] := chr(0);{80 spaces}
{below are standard settings which are not 0}
bitpix := 16;//vc16; {8bits per pixel, e.g. unsigned char 136}
DataType := 4;//vc4;{2=unsigned char, 4=16bit int 136}
Dim[0] := 3;
Dim[1] := 256;
Dim[2] := 256;
Dim[3] := 1;
Dim[4] := 1; {n vols}
Dim[5] := 1;
Dim[6] := 1;
Dim[7] := 1;
glMin := 0;
glMax := 255;
qform_code := kNIFTI_XFORM_UNKNOWN;
sform_code:= kNIFTI_XFORM_UNKNOWN;
quatern_b := 0;
quatern_c := 0;
quatern_d := 0;
qoffset_x := 0;
qoffset_y := 0;
qoffset_z := 0;
NII_SetIdentityMatrix(lHdr);
magic := kNIFTI_MAGIC_SEPARATE_HDR;
end; //with the NIfTI header...
end;
{$ENDIF}
function UpCaseExt(lFileName: string): string;
var lI: integer;
l2ndExt,lExt : string;
begin
lExt := ExtractFileExt(lFileName);
if length(lExt) > 0 then
for lI := 1 to length(lExt) do
lExt[lI] := upcase(lExt[lI]);
result := lExt;
if lExt <> '.GZ' then exit;
lI := length(lFileName) - 6;
if li < 1 then exit;
l2ndExt := upcase(lFileName[lI])+upcase(lFileName[lI+1])+upcase(lFileName[li+2])+upcase(lFileName[li+3]);
if (l2ndExt = '.NII')then
result := l2ndExt+lExt
else if (l2ndExt = 'BRIK') and (lI > 1) and (lFileName[lI-1] = '.') then
result := '.BRIK'+lExt;
end;
{$IFNDEF GL10}
procedure UnGZip(const FileName: string; buffer: bytep; offset, sz: integer);
{$IFDEF GZIP}
var
decomp: TGZFileStream;
skip: array of byte;
begin
decomp := TGZFileStream.create(FileName, gzopenread);
if offset > 0 then begin
setlength(skip, offset);
decomp.Read(skip[0], offset);
end;
//buffer^[0] := 0; //BlockRead should be out not var: https://fpc-pascal.freepascal.narkive.com/M2rzyAkf/blockread-and-buffers
//decomp.Read(buffer[0], sz);
decomp.Read(buffer[1], sz);
decomp.free;
end;
{$ELSE}
begin
{$IFDEF UNIX} writeln('Recompile with GZ support!'); {$ENDIF}
end;
{$ENDIF}
{$ENDIF}
(* function isECAT(fnm: string): boolean;
type
THdrMain = packed record //Next: ECAT signature
magic: array[1..14] of char;
end;
var
f: file;
mhdr: THdrMain;
begin
result := false;
if not fileexists(fnm) then exit;
if DirectoryExists(fnm) then exit;
if FSize(fnm) < 32 then exit;
{$I-}
AssignFile(f, fnm);
FileMode := fmOpenRead; //Set file access to read only
Reset(f, 1);
{$I+}
if ioresult <> 0 then
exit;
BlockRead(f, mhdr, sizeof(mhdr));
closefile(f);
if ((mhdr.magic[1] <> 'M') or (mhdr.magic[2] <> 'A') or (mhdr.magic[3] <> 'T') or (mhdr.magic[4] <> 'R') or (mhdr.magic[5] <> 'I') or (mhdr.magic[6] <> 'X')) then
exit;
result := true;
end; *)
function FSize (lFName: String): Int64;
var SearchRec: TSearchRec;
begin
result := 0;
if not fileexists(lFName) then exit;
FindFirst(lFName, faAnyFile, SearchRec);
result := SearchRec.size;
FindClose(SearchRec);
end;
function Swap2(s : SmallInt): smallint;
type
swaptype = packed record
case byte of
0:(Word1 : word); //word is 16 bit
1:(Small1: SmallInt);
end;
swaptypep = ^swaptype;
var
inguy:swaptypep;
outguy:swaptype;
begin
inguy := @s; //assign address of s to inguy
outguy.Word1 := swap(inguy^.Word1);
result :=outguy.Small1;
end;
procedure swap4(var s : LongInt);
type
swaptype = packed record
case byte of
0:(Word1,Word2 : word); //word is 16 bit
1:(Long:LongInt);
end;
swaptypep = ^swaptype;
var
inguy:swaptypep;
outguy:swaptype;
begin
inguy := @s; //assign address of s to inguy
outguy.Word1 := swap(inguy^.Word2);
outguy.Word2 := swap(inguy^.Word1);
s:=outguy.Long;
end;
procedure pswap4r ( var s:single);
type
swaptype = packed record
case byte of
0:(Word1,Word2 : word); //word is 16 bit
end;
swaptypep = ^swaptype;
var
inguy:swaptypep;
outguy:swaptype;
begin
inguy := @s; //assign address of s to inguy
outguy.Word1 := swap(inguy^.Word2);
outguy.Word2 := swap(inguy^.Word1);
inguy^.Word1 := outguy.Word1;
inguy^.Word2 := outguy.Word2;
end; //proc Xswap4r
procedure pswap4i(var s : LongInt);
type
swaptype = packed record
case byte of
0:(Word1,Word2 : word); //word is 16 bit
1:(Long:LongInt);
end;
swaptypep = ^swaptype;
var
inguy:swaptypep;
outguy:swaptype;
begin
inguy := @s; //assign address of s to inguy
outguy.Word1 := swap(inguy^.Word2);
outguy.Word2 := swap(inguy^.Word1);
s:=outguy.Long;
end; //proc swap4
function swap64r(s : double):double;
type
swaptype = packed record
case byte of
0:(Word1,Word2,Word3,Word4 : word); //word is 16 bit
1:(float:double);
end;
swaptypep = ^swaptype;
var
inguy:swaptypep;
outguy:swaptype;
begin
inguy := @s; //assign address of s to inguy
outguy.Word1 := swap(inguy^.Word4);
outguy.Word2 := swap(inguy^.Word3);
outguy.Word3 := swap(inguy^.Word2);
outguy.Word4 := swap(inguy^.Word1);
try
swap64r:=outguy.float;
except
swap64r := 0;
exit;
end;{}
end;
FUNCTION specialsingle (var s:single): boolean;
//returns true if s is Infinity, NAN or Indeterminate
//4byte IEEE: msb[31] = signbit, bits[23-30] exponent, bits[0..22] mantissa
//exponent of all 1s = Infinity, NAN or Indeterminate
CONST kSpecialExponent = 255 shl 23;
VAR Overlay: LongInt ABSOLUTE s;
BEGIN
IF ((Overlay AND kSpecialExponent) = kSpecialExponent) THEN
RESULT := true
ELSE
RESULT := false;
END;
function isBioFormats(fnm: string): string;
//detect LIF and LIFF format or other Imagej/Fiji Bioformat
const
LIF_MAGIC_BYTE = $70;
LIF_MEMORY_BYTE = $2a;
var
f: file;
bs: array[0..255] of byte;
begin
result := '';
if not fileexists(fnm) then exit;
if DirectoryExists(fnm) then exit;
if FSize(fnm) < 256 then exit;
{$I-}
AssignFile(f, fnm);
FileMode := fmOpenRead; //Set file access to read only
Reset(f, 1);
{$I+}
if ioresult <> 0 then
exit;
bs[0] := 0; //BlockRead should be out not var: https://fpc-pascal.freepascal.narkive.com/M2rzyAkf/blockread-and-buffers
BlockRead(f, bs, sizeof(bs)); //Byte-order Identifier
if (bs[8] = LIF_MEMORY_BYTE) and ((bs[0] = LIF_MAGIC_BYTE) or (bs[3] = LIF_MAGIC_BYTE)) then
result := 'LIF'; //file can be read using LIFReader.java
if (bs[4] = ord('i')) and (bs[5] = ord('m')) and (bs[6] = ord('p')) and (bs[7] = ord('r')) then
result := 'LIFF'; //Openlab LIFF format OpenLabReader.java
if (bs[0] = $D0) and (bs[1] = $CF) and (bs[2] = $11) and (bs[3] = $E0) then //IPW_MAGIC_BYTES = 0xd0cf11e0
result := 'IPW'; //IPWReader.java
if (bs[0] = ord('i')) and (bs[1] = ord('i')) and (bs[2] = ord('i')) and (bs[3] = ord('i')) then
result := 'IPL';//IPLabReader.java
if (bs[0] = $89) and (bs[1] = $48) and (bs[2] = $44) and (bs[3] = $46) then //IPW_MAGIC_BYTES = 0xd0cf11e0
result := 'HDF';//Various readers: ImarisHDFReader, CellH5Reader, etc
if (bs[0] = $DA) and (bs[1] = $CE) and (bs[2] = $BE) and (bs[3] = $0A) then//DA CE BE 0A
result := 'ND2';//MAGIC_BYTES_1 ND2Reader
if (bs[0] = $6a) and (bs[1] = $50) and (bs[2] = $20) and (bs[3] = $20) then
result := 'ND2';//MAGIC_BYTES_2 ND2Reader
if (bs[208] = $4D) and (bs[209] = $41) and (bs[210] = $50) then
result := 'MAP';//MRCReader http://www.ccpem.ac.uk/mrc_format/mrc2014.php
//GatanReader.java
closefile(f);
end;
function isTIFF(fnm: string): boolean;
var
f: file;
w: word;
begin
result := false;
if not fileexists(fnm) then exit;
if DirectoryExists(fnm) then exit;
if FSize(fnm) < 32 then exit;
{$I-}
AssignFile(f, fnm);
FileMode := fmOpenRead; //Set file access to read only
Reset(f, 1);
{$I+}
if ioresult <> 0 then
exit;
w := 0;
BlockRead(f, w, sizeof(w)); //Byte-order Identifier
if (w = $4D4D) or (w = $4949) then
result := true;
closefile(f);
end;
{$IFDEF GUI}
procedure ShowMsg(s: string);
begin
Showmessage(s);
end;
{$ENDIF}
procedure fromMatrix (m: mat44; out r11,r12,r13,r21,r22,r23,r31,r32,r33: double);
begin
r11 := m[0,0];
r12 := m[0,1];
r13 := m[0,2];
r21 := m[1,0];
r22 := m[1,1];
r23 := m[1,2];
r31 := m[2,0];
r32 := m[2,1];
r33 := m[2,2];
end;
function Matrix2D (r11,r12,r13,r21,r22,r23,r31,r32,r33: double): mat33;
begin
result[0,0] := r11;
result[0,1] := r12;
result[0,2] := r13;
result[1,0] := r21;
result[1,1] := r22;
result[1,2] := r23;
result[2,0] := r31;
result[2,1] := r32;
result[2,2] := r33;
end;
function nifti_mat33_determ( R: mat33 ):double; //* determinant of 3x3 matrix */
begin
result := r[0,0]*r[1,1]*r[2,2]
-r[0,0]*r[2,1]*r[1,2]
-r[1,0]*r[0,1]*r[2,2]
+r[1,0]*r[2,1]*r[0,2]
+r[2,0]*r[0,1]*r[1,2]
-r[2,0]*r[1,1]*r[0,2] ;
end;
function nifti_mat33_rownorm( A: mat33 ): single; // max row norm of 3x3 matrix
var
r1,r2,r3: single ;
begin
r1 := abs(A[0,0])+abs(A[0,1])+abs(A[0,2]);
r2 := abs(A[1,0])+abs(A[1,1])+abs(A[1,2]);
r3 := abs(A[2,0])+abs(A[2,1])+abs(A[2,2]);
if( r1 < r2 ) then r1 := r2 ;
if( r1 < r3 ) then r1 := r3 ;
result := r1 ;
end;
procedure fromMatrix33 (m: mat33; out r11,r12,r13,r21,r22,r23,r31,r32,r33: double);
begin
r11 := m[0,0];
r12 := m[0,1];
r13 := m[0,2];
r21 := m[1,0];
r22 := m[1,1];
r23 := m[1,2];
r31 := m[2,0];
r32 := m[2,1];
r33 := m[2,2];
end;
function nifti_mat33_inverse( R: mat33 ): mat33; //* inverse of 3x3 matrix */
var
r11,r12,r13,r21,r22,r23,r31,r32,r33 , deti: double ;
begin
FromMatrix33(R,r11,r12,r13,r21,r22,r23,r31,r32,r33);
deti := r11*r22*r33-r11*r32*r23-r21*r12*r33
+r21*r32*r13+r31*r12*r23-r31*r22*r13 ;
if( deti <> 0.0 ) then deti := 1.0 / deti ;
result[0,0] := deti*( r22*r33-r32*r23) ;
result[0,1] := deti*(-r12*r33+r32*r13) ;
result[0,2] := deti*( r12*r23-r22*r13) ;
result[1,0] := deti*(-r21*r33+r31*r23) ;
result[1,1] := deti*( r11*r33-r31*r13) ;
result[1,2] := deti*(-r11*r23+r21*r13) ;
result[2,0] := deti*( r21*r32-r31*r22) ;
result[2,1] := deti*(-r11*r32+r31*r12) ;
result[2,2] := deti*( r11*r22-r21*r12) ;
end;
function nifti_mat33_colnorm( A: mat33 ): single; //* max column norm of 3x3 matrix */
var
r1,r2,r3: single ;
begin
r1 := abs(A[0,0])+abs(A[1,0])+abs(A[2,0]) ;
r2 := abs(A[0,1])+abs(A[1,1])+abs(A[2,1]) ;
r3 := abs(A[0,2])+abs(A[1,2])+abs(A[2,2]) ;
if( r1 < r2 ) then r1 := r2 ;
if( r1 < r3 ) then r1 := r3 ;
result := r1 ;
end;
function nifti_mat33_polar( A: mat33 ): mat33;
var
k:integer;
X , Y , Z: mat33 ;
dif,alp,bet,gam,gmi : single;
begin
dif := 1;
k := 0;
X := A ;
gam := nifti_mat33_determ(X) ;
while( gam = 0.0 )do begin //perturb matrix
gam := 0.00001 * ( 0.001 + nifti_mat33_rownorm(X) ) ;
X[0,0] := X[0,0]+gam ;
X[1,1] := X[1,1]+gam ;
X[2,2] := X[2,2] +gam ;
gam := nifti_mat33_determ(X) ;
end;
while true do begin
Y := nifti_mat33_inverse(X) ;
if( dif > 0.3 )then begin // far from convergence
alp := sqrt( nifti_mat33_rownorm(X) * nifti_mat33_colnorm(X) ) ;
bet := sqrt( nifti_mat33_rownorm(Y) * nifti_mat33_colnorm(Y) ) ;
gam := sqrt( bet / alp ) ;
gmi := 1.0 / gam ;
end else begin
gam := 1.0;
gmi := 1.0 ; //close to convergence
end;
Z[0,0] := 0.5 * ( gam*X[0,0] + gmi*Y[0,0] ) ;
Z[0,1] := 0.5 * ( gam*X[0,1] + gmi*Y[1,0] ) ;
Z[0,2] := 0.5 * ( gam*X[0,2] + gmi*Y[2,0] ) ;
Z[1,0] := 0.5 * ( gam*X[1,0] + gmi*Y[0,1] ) ;
Z[1,1] := 0.5 * ( gam*X[1,1] + gmi*Y[1,1] ) ;
Z[1,2] := 0.5 * ( gam*X[1,2] + gmi*Y[2,1] ) ;
Z[2,0] := 0.5 * ( gam*X[2,0] + gmi*Y[0,2] ) ;
Z[2,1] := 0.5 * ( gam*X[2,1] + gmi*Y[1,2] ) ;
Z[2,2] := 0.5 * ( gam*X[2,2] + gmi*Y[2,2] ) ;
dif := abs(Z[0,0]-X[0,0])+abs(Z[0,1]-X[0,1])+abs(Z[0,2]-X[0,2])
+abs(Z[1,0]-X[1,0])+abs(Z[1,1]-X[1,1])+abs(Z[1,2]-X[1,2])
+abs(Z[2,0]-X[2,0])+abs(Z[2,1]-X[2,1])+abs(Z[2,2]-X[2,2]);
k := k+1 ;
if( k > 100) or (dif < 3.e-6 ) then begin
result := Z;
break ; //convergence or exhaustion
end;
X := Z ;
end;
result := Z ;
end;
procedure nifti_mat44_to_quatern( lR :mat44; out qb, qc, qd, qx, qy, qz, dx, dy, dz, qfac : single);
var
r11,r12,r13 , r21,r22,r23 , r31,r32,r33, xd,yd,zd , a,b,c,d : double;
P,Q: mat33; //3x3
begin
// offset outputs are read write out of input matrix
qx := lR[0,3];
qy := lR[1,3];
qz := lR[2,3];
//load 3x3 matrix into local variables
fromMatrix(lR,r11,r12,r13,r21,r22,r23,r31,r32,r33);
//compute lengths of each column; these determine grid spacings
xd := sqrt( r11*r11 + r21*r21 + r31*r31 ) ;
yd := sqrt( r12*r12 + r22*r22 + r32*r32 ) ;
zd := sqrt( r13*r13 + r23*r23 + r33*r33 ) ;
//if a column length is zero, patch the trouble
if( xd = 0.0 )then begin r11 := 1.0 ; r21 := 0; r31 := 0.0 ; xd := 1.0 ; end;
if( yd = 0.0 )then begin r22 := 1.0 ; r12 := 0; r32 := 0.0 ; yd := 1.0 ; end;
if( zd = 0.0 )then begin r33 := 1.0 ; r13 := 0; r23 := 0.0 ; zd := 1.0 ; end;
//assign the output lengths
dx := xd;
dy := yd;
dz := zd;
//normalize the columns
r11 := r11/xd ; r21 := r21/xd ; r31 := r31/xd ;
r12 := r12/yd ; r22 := r22/yd ; r32 := r32/yd ;
r13 := r13/zd ; r23 := r23/zd ; r33 := r33/zd ;
{ At this point, the matrix has normal columns, but we have to allow
for the fact that the hideous user may not have given us a matrix
with orthogonal columns. So, now find the orthogonal matrix closest
to the current matrix.
One reason for using the polar decomposition to get this
orthogonal matrix, rather than just directly orthogonalizing
the columns, is so that inputting the inverse matrix to R
will result in the inverse orthogonal matrix at this point.
If we just orthogonalized the columns, this wouldn't necessarily hold.}
Q := Matrix2D (r11,r12,r13, // 2D "graphics" matrix
r21,r22,r23,
r31,r32,r33);
P := nifti_mat33_polar(Q) ; //P is orthog matrix closest to Q
FromMatrix33(P,r11,r12,r13,r21,r22,r23,r31,r32,r33);
{ [ r11 r12 r13 ]
at this point, the matrix [ r21 r22 r23 ] is orthogonal
[ r31 r32 r33 ]
compute the determinant to determine if it is proper}
zd := r11*r22*r33-r11*r32*r23-r21*r12*r33
+r21*r32*r13+r31*r12*r23-r31*r22*r13 ; //should be -1 or 1
if( zd > 0 )then begin // proper
qfac := 1.0 ;
end else begin //improper ==> flip 3rd column
qfac := -1.0 ;
r13 := -r13 ; r23 := -r23 ; r33 := -r33 ;
end;
// now, compute quaternion parameters
a := r11 + r22 + r33 + 1.0;
if( a > 0.5 ) then begin //simplest case
a := 0.5 * sqrt(a) ;
b := 0.25 * (r32-r23) / a ;
c := 0.25 * (r13-r31) / a ;
d := 0.25 * (r21-r12) / a ;
end else begin //trickier case
xd := 1.0 + r11 - (r22+r33) ;// 4*b*b
yd := 1.0 + r22 - (r11+r33) ;// 4*c*c
zd := 1.0 + r33 - (r11+r22) ;// 4*d*d
if( xd > 1.0 ) then begin
b := 0.5 * sqrt(xd) ;
c := 0.25* (r12+r21) / b ;
d := 0.25* (r13+r31) / b ;
a := 0.25* (r32-r23) / b ;
end else if( yd > 1.0 ) then begin
c := 0.5 * sqrt(yd) ;
b := 0.25* (r12+r21) / c ;
d := 0.25* (r23+r32) / c ;
a := 0.25* (r13-r31) / c ;
end else begin
d := 0.5 * sqrt(zd) ;
b := 0.25* (r13+r31) / d ;
c := 0.25* (r23+r32) / d ;
a := 0.25* (r21-r12) / d ;
end;
if( a < 0.0 )then begin b:=-b ; c:=-c ; d:=-d; {a:=-a; this is not used} end;
end;
qb := b ;
qc := c ;
qd := d ;
end;
procedure ZERO_MAT33(out m: mat33); //note sets m[3,3] to one
var
i,j: integer;
begin
for i := 0 to 2 do
for j := 0 to 2 do
m[i,j] := 0.0;
m[2,2] := 1;
end;
procedure ZERO_MAT44(out m: mat44); //note sets m[3,3] to one
var
i,j: integer;
begin
for i := 0 to 3 do
for j := 0 to 3 do
m[i,j] := 0.0;
m[3,3] := 1;
end;
procedure LOAD_MAT33(out m: mat33; m00,m01,m02, m10,m11,m12, m20,m21,m22: single);
begin
m[0,0] := m00;
m[0,1] := m01;
m[0,2] := m02;
m[1,0] := m10;
m[1,1] := m11;
m[1,2] := m12;
m[2,0] := m20;
m[2,1] := m21;
m[2,2] := m22;
end;
function nifti_mat33vec_mul(m: mat33; v: vect3): vect3;
var
i: integer;
begin
for i := 0 to 2 do
result[i] := (v[0]*m[i,0])+(v[1]*m[i,1])+(v[2]*m[i,2]);
end;
function nifti_mat33_mul( A,B: mat33): mat33;
var
i,j: integer;
begin
for i:=0 to 2 do
for j:=0 to 2 do
result[i,j] := A[i,0] * B[0,j]
+ A[i,1] * B[1,j]
+ A[i,2] * B[2,j] ;
end;
procedure LOAD_MAT44(out m: mat44; m00,m01,m02,m03, m10,m11,m12,m13, m20,m21,m22,m23: single);
begin
m[0,0] := m00;
m[0,1] := m01;
m[0,2] := m02;
m[0,3] := m03;
m[1,0] := m10;
m[1,1] := m11;
m[1,2] := m12;
m[1,3] := m13;
m[2,0] := m20;
m[2,1] := m21;
m[2,2] := m22;
m[2,3] := m23;
m[3,0] := 0.0;
m[3,1] := 0.0;
m[3,2] := 0.0;
m[3,3] := 1.0;
end;
function validMatrix(var m: mat44): boolean;
var
i: integer;
begin
result := false;
for i := 0 to 2 do begin
if (m[0,i] = 0.0) and (m[1,i] = 0.0) and (m[2,i] = 0.0) then exit;
if (m[i,0] = 0.0) and (m[i,1] = 0.0) and (m[i,2] = 0.0) then exit;
end;
result := true;
end;
procedure vCoord(var lV: vect3; lMat: mat33);
//transform X Y Z by matrix
var
lXi,lYi,lZi: single;
begin
lXi := lV[0]; lYi := lV[1]; lZi := lV[2];
lV[0] := (lXi*lMat[0,0]+lYi*lMat[0,1]+lZi*lMat[0,2]);
lV[1] := (lXi*lMat[1,0]+lYi*lMat[1,1]+lZi*lMat[1,2]);
lV[2] := (lXi*lMat[2,0]+lYi*lMat[2,1]+lZi*lMat[2,2]);
end;
procedure SetCenter(var nhdr: TNIFTIhdr);
var
v: vect3;
m: mat33;
i: integer;
begin
for i := 0 to 2 do begin
m[0,i] := nhdr.srow_x[i];
m[1,i] := nhdr.srow_y[i];
m[2,i] := nhdr.srow_z[i];
v[i] := nhdr.dim[i+1]*0.5;
end;
vCoord(v,m);
//Voxel2mm
//nhdr.srow_x[3]:=-0.5 * (d[0]*m[0,0]+ d[1]*m[0,1]+d[2]*m[0,2]);
nhdr.srow_x[3] := -v[0];
nhdr.srow_y[3] := -v[1];
nhdr.srow_z[3] := -v[2];
end;
procedure SetSForm(var nhdr: TNIFTIhdr);
begin
nhdr.srow_x[0]:=nhdr.pixdim[1]; nhdr.srow_x[1]:=0; nhdr.srow_x[2]:=0; nhdr.srow_x[3]:=-(nhdr.dim[1]-2.0)/2.0*nhdr.pixdim[1];
nhdr.srow_y[0]:=0; nhdr.srow_y[1]:=nhdr.pixdim[2]; nhdr.srow_y[2]:=0; nhdr.srow_y[3]:=-(nhdr.dim[2]-2.0)/2.0*nhdr.pixdim[2];
nhdr.srow_z[0]:=0; nhdr.srow_z[1]:=0; nhdr.srow_z[2]:=nhdr.pixdim[3]; nhdr.srow_z[3]:=-(nhdr.dim[3]-2.0)/2.0*nhdr.pixdim[3];
end;
procedure convertForeignToNifti(var nhdr: TNIFTIhdr);
var
i,nonSpatialMult: integer;
qto_xyz: mat44;
dumdx, dumdy, dumdz: single;
begin
nhdr.HdrSz := 348; //used to signify header does not need to be byte-swapped
nhdr.magic:=kNIFTI_MAGIC_EMBEDDED_HDR;
if (nhdr.dim[3] = 0) then nhdr.dim[3] := 1; //for 2D images the 3rd dim is not specified and set to zero
nhdr.dim[0] := 3; //for 2D images the 3rd dim is not specified and set to zero
nonSpatialMult := 1;
for i := 4 to 7 do
if nhdr.dim[i] > 0 then
nonSpatialMult := nonSpatialMult * nhdr.dim[i];
if (nonSpatialMult > 1) then begin
nhdr.dim[0] := 4;
nhdr.dim[4] := nonSpatialMult;
for i := 5 to 7 do
nhdr.dim[i] := 0;
end;
nhdr.bitpix := 8;
if (nhdr.scl_slope = 0.0) then
nhdr.scl_slope := 1.0;
if (nhdr.datatype = 4) or (nhdr.datatype = 512) then nhdr.bitpix := 16;
if (nhdr.datatype = kDT_RGB) or (nhdr.datatype = kDT_RGBplanar3D) then nhdr.bitpix := 24;
if (nhdr.datatype = 8) or (nhdr.datatype = 16) or (nhdr.datatype = 768) then nhdr.bitpix := 32;
if (nhdr.datatype = 32) or (nhdr.datatype = 64) or (nhdr.datatype = 1024) or (nhdr.datatype = 1280) then nhdr.bitpix := 64;
LOAD_MAT44(qto_xyz, nhdr.srow_x[0], nhdr.srow_x[1], nhdr.srow_x[2], nhdr.srow_x[3],
nhdr.srow_y[0], nhdr.srow_y[1], nhdr.srow_y[2], nhdr.srow_y[3],
nhdr.srow_z[0], nhdr.srow_z[1], nhdr.srow_z[2], nhdr.srow_z[3]);
if not validMatrix(qto_xyz) then begin
nhdr.sform_code := 0;
nhdr.qform_code := 0;
for i := 0 to 3 do begin
nhdr.srow_x[i] := 0;
nhdr.srow_y[i] := 0;
nhdr.srow_z[i] := 0;
end;
nhdr.srow_x[0] := 1;
nhdr.srow_y[1] := 1;
nhdr.srow_z[2] := 1;
exit;
end;
nhdr.sform_code := 1;
nifti_mat44_to_quatern( qto_xyz , nhdr.quatern_b, nhdr.quatern_c, nhdr.quatern_d,nhdr.qoffset_x,nhdr.qoffset_y,nhdr.qoffset_z, dumdx, dumdy, dumdz,nhdr.pixdim[0]) ;
nhdr.qform_code := 0;//kNIFTI_XFORM_SCANNER_ANAT;
end;
procedure NSLog( str: string);
begin
{$IFDEF GUI}
showmsg(str);
{$ENDIF}
{$IFDEF UNIX}writeln(str);{$ENDIF}
end;
function parsePicString(s: string): single;
//given "AXIS_4 001 0.000000e+00 4.000000e-01 microns" return 0.4
var
sList : TStringList;
begin
result := 0.0;
{$IFDEF FPC}
DefaultFormatSettings.DecimalSeparator := '.' ;
{$ELSE}
DecimalSeparator := '.';
{$ENDIF}
sList := TStringList.Create;
sList.Delimiter := ' '; // Each list item will be blank separated
sList.DelimitedText := s;
if sList.Count > 4 then begin
//ShowMessage(sList[3]);
try
result := StrToFloat(sList[3]); // Middle blanks are not supported
except
//ShowMessage(Exception.Message);
end;
end;
sList.Free;
end;
function readVmr (var fname: string; isV16: boolean; var nhdr: TNIFTIhdr; var swapEndian: boolean): boolean;
//http://support.brainvoyager.com/automation-aamp-development/23-file-formats/385-developer-guide-26-the-format-of-vmr-files.html
Type
Tvmr_header = packed record //Next: VMR Format Header structure
ver, nx, ny, nz: word; // 0,4,8,12
end; // Tbv_header;
(*Tvmr_tail = packed record //
Xoff,Yoff,Zoff,FramingCube: int16; //v3
PosFlag,CoordSystem: int32;
X1, Y1, Z1,Xn,Yn,Zn, RXv,RYv,RZv, CXv,CYv,CZv: single;
nRmat, nCmat: int32;
Rfov, Cfov, Zthick, Zgap: single;
nTrans: int32;
LRconv: uint8;
vXres, vYres, vZres: single;
isResVerified, isTal: uint8;
min, mean, max: int32;
end; *)
var
vhdr : Tvmr_header;
//vtail : Tvmr_tail;
lHdrFile: file;
xSz, nvox, FSz, Hsz : integer;
begin
result := false;
{$I-}
AssignFile(lHdrFile, fname);
FileMode := fmOpenRead; //Set file access to read only
Reset(lHdrFile, 1);
{$I+}
if ioresult <> 0 then begin
NSLog('Error in reading vmr header.'+inttostr(IOResult));
FileMode := 2;
exit;
end;
FSz := Filesize(lHdrFile);
vhdr.nx := 0; //BlockRead should be out not var: https://fpc-pascal.freepascal.narkive.com/M2rzyAkf/blockread-and-buffers
BlockRead(lHdrFile, vhdr, sizeof(Tvmr_header));
nVox := vhdr.nx * vhdr.ny * vhdr.nz;
if isV16 then
xSz := (2 * nVox) + sizeof(Tvmr_header)
else
xSz := nVox + sizeof(Tvmr_header);//+ sizeof(Tvmr_tail);
Hsz := sizeof(Tvmr_header);
if (xSz > FSz) then begin //version 1? (6 byte header)
nVox := vhdr.ver * vhdr.nx * vhdr.ny;
if isV16 then
xSz := (2 * nVox) + 6
else
xSz := nVox + 6;
if (xSz = FSz) then begin //version 1
vhdr.nz := vhdr.ny;
vhdr.ny := vhdr.nx;
vhdr.nx := vhdr.ver;
vhdr.ver := 1;
Hsz := 6;
end;
end;
if (xSz > FSz) then begin //docs do not specify endian - wrong endian?
NSLog(format('Odd v16 or vmr format image %dx%dx%d ver %d sz %d', [vhdr.nx, vhdr.ny, vhdr.nz, vhdr.ver, FSz] ));
CloseFile(lHdrFile);
exit;
end;
//seek(lHdrFile, nVox + sizeof(Tvmr_header));
//BlockRead(lHdrFile, vtail, sizeof(Tvmr_tail));
CloseFile(lHdrFile);
swapEndian := false;
nhdr.dim[0]:=3;//3D
nhdr.dim[1]:=vhdr.nx;
nhdr.dim[2]:=vhdr.ny;
nhdr.dim[3]:=vhdr.nz;
nhdr.dim[4]:=1;