forked from xiangruili/dicm2nii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dicm_hdr.m
1536 lines (1424 loc) · 60.7 KB
/
dicm_hdr.m
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
function [s, info, dict] = dicm_hdr(fname, dict, iFrames)
% Return header of a dicom file in a struct.
%
% [s, err] = DICM_HDR(dicomFileName, dict, iFrames);
%
% The mandatory 1st input is the dicom file name.
%
% The optional 2nd input is a dicom dictionary returned by dicm_dict. It may
% have only part of the full dictionary, which can speed up header read
% considerably. See rename_dicm for example.
%
% The optional 3rd intput is useful for multi-frame dicom. When there are many
% frames, it may be slow to read all frames in PerFrameFunctionalGroupsSequence.
% The 3rd input specifies the frames to read. By default, items for only 1st,
% 2nd and last frames are read.
%
% The optional 2nd output contains information in case of error, and will be
% empty if there is no error.
%
% The optional 3rd output is rarely needed. It returns the dicom dictionary
% which may be updated from the input dict if the dicom vendor is different from
% that in the input dict.
%
% DICM_HDR is like Matlab dicominfo, but is independent of Image Processing
% Toolbox. The advantage is that it decodes most private and shadow tags for
% Siemens, GE and Philips dicom, and runs faster, especially for partial header
% and multi-frame dicom.
%
% DICM_HDR can also read Philips PAR/XML file, AFNI HEAD file, Freesurfer MGH
% file and some BrainVoyager files, and return needed fields for dicm2nii to
% convert into nifti.
%
% See also DICM_DICT, DICM2NII, DICM_IMG, RENAME_DICM, SORT_DICM, ANONYMIZE_DICM
% History (yymmdd):
% 130823 Write it for dicm2nii.m ([email protected]).
% 130912 Extend private tags, automatically detect vendor.
% 130923 Call philips_par, so make dicm2nii easier.
% 131001 Decode SQ, useful for multiframe dicom and Philips Stack.
% 131008 Load then typecast. Faster than multiple fread.
% 131009 Work for implicit VR.
% 131010 Decode Siemens CSA header (slow), so it is human readable.
% 131019 PAR file: read image col labels, and use it for indexing.
% 131023 Implement afni_hdr.
% 131102 Use last tag for partial hdr, so return if it is non-exist fld.
% 131107 Search tags if only a few fields: faster than regular way.
% 131114 Add 3rd input: only 1,2,last frames hdr read. 0.4 vs 38 seconds!
% Store needed fields in LastFile for PAR MIXED image type.
% 140123 Support dicom without meta info (thanks Paul).
% 140213 afni_head: IJK_TO_DICOM_REAL replaces IJK_TO_DICOM.
% 140502 philips_par: don't use FOV for PixelSpacing and SpacingBetweenSlices.
% 140506 philips_par: use PAR file name as SeriesDescription.
% 140512 decode GE ProtocolDataBlock (gz compressed).
% 140611 No re-do if there are <16 extra bytes after image data.
% 140724 Ignore PAR/HEAD ext case; fix philips_par: Patient Position.
% 140924 Use dict VR if VR==OB/UN (thx Macro R). Could be bad in theory.
% 141006 philips_par: take care of char(13 10) issue (thx Hye).
% 141021 Store fields in dict, so it can be used for changed vendor.
% 141023 checkManufacturer for fast search approach too.
% 141128 Minor tweaks (len-1 in read_csa) for Octave 3.8.1.
% 150114 Siemens CSA str is not always len=1. Fix it (runs slower).
% 150128 Use memory gunzip for GE ProtocolDataBlock (0.5 vs 43 ms).
% 150222 Avoid repeatedly reading .REC .BRIK file for hdr.
% 150227 Avoid error due to empty file (thx Kushal).
% 150316 Avoid error due to empty item dat for search method (thx VG).
% 150324 philips_par/afni_head: make up SeriesInstanceUID for dicm2nii.
% 150405 Implement bv_file to read non-transformed BV fmr/vmr/dmr.
% 150504 bv_file: fix multiple STCdata; bug fix for VMRData.
% 150513 return dict as 3rd output for dicm2nii in case of vendor change.
% 150517 fix manufacturer check problem for Octave: no re-read.
% 150522 PerFrameSQ ind: fix the case if numel(ind)~=nFrame.
% 150526 read_sq: use ItemDelimitationItem instead of empty dat1 as SQ end.
% 150924 philips_par: store SliceNumber if not acsending/decending order.
% 151001 check Manufacturer in advance for 'search' method.
% 160105 Bug fix for b just missing iPixelData (Thx Andrew S).
% 160127 Support big endian dicom; Always return TransferSyntaxUID for dicm_img.
% 160310 Fix problem of failing to update allRead with Inf bytes read.
% 160410 philips_par: check IndexInREC, and minor improvement.
% 160412 add read_val() for search method, but speed benefit is minor.
% 160414 Skip GEIIS SQ: not dicom compliant.
% 160418 Add search_MF_val(); need FrameStart in PerFrameSQ.
% 160422 Performance: avoid nestedFunc (big), use uint8, avoid typecast (minor).
% 160527 philips_par: center of slice 1 for slice dir; (dim-1)/2 for vol center.
% 160608 read_sq: n=nEnd (j>2) with PerFrameSQ (needed if length is not inf).
% 160825 can read dcm without PixelData, by faking p.iPixelData=fSize+1.
% 160829 no make-up SeriesNumber/InstanceUID in afni_head/philips_par/bv_file.
% 160928 philips_par: fix para table ind; treat type 17 as phase img. Thx SS.
% 161130 check i+n-1<=p.iPixelData in search method to avoid error. Thx xLei.
% 170127 Implement mgh_file: read FreeSurfer mgh or mgz.
% 170618 philips_par(): use regexp (less error prone); ignore keyname case.
% 170618 afni_head(): make MSB_FIRST (BE) BRIK work; fix negative PixelSpacing.
% 170625 read_ProtocolDataBlock(): decompress only to avoid datatype guess.
% 170803 par_key(): bug fix introduced on 170618.
% 170910 regexp tweak to work for Octave.
% 170921 read_ProtocolDataBlock: decode into struct with better performance.
% 171228 philips_par: bug fix for possible slice flip. thx ShereifH.
% 170309 philips_par: take care of incomplete volume if not XYTZ. thx YiL.
% 180507 read_val: keep bytes if typecast fails. thx JillM.
% 180528 remove reversed search so allow to get item from 1st PerFrame.
% 180531 philips_par: use SortFrames to solve XYTZ and incomplete volume.
% 180605 philips_xml: much faster than xml2par;
% philips_par: start to support V3 (thx ChrisR); fix (ap,fh,rl) issue.
% 180612 philips_par & xml: take care of IndexInREC (may nerver be tested).
% 180615 Avoid error for dicm without PixelData for search method (thx LucaT).
% 180620 philips_xml: bug fix to convert str to num for sort_frames.
persistent dict_full;
s = []; info = '';
if nargin<2 || isempty(dict)
if isempty(dict_full), dict_full = dicm_dict; end
p.fullHdr = true;
p.dict = dict_full;
else
p.fullHdr = false; % p updated in main func
p.dict = dict;
end
if nargin==3 && isstruct(fname) % wrapper
s = search_MF_val(fname, dict, iFrames); % s, s1, iFrames
return;
end
if nargin<3, iFrames = []; end
p.iFrames = iFrames;
fid = fopen(fname, 'r', 'l');
if fid<0, info = ['File not exists: ' fname]; return; end
closeFile = onCleanup(@() fclose(fid)); % auto close when done or error
fseek(fid, 0, 1); fSize = ftell(fid); fseek(fid, 0, -1);
if fSize<140 % 132 + one empty tag, ignore truncated
info = ['Invalid file: ' fname];
return;
end
b8 = fread(fid, 130000, 'uint8=>uint8')'; % enough for most dicom
iTagStart = 132; % start of first tag
isDicm = isequal(b8(129:132), 'DICM');
if ~isDicm % truncated dicom: is first group 2 or 8? not safe
group = ch2int16(b8(1:2), 0);
isDicm = group==2 || group==8; % truncated dicm always LE
iTagStart = 0;
end
if ~isDicm % may be PAR/HEAD/BV file
[~, ~, ext] = fileparts(fname);
try
if strcmpi(ext, '.PAR')
[s, info] = philips_par(fname);
elseif strcmpi(ext, '.xml')
% [s, info] = philips_par(fname);
[s, info] = philips_xml(fname);
elseif strcmpi(ext, '.HEAD') % || strcmpi(ext, '.BRIK')
[s, info] = afni_head(fname);
elseif any(strcmpi(ext, {'.mgh' '.mgz'}))
[s, info] = mgh_file(fname);
elseif any(strcmpi(ext, {'.vmr' '.fmr' '.dmr'})) % BrainVoyager
[s, info] = bv_file(fname);
else
info = ['Unknown file type: ' fname];
return;
end
catch me
info = me.message;
return;
end
if ~isempty(s), return; end
if isempty(info), info = ['Not dicom file: ' fname]; end
return;
end
p.expl = false; % default for truncated dicom
p.be = false; % little endian by default
% Get TransferSyntaxUID first, so find PixelData
i = strfind(char(b8), [char([2 0 16 0]) 'UI']); % always explicit LE
tsUID = '';
if ~isempty(i) % empty for truncated
i = i(1) + 6;
n = ch2int16(b8(i+(0:1)), 0);
tsUID = deblank(char(b8(i+1+(1:n))));
p.expl = ~strcmp(tsUID, '1.2.840.10008.1.2'); % may be wrong for some
p.be = strcmp(tsUID, '1.2.840.10008.1.2.2');
end
% find s.PixelData.Start so avoid search in img
% We verify iPixelData+bytes=fSize. If bytes=2^32-1, read all and use last tag
tg = char([224 127 16 0]); % PixelData, VR can be OW/OB even if expl
if p.be, tg = tg([2 1 4 3]); end
found = false;
for nb = [0 2e6 20e6 fSize] % if not enough, read more till all read
b8 = [b8 fread(fid, nb, 'uint8=>uint8')']; %#ok
i = strfind(char(b8), tg);
i = i(mod(i,2)==1); % must be odd number
for k = i(end:-1:1) % last is likely real PixelData
p.iPixelData = k + p.expl*4 + 7; % s.PixelData.Start: 0-based
if numel(b8)<p.iPixelData, b8 = [b8 fread(fid, 12, '*uint8')']; end %#ok
p.bytes = ch2int32(b8(p.iPixelData+(-3:0)), p.be);
if p.bytes==4294967295 && feof(fid), break; end % 2^32-1 compressed
d = fSize - p.iPixelData - p.bytes; % d=0 most of time
if d>=0 && d<16, found = true; break; end % real PixelData
end
if found, break; end
if feof(fid)
if isempty(i), p.iPixelData = fSize+1; end % fake it: no PixelData
break;
end
end
s.Filename = fopen(fid);
s.FileSize = fSize;
nTag = numel(p.dict.tag); % always search if only one tag: can find it in any SQ
toSearch = nTag<2 || (nTag<30 && ~any(strcmp(p.dict.vr, 'SQ')) && p.iPixelData<1e6);
if toSearch % search each tag if header is short and not many tags asked
if ~isempty(tsUID), s.TransferSyntaxUID = tsUID; end % hope it is 1st tag
bc = char(b8(1:min(end, p.iPixelData)));
if ~isempty(p.dict.vendor) && any(mod(p.dict.group, 2)) % private group
tg = char([8 0 112 0]); % Manufacturer
if p.be, tg = tg([2 1 4 3]); end
if p.expl, tg = [tg 'LO']; end
i = strfind(bc, tg);
i = i(mod(i,2)==1);
if ~isempty(i)
i = i(1) + 4 + p.expl*2; % Manufacturer should be the earliest one
n = ch2int16(b8(i+(0:1)), p.be);
dat = deblank(bc(i+1+(1:n)));
[p, dict] = updateVendor(p, dat);
end
end
tg = char([40 0 8 0]); % NumberOfFrames
if p.be, tg = tg([2 1 4 3]); end
if p.expl, tg = [tg 'IS']; end
i = strfind(bc, tg);
i = i(mod(i,2)==1);
if ~isempty(i)
i = i(1) + 4 + p.expl*2; % take 1st
n = ch2int16(b8(i+(0:1)), p.be);
p.nFrames = str2double(bc(i+1+(1:n)));
end
for k = 1:numel(p.dict.tag)
group = p.dict.group(k);
swap = p.be && group~=2;
hasVR = p.expl || group==2;
tg = char(typecast([group p.dict.element(k)], 'uint8'));
if swap, tg = tg([2 1 4 3]); end
i = strfind(bc, tg);
i = i(mod(i,2)==1);
if isempty(i), continue; % no this tag, next
elseif isfield(p, 'nFrames') && numel(i)==p.nFrames, i = i(1);
% elseif strcmp('SeriesInstanceUID', p.dict.name{k}), i = i(end);
elseif numel(i)>1 % +1 tags found, add vr to try again if expl
if hasVR
tg = [tg p.dict.vr{k}]; %#ok
i = strfind(bc, tg);
i = i(mod(i,2)==1);
if numel(i)~=1, toSearch = false; break; end
else
toSearch = false; break; % switch to regular way
end
end
i = i + 4; % tag
if hasVR
vr = bc(i+(0:1)); i = i+2;
if any(vr>'Z') || any(vr<'A'), toSearch = false; break; end
if strcmp(vr, 'UN') || strcmp(vr, 'OB'), vr = p.dict.vr{k}; end
else
vr = p.dict.vr{k};
end
[n, nvr] = val_len(vr, b8(i+(0:5)), hasVR, swap); i = i+nvr;
if n==0, continue; end % dont assign empty tag
if i+n-1>p.iPixelData, break; end
[dat, info] = read_val(b8(i+(0:n-1)), vr, swap);
if ~isempty(info), toSearch = false; break; end % re-do in regular way
if ~isempty(dat), s.(p.dict.name{k}) = dat; end
end
end
i = iTagStart + 1;
while ~toSearch
if i >= p.iPixelData
if strcmp(name, 'PixelData') % iPixelData might be in img
p.iPixelData = iPre + p.expl*4 + 7; % overwrite previous
p.bytes = ch2int32(b8(p.iPixelData+(-3:0)), p.be);
elseif p.iPixelData < fSize % has PixelData
info = ['End of file reached: likely error: ' s.Filename];
end
break; % done or give up
end
iPre = i; % back it up for PixelData
[dat, name, info, i, tg] = read_item(b8, i, p);
if ~isempty(info), break; end
if ~p.fullHdr && tg>p.dict.tag(end), break; end % done for partial hdr
if isempty(dat) || isnumeric(name), continue; end
s.(name) = dat;
if strcmp(name, 'Manufacturer')
[p, dict] = updateVendor(p, dat);
elseif tg>=2621697 && ~isfield(p, 'nFrames') % BitsAllocated
p = get_nFrames(s, p, b8); % only make code here cleaner
end
end
if p.iPixelData < fSize+1
s.PixelData.Start = p.iPixelData;
s.PixelData.Bytes = p.bytes;
end
if isfield(s, 'CSAImageHeaderInfo') % Siemens CSA image header
s.CSAImageHeaderInfo = read_csa(s.CSAImageHeaderInfo);
end
if isfield(s, 'CSASeriesHeaderInfo') % series header
s.CSASeriesHeaderInfo = read_csa(s.CSASeriesHeaderInfo);
end
if isfield(s, 'ProtocolDataBlock') % GE
s.ProtocolDataBlock = read_ProtocolDataBlock(s.ProtocolDataBlock);
end
%% nested function: update Manufacturer
function [p, dict] = updateVendor(p, vendor)
if ~isempty(p.dict.vendor) && strncmpi(vendor, p.dict.vendor, 2)
dict = p.dict; % in case dicm_hdr asks 3rd output
return;
end
dict_full = dicm_dict(vendor);
if ~p.fullHdr && isfield(p.dict, 'fields')
dict = dicm_dict(vendor, p.dict.fields);
else
dict = dict_full;
end
p.dict = dict;
end
end % main func
%% subfunction: read dicom item. Called by dicm_hdr and read_sq
function [dat, name, info, i, tag] = read_item(b8, i, p)
dat = []; name = nan; info = ''; vr = 'CS'; % vr may be used if implicit
group = b8(i+(0:1)); i=i+2;
swap = p.be && ~isequal(group, [2 0]); % good news: no 0x0200 group
group = ch2int16(group, swap);
elmnt = ch2int16(b8(i+(0:1)), swap); i=i+2;
tag = group*65536 + elmnt;
if tag == 4294893581 % || tag == 4294893789 % FFFEE00D or FFFEE0DD
i = i+4; % skip length
return; % return in case n is not 0
end
swap = p.be && group~=2;
hasVR = p.expl || group==2;
if hasVR, vr = char(b8(i+(0:1))); i = i+2; end % 2-byte VR
[n, nvr] = val_len(vr, b8(i+(0:5)), hasVR, swap); i = i + nvr;
if n==0, return; end % empty val
% Look up item name in dictionary
ind = find(p.dict.tag == tag, 1);
if ~isempty(ind)
name = p.dict.name{ind};
if strcmp(vr, 'UN') || strcmp(vr, 'OB') || ~hasVR, vr = p.dict.vr{ind}; end
elseif tag==524400 % in case not in dict
name = 'Manufacturer';
elseif tag==131088 % need TransferSyntaxUID even if not in dict
name = 'TransferSyntaxUID';
elseif tag==593936 % 0x0009 0010 GEIIS not dicom compliant
i = i+n; return; % seems n is not 0xffffffff
elseif p.fullHdr
if elmnt==0, i = i+n; return; end % skip GroupLength
if mod(group,2), name = sprintf('Private_%04x_%04x', group, elmnt);
else, name = sprintf('Unknown_%04x_%04x', group, elmnt);
end
if ~hasVR, vr = 'UN'; end % not in dict, will leave as uint8
elseif n<4294967295 % no skip for SQ with length 0xffffffff
i = i+n; return;
end
% compressed PixelData, n can be 0xffffffff
if ~hasVR && n==4294967295, vr = 'SQ'; end % best guess
if n+i>p.iPixelData && ~strcmp(vr, 'SQ'), i = i+n; return; end % PixelData or err
% fprintf('(%04x %04x) %s %6.0f %s\n', group, elmnt, vr, n, name);
if strcmp(vr, 'SQ')
nEnd = min(i+n, p.iPixelData); % n is likely 0xffff ffff
[dat, info, i] = read_sq(b8, i, nEnd, p, tag==1375769136); % isPerFrameSQ?
else
[dat, info] = read_val(b8(i+(0:n-1)), vr, swap); i=i+n;
end
% if group==33
% fprintf('\t''%04X'' ''%04X'' ''%s'' ''%s'' ', group, elmnt, vr, name);
% if numel(dat)>99, fprintf('''Long''');
% elseif ischar(dat), fprintf('''%s''', dat);
% elseif isnumeric(dat), fprintf(''''); fprintf('%g ', dat); fprintf('''');
% else, fprintf('''SQ''');
% end
% fprintf('\n');
% end
end
%% Subfunction: decode SQ, called by read_item (recursively)
% SQ structure:
% while isItem (FFFE E000, Item) % Item_1, Item_2, ...
% loop tags under the Item till FFFE E00D, ItemDelimitationItem
% return if FFFE E0DD SequenceDelimitationItem (not checked)
function [rst, info, i] = read_sq(b8, i, nEnd, p, isPerFrameSQ)
rst = []; info = ''; tag1 = []; j = 0; % j is SQ Item index
while i<nEnd % loop through multi Item under the SQ
tag = b8(i+([2 3 0 1])); i = i+4;
if p.be, tag = tag([2 1 3 4]); end
tag = ch2int32(tag, 0);
if tag ~= 4294893568, i = i+4; return; end % only do FFFE E000, Item
n = ch2int32(b8(i+(0:3)), p.be); i = i+4; % n may be 0xffff ffff
n = min(i+n, nEnd);
j = j + 1;
% This 'if' block deals with partial PerFrameSQ: j and i jump to a frame.
% The 1/2/nf frame scheme will have problem in case that tag1 in 1st frame
% is not the first tag in other frames. Then the tags before tag1 in other
% frames will be treated as for previous frame. This is very unlikely since
% the 1st tag is almost always a SQ, like MREchoSequence
if isPerFrameSQ
if ischar(p.iFrames) % 'all' frames
if j==1 && ~isnan(p.nFrames), rst.FrameStart = nan(1, p.nFrames); end
rst.FrameStart(j) = i-9;
elseif j==1, i0 = i-8; % always read 1st frame, save i0 in case of re-do
elseif j==2 % always read 2nd frame, and find start ind for all frames
if isnan(p.nFrames) || isempty(tag1) % 1st frame has no asked tag
p.iFrames = 'all'; rst = []; j = 0; i = i0; % re-do the SQ
continue; % re-do
end
tag1 = char(typecast(uint32(tag1), 'uint8'));
tag1 = tag1([3 4 1 2]);
if p.be && ~isequal(tag1(1:2),[2 0]), tag1 = tag1([2 1 4 3]); end
ind = strfind(char(b8(i0:p.iPixelData)), tag1) + i0 - 1;
ind = ind(mod(ind,2)==1);
nInd = numel(ind);
if nInd ~= p.nFrames
tag1PerF = nInd / p.nFrames;
if mod(tag1PerF, 1) > 0 % not integer, read all frames
p.iFrames = 'all'; rst = []; j = 0; i = i0; % re-do SQ
fprintf(2, ['Failed to determine indice for frames. ' ...
'Reading all frames. Maybe slow ...\n']);
continue;
elseif tag1PerF>1 % more than one ind for each frame
ind = ind(1:tag1PerF:nInd);
nInd = p.nFrames;
end
end
rst.FrameStart = ind-9; % 0-based
iItem = 2; % initialize here. Increase when j>2
iFrame = unique([1 2 round(p.iFrames) nInd]);
else % overwrite j with asked iFrame, overwrite i with start ind
iItem = iItem + 1;
j = iFrame(iItem);
i = ind(j); % start of tag1 for asked frame
n = nEnd; % use very end of the sq
end
end
Item_n = sprintf('Item_%g', j);
while i<n % loop through multi tags under one Item
[dat, name, info, i, tag] = read_item(b8, i, p);
if tag == 4294893581, break; end % FFFE E00D ItemDelimitationItem
if isempty(tag1), tag1 = tag; end % first detected tag for PerFrameSQ
if isempty(dat) || isnumeric(name), continue; end % 0-length or skipped
rst.(Item_n).(name) = dat;
end
end
end
%% subfunction: cast uint8/char to double. Better performance than typecast
function d = ch2int32(u8, swap)
if swap, u8 = u8([4 3 2 1]); end
d = double(u8);
d = d(1) + d(2)*256 + d(3)*65536 + d(4)*16777216; % d = d * 256.^(0:3)';
end
function d = ch2int16(u8, swap)
if swap, u8 = u8([2 1]); end
d = double(u8);
d = d(1) + d(2)*256;
end
%% subfunction: return value length, numel(b)=6
function [n, nvr] = val_len(vr, b, expl, swap)
len16 = 'AE AS AT CS DA DS DT FD FL IS LO LT PN SH SL SS ST TM UI UL US';
if ~expl % implicit, length irrevalent to vr (faked as CS)
n = ch2int32(b(1:4), swap);
nvr = 4; % bytes of VR
elseif ~isempty(strfind(len16, vr)) %#ok<*STREMP> % length in uint16
n = ch2int16(b(1:2), swap);
nvr = 2;
else % length in uint32 and skip 2 bytes
n = ch2int32(b(3:6), swap);
nvr = 6;
end
if n==13, n = 10; end % ugly bug fix for some old dicom file
end
%% subfunction: read value, called by search method and read_item
function [dat, info] = read_val(b, vr, swap)
if strcmp(vr, 'DS') || strcmp(vr, 'IS')
dat = sscanf(char(b), '%f\\'); % like 1\2\3
elseif ~isempty(strfind('AE AS CS DA DT LO LT PN SH ST TM UI UT', vr)) % char
dat = deblank(char(b));
else % numeric data, UN. SQ taken care of
fmt = vr2fmt(vr);
if isempty(fmt)
dat = [];
info = sprintf('Given up: Invalid VR (%d %d)', vr);
return;
end
dat = b'; % keep as bytes in case typecast fails
try dat = typecast(dat, fmt); end
if swap, dat = swapbytes(dat); end
end
info = '';
end
%% subfunction: numeric format str from VR
function fmt = vr2fmt(vr)
switch vr
case 'US', fmt = 'uint16';
case 'OB', fmt = 'uint8';
case 'FD', fmt = 'double';
case 'SS', fmt = 'int16';
case 'UL', fmt = 'uint32';
case 'SL', fmt = 'int32';
case 'FL', fmt = 'single';
case 'AT', fmt = 'uint16';
case 'OW', fmt = 'uint16';
case 'UN', fmt = 'uint8';
otherwise, fmt = '';
end
end
%% subfunction: get nFrames into p.nFrames
function p = get_nFrames(s, p, ch)
if isfield(s, 'NumberOfFrames')
p.nFrames = s.NumberOfFrames; % useful for PerFrameSQ
elseif all(isfield(s, {'Columns' 'Rows' 'BitsAllocated'})) && p.bytes<4294967295
if isfield(s, 'SamplesPerPixel'), spp = double(s.SamplesPerPixel);
else, spp = 1;
end
n = p.bytes * 8 / double(s.BitsAllocated);
p.nFrames = n / (spp * double(s.Columns) * double(s.Rows));
else
% FFFE E0DD, 4-byte len (zeros), 0020 9111 (FrameContentSequence)
% GE has no FFFE E0DD 0000 0000. Only FrameContentSequence tag is not safe
tg = char([254 255 221 224 0 0 0 0 32 0 17 145]);
if p.be, tg = tg([2 1 4 3 5:8 10 9 12 11]); end
if p.expl, tg = [tg 'SQ']; end
p.nFrames = numel(strfind(char(ch), tg));
if p.nFrames<1, p.nFrames = nan; end
end
end
%% subfunction: decode Siemens CSA image and series header
function csa = read_csa(csa)
b = csa';
if numel(b)<4 || ~strcmp(char(b(1:4)), 'SV10'), return; end % no op if not SV10
chDat = 'AE AS CS DA DT LO LT PN SH ST TM UI UN UT';
i = 8; % 'SV10' 4 3 2 1
try % in case of error, we return the original csa
nField = ch2int32(b(i+(1:4)), 0); i=i+8;
for j = 1:nField
i=i+68; % name(64) and vm(4)
vr = char(b(i+(1:2))); i=i+8; % vr(4), syngodt(4)
n = ch2int32(b(i+(1:4)), 0); i=i+8;
if n<1, continue; end % skip name decoding, faster
nam = regexp(char(b(i-84+(1:64))), '\w+', 'match', 'once');
isNum = isempty(strfind(chDat, vr));
% fprintf('%s %3g %s\n', vr, n, nam);
dat = [];
for k = 1:n % n is often 6, but often only the first contains value
len = ch2int32(b(i+(1:4)), 0); i=i+16;
if len<1, i = i+(n-k)*16; break; end % rest are empty too
foo = char(b(i+(1:len-1))); % exclude nul, need for Octave
i = i + ceil(len/4)*4; % multiple 4-byte
if isNum
tmp = sscanf(foo, '%f', 1); % numeric to double
if ~isempty(tmp), dat(k,1) = tmp; end %#ok
else
dat{k} = deblank(foo); %#ok
end
end
if ~isNum
dat(cellfun(@isempty, dat)) = []; %#ok
if isempty(dat), continue; end
if numel(dat)==1, dat = dat{1}; end
end
rst.(nam) = dat;
end
csa = rst;
end
end
%% subfunction: decode GE ProtocolDataBlock
function ch = read_ProtocolDataBlock(ch)
n = typecast(ch(1:4), 'int32') + 4; % nBytes, zeros may be padded to make 4x
if ~all(ch(5:6) == [31 139]') || n>numel(ch), return; end % gz signature
ch = nii_tool('LocalFunc', 'gunzip_mem', ch(5:n))';
ch = regexp(char(ch), '(\w*)\s+"(.*?)"\n', 'tokens');
ch = [ch{:}];
ch = struct(ch{:});
end
%% subfunction: get fields for multiframe dicom
function s1 = search_MF_val(s, s1, iFrame)
% s1 = search_MF_val(s, s1, iFrame);
% Arg 1: the struct returned by dicm_hdr for a multiframe dicom
% Arg 2: a struct with fields to search, and with initial value, such as
% zeros or nans. The number of rows indicates the number of values for the
% tag, and columns for frames indicated by iFrame, Arg 3.
% Arg 3: frame indice, length consistent with columns of s1 field values.
% Example:
% s = dicm_hdr('multiFrameFile.dcm'); % read only 1,2 and last frame by default
% s1 = struct('ImagePositionPatient', nan(3, s.NumberOfFrames)); % define size
% s1 = search_MF_val(s, s1, 1:s.NumberOfFrames); % get values
% This is MUCH faster than asking all frames by dicm_hdr, and avoid to get into
% annoying SQ levels under PerFrameFuntionalGroupSequence. In case a tag is not
% found in PerFrameSQ, the code will search SharedSQ and common tags, and will
% ignore the 3th arg and duplicate the same value for all frames.
if ~isfield(s, 'PerFrameFunctionalGroupsSequence'), return; end
expl = false;
be = false;
if isfield(s, 'TransferSyntaxUID')
expl = ~strcmp(s.TransferSyntaxUID, '1.2.840.10008.1.2');
be = strcmp(s.TransferSyntaxUID, '1.2.840.10008.1.2.2');
end
fStart = s.PerFrameFunctionalGroupsSequence.FrameStart; % error if no FrameStart
fid = fopen(s.Filename);
b0 = fread(fid, fStart(1), 'uint8=>char')'; % before 1st frame in PerFrameSQ
b = fread(fid, s.PixelData.Start-fStart(1), 'uint8=>char')'; % within PerFrameSQ
fclose(fid);
fStart(end+1) = s.PixelData.Start; % for later ind search
fStart = fStart - fStart(1) + 1; % 1-based index in b
flds = fieldnames(s1);
dict = dicm_dict(s.Manufacturer, flds);
len16 = 'AE AS AT CS DA DS DT FD FL IS LO LT PN SH SL SS ST TM UI UL US';
chDat = 'AE AS CS DA DT LO LT PN SH ST TM UI UT';
nf = numel(iFrame);
for i = 1:numel(flds)
k = find(strcmp(dict.name, flds{i}), 1, 'last'); % GE has another ipp tag
if isempty(k), continue; end % likely private tag for another vendor
vr = dict.vr{k};
group = dict.group(k);
isBE = be && group~=2;
isEX = expl || group==2;
tg = char(typecast([group dict.element(k)], 'uint8'));
if isBE, tg = tg([2 1 4 3]); end
if isEX, tg = [tg vr]; end %#ok
ind = strfind(b, tg);
ind = ind(mod(ind,2)>0); % indice is odd
if isempty(ind) % no tag in PerFrameSQ, try tag before PerFrameSQ
ind = strfind(b0, tg);
ind = ind(mod(ind,2)>0);
if ~isempty(ind)
k = ind(1) + numel(tg); % take 1st in case of multiple
[n, nvr] = val_len(vr, uint8(b0(k+(0:5))), isEX, isBE); k = k + nvr;
a = read_val(uint8(b0(k+(0:n-1))), vr, isBE);
if ischar(a), a = {a}; end
s1.(flds{i}) = repmat(a, 1, nf); % all frames have the same value
end
continue;
end
len = 4; % bytes of tag value length (uint32)
if ~isEX % implicit, length irrevalent to VR
ind = ind + 4; % tg(4)
elseif ~isempty(strfind(len16, vr)) % data length in uint16
ind = ind + 6; % tg(4), vr(2)
len = 2;
else % length in uint32: skip 2 bytes
ind = ind + 8; % tg(4), vr(2), skip(2)
end
isCH = ~isempty(strfind(chDat, vr)); % char data
isDS = strcmp(vr, 'DS') || strcmp(vr, 'IS');
if ~isCH && ~isDS % numeric data, UN or SQ
fmt = vr2fmt(vr);
if isempty(fmt), continue; end % skip SQ
end
for k = 1:nf
j = iFrame(k); % asked frame index
j = find(ind>fStart(j) & ind<fStart(j+1), 1); % index in ind
if isempty(j), continue; end % no tag for this frame
if len==2, n = ch2int16(b(ind(j)+(0:1)), isBE);
else, n = ch2int32(b(ind(j)+(0:3)), isBE);
end
a = b(ind(j)+len+(0:n-1));
if isDS
a = sscanf(a, '%f\\'); % like 1\2\3
try s1.(flds{i})(:,k) = a; end %#ok<*TRYNC> ignore in case of error
elseif isCH
try s1.(flds{i}){k} = deblank(a); end
else
a = typecast(uint8(a), fmt)';
if isBE, a = swapbytes(a); end
try s1.(flds{i})(:,k) = a; end
end
end
end
end
%% subfunction: read PAR file, return struct like that from dicm_hdr.
function [s, err] = philips_par(fname)
err = '';
fid = fopen(fname);
if fid<0, s = []; err = ['File not exist: ' fname]; return; end
fullName = fopen(fid); % name with full path
[pth, nam, ext] = fileparts(fullName);
if strcmpi(ext, '.xml') % if this is an xml file, convert to a temporary PAR file
fclose(fid);
fname = fullfile(tempdir, [nam '_tmp.PAR']);
xml2par(fullName, fname);
delTmpPar = onCleanup(@() delete(fname));
fid = fopen(fname);
end
str = fread(fid, inf, '*char')'; % read all as char
fclose(fid);
str = strrep(str, char([13 10]), char(10)); % remove char(13)
ch = regexp(str, '.*?(?=IMAGE INFORMATION DEFINITION)', 'match', 'once');
V = regexpi(ch, 'image export tool\s*(V[\d\.]+)', 'tokens', 'once');
if isempty(V), err = 'Not PAR file'; s = []; return; end
V = V{1};
% Fix V4 bug: based on Chris observation. Only those in table are 1:3
% The ugly hard-coded order is the simple solution
if strcmpi(V, 'V4'), ax_order = 1:3; else, ax_order = [3 1 2]; end
s.SoftwareVersion = [V '\' ext(2:end)]; % xml files have "PRIDE V5"
s.PatientName = par_attr(ch, 'Patient name', 0);
s.StudyDescription = par_attr(ch, 'Examination name', 0);
s.SeriesDescription = nam;
s.ProtocolName = par_attr(ch, 'Protocol name', 0);
a = par_attr(ch, 'Examination date/time', 0);
s.AcquisitionDateTime = a(isstrprop(a, 'digit'));
s.SeriesNumber = par_attr(ch, 'Acquisition nr');
% s.ReconstructionNumberMR = par_attr(ch, 'Reconstruction nr');
% s.MRSeriesScanDuration = par_attr(ch, 'Scan Duration');
s.NumberOfEchoes = par_attr(ch, 'Max. number of echoes');
a = par_attr(ch, 'Patient position', 0);
if isempty(a), a = par_attr(ch, 'Patient Position', 0); end
if ~isempty(a)
if numel(a)>4, s.PatientPosition = a(regexp(a, '\<.'));
else, s.PatientPosition = a;
end
end
s.MRAcquisitionType = par_attr(ch, 'Scan mode', 0);
s.ScanningSequence = par_attr(ch, 'Technique', 0); % ScanningTechnique
typ = par_attr(ch, 'Series Type', 0); typ(isspace(typ)) = '';
s.ImageType = ['PhilipsPAR\' typ '\' s.ScanningSequence];
s.RepetitionTime = par_attr(ch, 'Repetition time');
s.WaterFatShift = par_attr(ch, 'Water Fat shift');
s.EPIFactor = par_attr(ch, 'EPI factor');
% s.DynamicSeries = par_key(ch, 'Dynamic scan'); % 0 or 1
isDTI = par_attr(ch, 'Diffusion')>0;
if isDTI
s.ImageType = [s.ImageType '\DIFFUSION\'];
s.DiffusionEchoTime = par_attr(ch, 'Diffusion echo time'); % ms
end
% Get list of para meaning for the table, and col index of each para
i1 = regexpi(str, 'IMAGE INFORMATION DEFINITION', 'once');
i2 = regexpi(str, '= IMAGE INFORMATION ='); i2 = i2(end);
ind = regexp(str(i1:i2), '\n#') + i1;
colLabel = {}; iColumn = [];
for i = 1:numel(ind)-1
a = str(ind(i)+1:ind(i+1)-2); % a line
i1 = regexp(a, '[<(]{1}'); % need first '<' or '(', and last '('
if isempty(i1), continue; end
nCol = sscanf(a(i1(end)+1:end), '%g');
if isempty(nCol), nCol = 1; end
colLabel{end+1} = strtrim(a(1:i1(1)-1)); %#ok para name
iColumn(end+1) = nCol; %#ok number of columns in the table for this para
end
iColumn = cumsum([1 iColumn]); % col start ind for corresponding colLabel
keyInLabel = @(key)strcmpi(colLabel, key);
colIndex = @(key)iColumn(keyInLabel(key));
i1 = regexp(str(i2:end), '\n\s*\d+', 'once') + i2;
n = iColumn(end)-1; % number of items each row, 41 for V4
para = sscanf(str(i1:end), '%g'); % read all numbers
nFrame = floor(numel(para) / n);
para = reshape(para(1:n*nFrame), n, nFrame)'; % whole table now
% SortFrames solves XYTZ, unusual slice order, incomplete volume etc
keys = {'dynamic scan number' 'gradient orientation number' 'echo number' ...
'cardiac phase number' 'image_type_mr' 'label type' 'scanning sequence'};
ic = []; for i = 1:numel(keys), ic = [ic colIndex(keys{i})]; end %#ok
sort_frames = dicm2nii('', 'sort_frames', 'func_handle');
sl = [para(:, colIndex('slice number')) para(:, colIndex('diffusion_b_factor'))];
[ind_sort, nSL] = sort_frames(sl, para(:, ic));
a = par_val('index in REC file', 1:nFrame); % always 0:nFrame-1 ?
a(a+1) = 1:nFrame; % [~, a] = sort(a);
a = a(ind_sort)';
if ~isequal(a, 1:nFrame), s.SortFrames = a; end % used only in dicm2nii
para = para(ind_sort, :); % XYZT order
s.LocationsInAcquisition = nSL;
s.NumberOfFrames = numel(ind_sort); % may be smaller than nFrame
s.NumberOfTemporalPositions = s.NumberOfFrames/nSL;
iVol = (0:s.NumberOfTemporalPositions-1)*nSL + 1; % already XYZT
fld = 'ComplexImageComponent';
typ = {'MAGNITUDE' 'REAL' 'IMAGINARY' 'PHASE'};
imgType = para(iVol, colIndex('image_type_mr')); % 0:3
imgType(imgType==16) = 0;
imgType(imgType==17) = 3;
imgType(imgType==18) = 1;
imgType(imgType>3) = 0; % unknown treated as magnitude
if numel(iVol) == 1
s.ComplexImageComponent = typ{imgType(1)+1};
elseif any(diff(imgType) ~= 0) % more than 1 type of image
s.(fld) = 'MIXED';
s.Volumes.(fld) = typ(imgType+1); % one for each vol
s.Volumes.RescaleIntercept = para(iVol, colIndex('rescale intercept'));
s.Volumes.RescaleSlope = para(iVol, colIndex('rescale slope'));
s.Volumes.MRScaleSlope = para(iVol, colIndex('scale slope'));
else
s.ComplexImageComponent = typ(imgType(1)+1); % cellstr
end
% These columns should be the same for nifti-convertible images:
cols = {'image pixel size' 'recon resolution' 'image angulation' ...
'slice thickness' 'slice gap' 'slice orientation' 'pixel spacing'};
if ~strcmp(s.((fld)), 'MIXED')
cols = [cols {'rescale intercept' 'rescale slope' 'scale slope'}];
end
ind = [];
for i = 1:numel(cols)
j = find(keyInLabel(cols{i}));
if isempty(j), continue; end % some not in V3
ind = [ind iColumn(j):iColumn(j+1)-1]; %#ok
end
a = para(:, ind);
a = abs(diff(a));
if any(a(:) > 1e-5)
err = sprintf('Inconsistent image size, bits etc: %s', fullName);
fprintf(2, ' %s. \n', err);
s = []; return;
end
% s.EchoNumber = getTableVal('echo number', 1:s.NumberOfFrames);
% 'pixel spacing' and 'slice gap' have poor precision for v<=4?
% It may be wrong to use FOV, maybe due to partial Fourier?
if strncmp(V, 'V3', 2)
s.BitsAllocated = par_attr(ch, 'Image pixel size', 1);
res = par_attr(ch, 'Recon resolution', 1);
s.SliceThickness = par_attr(ch, 'Slice thickness', 1);
gap = par_attr(ch, 'Slice gap', 1);
s.TurboFactor = par_attr('TURBO factor', 1);
s.NumberOfAverages = par_attr(ch, 'Number of averages', 1);
else
s.BitsAllocated = par_val('image pixel size');
res = par_val('recon resolution');
s.SliceThickness = par_val('slice thickness');
gap = par_val('slice gap');
s.TurboFactor = par_val('TURBO factor');
s.NumberOfAverages = par_val('number of averages');
end
s.Columns = res(1);
s.Rows = res(2);
s.SpacingBetweenSlices = gap + s.SliceThickness;
a = par_val('pixel spacing');
s.PixelSpacing = a(:);
s.RescaleIntercept = par_val('rescale intercept');
s.RescaleSlope = par_val('rescale slope');
s.MRScaleSlope = par_val('scale slope');
s.EchoTimes = par_val('echo_time', iVol);
s.EchoTime = s.EchoTimes(1);
s.FlipAngle = par_val('image_flip_angle');
s.CardiacTriggerDelayTimes = par_val('trigger_time', iVol);
% s.TimeOfAcquisition = par_val('dyn_scan_begin_time', 1:s.NumberOfFrames);
if isDTI
s.B_value = par_val('diffusion_b_factor', iVol);
a = par_val('diffusion', iVol);
if ~isempty(a), s.bvec_original = a(:, ax_order); end
end
posMid = par_attr(ch, 'Off Centre midslice'); % (ap,fh,rl) [mm]
posMid = posMid([3 1 2]); % better precision than those in the table
rotAngle = par_attr(ch, 'Angulation midslice'); % (ap,fh,rl) deg
a = rotAngle([3 1 2]) /180*pi; % always this order?
R = makehgtform('xrotate', a(1), 'yrotate', a(2), 'zrotate', a(3));
R = R(1:3, :);
iOri = par_val('slice orientation'); % 1/2/3 for TRA/SAG/COR
iOri = mod(iOri+1, 3) + 1;
a = {'SAGITTAL' 'CORONAL' 'TRANSVERSAL'};
s.SliceOrientation = a{iOri};
if iOri == 1
R(:,[1 3]) = -R(:,[1 3]);
R = R(:, [2 3 1 4]);
elseif iOri == 2
R(:,3) = -R(:,3);
R = R(:, [1 3 2 4]);
end
a = par_attr(ch, 'Preparation direction', 0); % Anterior-Posterior
if ~isempty(a)
a = a(regexp(a, '\<.')); % 'AP'
s.Stack.Item_1.MRStackPreparationDirection = a;
iPhase = strfind('LRAPFH', a(1));
iPhase = ceil(iPhase/2); % 1/2/3
if iPhase == (iOri==1)+1, a = 'ROW'; else, a = 'COL'; end
s.InPlanePhaseEncodingDirection = a;
end
s.ImageOrientationPatient = R(1:6)';
R = R * diag([s.PixelSpacing; s.SpacingBetweenSlices; 1]);
R(:,4) = posMid; % 4th col is mid slice center position
a = par_val('image offcentre');
s.SliceLocation = a(ax_order(iOri)); % center loc for 1st slice
if sign(R(iOri,3)) ~= sign(posMid(iOri)-s.SliceLocation)
R(:,3) = -R(:,3);
end
R(:,4) = R * [-([s.Columns s.Rows nSL]-1)/2 1]'; % vol center to corner of 1st
s.ImagePositionPatient = R(:,4);
s.LastFile.ImagePositionPatient = R * [0 0 nSL-1 1]'; % last slice
s.Manufacturer = 'Philips';
s.Filename = fullfile(pth, [nam '.REC']); % rest for dicm_img
s.PixelData.Start = 0;
s.PixelData.Bytes = s.Rows * s.Columns * nFrame * s.BitsAllocated / 8;
% nested function: set field if the key is in colTable
function val = par_val(key, iRow)
if nargin<2, iRow = 1; end
iCol = find(keyInLabel(key));
val = para(iRow, iColumn(iCol):iColumn(iCol+1)-1);
end
% subfunction: return value specified by key in PAR file
function val = par_attr(ch, key, isNum)
expr = ['\n.\s*' key '.*?:(.*?)\n']; % \n. key ... : val \n
val = strtrim(regexp(ch, expr, 'tokens', 'once'));
if isempty(val), val = ''; else, val = val{1}; end
if nargin<3 || isNum, val = sscanf(val, '%g'); end
end
end
%% subfunction: read AFNI HEAD file, return struct like that from dicm_hdr.
function [s, err] = afni_head(fname)
err = '';
fid = fopen(fname);
if fid<0, s = []; err = ['File not exist: ' fname]; return; end
str = fread(fid, inf, '*char')';
fname = fopen(fid);
fclose(fid);
i = strfind(str, 'DATASET_DIMENSIONS');
if isempty(i), s = []; err = 'Not brik header file'; return; end
% these make dicm_nii.m happy
[~, foo] = fileparts(fname);
% s.IsAFNIHEAD = true;
s.ProtocolName = foo;
s.ImageType = ['AFNIHEAD\' afni_key('TYPESTRING')];
foo = afni_key('BYTEORDER_STRING'); % "LSB_FIRST" or "MSB_FIRST".
if strcmpi(foo, 'MSB_FIRST'), s.TransferSyntaxUID = '1.2.840.10008.1.2.2'; end
foo = afni_key('BRICK_FLOAT_FACS');
if any(diff(foo)~=0), err = 'Inconsistent BRICK_FLOAT_FACS';
s = []; return;
end
if foo(1)==0, foo = 1; end
s.RescaleSlope = foo(1);
s.RescaleIntercept = 0;
foo = afni_key('BRICK_TYPES');
if any(diff(foo)~=0), err = 'Inconsistent DataType'; s = []; return; end
foo = foo(1);
if foo == 0
s.BitsAllocated = 8; s.PixelData.Format = '*uint8';
elseif foo == 1
s.BitsAllocated = 16; s.PixelData.Format = '*int16';
elseif foo == 3
s.BitsAllocated = 32; s.PixelData.Format = '*single';
else
error('Unsupported BRICK_TYPES: %g', foo);
end
hist = afni_key('HISTORY_NOTE');
i = strfind(hist, 'Time:') + 6;
if ~isempty(i)
dat = sscanf(hist(i:end), '%11c', 1); % Mar 1 2010
dat = datenum(dat, 'mmm dd yyyy');
s.AcquisitionDateTime = datestr(dat, 'yyyymmdd');
end
i = strfind(hist, 'Sequence:') + 9;