-
Notifications
You must be signed in to change notification settings - Fork 44
/
dicm2nii.m
3111 lines (2879 loc) · 124 KB
/
dicm2nii.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 varargout = dicm2nii(src, niiFolder, fmt)
% Convert dicom and more into nii or img/hdr files.
%
% DICM2NII(dcmSource, niiFolder, outFormat)
%
% The input arguments are all optional:
% 1. source file or folder can be a zip or tgz file, a folder containing dicom
% files, or other convertible files. It can also contain wildcards like
% 'run1_*' for all files start with 'run1_'.
% 2. folder to save result files.
% 3. output file format:
% 0 or '.nii' for single nii uncompressed.
% 1 or '.nii.gz' for single nii compressed (default).
% 2 or '.hdr' for hdr/img pair uncompressed.
% 3 or '.hdr.gz' for hdr/img pair compressed.
% 4 or '.nii 3D' for 3D nii uncompressed (SPM12).
% 5 or '.nii.gz 3D' for 3D nii compressed.
% 6 or '.hdr 3D' for 3D hdr/img pair uncompressed (SPM8).
% 7 or '.hdr.gz 3D' for 3D hdr/img pair compressed.
% 'bids' for bids data structure (http://bids.neuroimaging.io/)
%
% Typical examples:
% DICM2NII; % bring up user interface if there is no input argument
% DICM2NII('D:/myProj/zip/subj1.zip', 'D:/myProj/subj1/data'); % zip file
% DICM2NII('D:/myProj/subj1/dicom/', 'D:/myProj/subj1/data'); % folder
%
% Less common examples:
% DICM2NII('D:/myProj/dicom/', 'D:/myProj/subj2/data', 'nii'); % no gz compress
% DICM2NII('D:/myProj/dicom/run2*', 'D:/myProj/subj/data'); % convert run2 only
% DICM2NII('D:/dicom/', 'D:/data', '3D.nii'); % SPM style files
%
% If there is no input, or any of the first two input is empty, the graphic user
% interface will appear.
%
% If the first input is a zip/tgz file, such as those downloaded from a dicom
% server, DICM2NII will extract files into a temp folder, create NIfTI files
% into the data folder, and then delete the temp folder. For this reason, it is
% better to keep the compressed file as backup.
%
% If a folder is the data source, DICM2NII will convert all files in the folder
% and its subfolders (there is no need to sort files for different series).
%
% The output file names adopt SeriesDescription or ProtocolName of each series
% used on scanner console. If both original and MoCo series are present, '_MoCo'
% will be appended for MoCo series. For phase image, such as those from field
% map, '_phase' will be appended to the name. If multiple subjects data are
% mixed (highly discouraged), subject name will be in file name. In case of name
% conflict, SeriesNumber, such as '_s005', will be appended to make file names
% unique. It is suggested to use short, descriptive and distinct
% SeriesDescription on the scanner console.
%
% For SPM 3D files, the file names will have volume index in format of '_00001'
% appended to above name.
%
% Please note that, if a file in the middle of a series is missing, the series
% will normally be skipped without converting, and a warning message in red text
% will be shown in Command Window. The message will also be saved into a text
% file under the data folder.
%
% A Matlab data file, dcmHeaders.mat, is always saved into the data folder. This
% file contains dicom header from the first file for created series and some
% information from last file in field LastFile. Some extra information is also
% saved into this file. For MoCo series, motion parameters (RBMoCoTrans and
% RBMoCoRot) are also saved.
%
% Slice timing information, if available, is stored in nii header, such as
% slice_code and slice_duration. But the simple way may be to use the field
% SliceTiming in dcmHeaders.mat. That timing is actually those numbers for FSL
% when using custom slice timing. This is the universal method to specify any
% kind of slice order, and for now, is the only way which works for multiband.
% Slice order is one of the most confusing parameters, and it is recommended to
% use this method to avoid mistake. Following shows how to convert this timing
% into slice timing in ms and slice order for SPM:
%
% load('dcmHeaders.mat'); % or drag and drop the MAT file into Command Window
% s = h.myFuncSeries; % field name is the same as nii file name
% spm_ms = (0.5 - s.SliceTiming) * s.RepetitionTime;
% [~, spm_order] = sort(-s.SliceTiming);
%
% Some information, such as TE, phase encoding direction and effective dwell
% time, are stored in descrip of nii header. These are useful for fieldmap B0
% unwarp correction. Acquisition start time and date are also stored, and this
% may be useful if one wants to align the functional data to some physiological
% recording, like pulse, respiration or ECG.
%
% If there is DTI series, bval and bvec files will be generated for FSL etc.
% bval and bvec are also saved in the dcmHeaders.mat file.
%
% Starting from 20150514, the converter stores some useful information in NIfTI
% text extension (ecode=6). nii_tool can decode these information easily:
% ext = nii_tool('ext', 'myNiftiFile.nii'); % read NIfTI extension
% ext.edata_decoded contains all above mentioned information, and more. The
% included nii_viewer can show the extension by Window->Show NIfTI ext.
%
% Several preference can be set from dicm2nii GUI. The preference change stays
% in effect until it is changed next time.
%
% One of preference is to save a .json file for each converted NIfTI. For more
% information about the purpose of json file, check
% http://bids.neuroimaging.io/
%
% By default, the converter will use parallel pool for dicom header reading if
% there are 2000+ files. User can turn this off from GUI.
%
% By default, the PatientName is stored in NIfTI hdr and ext. This can be turned
% off from GUI.
%
% Please note that some information, such as the slice order information, phase
% encoding direction and DTI bvec are in image reference, rather than NIfTI
% coordinate system. This is because most analysis packages require information
% in image space. For this reason, in case the image in a NIfTI file is flipped
% or re-oriented, these information may not be correct anymore.
%
% Please report any bug to [email protected] or at
% https://github.com/xiangruili/dicm2nii/issues
% http://www.mathworks.com/matlabcentral/fileexchange/42997
%
% To cite the work and for more detail about the conversion, check the paper at
% http://www.sciencedirect.com/science/article/pii/S0165027016300073
%
% See also NII_VIEWER, NII_MOCO, NII_STC
% Thanks to:
% Jimmy Shen's Tools for NIfTI and ANALYZE image,
% Chris Rorden's dcm2nii pascal source code,
% Przemyslaw Baranski for direction cosine matrix to quaternions.
% History (yymmdd):
% 130512 Publish to CCBBI users (Xiangrui Li).
% 130823 Remove dependency on Image Processing Toolbox.
% 130919 Work for GE and Philips dicom at Chris R website.
% 130923 Work for Philips PAR/REC pair files.
% 131021 Implement conversion for AFNI HEAD/BRIK.
% 131219 Write warning message to a file in data folder (Gui's suggestion).
% 140621 Support tgz file as data source.
% 150112 Use nii_tool.m, remove make_nii, save_nii etc from this file.
% 150209 Support output format for SPM style: 3D output;
% 150405 Implement BrainVoyager dmr/fmr/vmr conversion: need BVQX_file.
% 150514 set_nii_ext: start to store txt edata (ecode=6).
% 160127 dicm_hdr & dicm_img: support big endian dicom.
% 160229 reorient now makes det<0, instead negative 1st axis (cor slice affected).
% 170404 set MB slice_code to 0 to avoid FreeSurfer error. Thx JacobM.
% 170826 Use 'VolumeTiming' for missing volumes based on BIDS.
% 171211 Make it work for Siemens multiframe dicom (seems 3D only).
% 180523 set_nii_hdr: use MRScaleSlope for Philips, same as dcm2niiX default.
% 180530 store EchoTimes and CardiacTriggerDelayTimes;
% split_components: not only phase, json for each file (thx ChrisR).
% 180614 Implement scale_16bit: free precision for tools using 16-bit datatype.
% 180914 support UIH dicm, both GRID (mosaic) and regular.
% 190122 add BIDS support. [email protected]
% Most later history relies on GitHub
% TODO: need testing files to figure out following parameters:
% flag for MOCO series for GE/Philips
% GE non-axial slice (phase: ROW) bvec sign
if nargout, varargout{1} = ''; end
if nargin==3 && ischar(fmt) && strcmp(fmt, 'func_handle') % special purpose
varargout{1} = str2func(niiFolder);
return;
end
%% Deal with output format first, and error out if invalid
if nargin<3 || isempty(fmt), fmt = 1; end % default .nii.gz
no_save = ischar(fmt) && strcmp(fmt, 'no_save');
if no_save, fmt = 'nii'; end
bids = false;
if ischar(fmt) && strcmpi(fmt,'BIDS')
bids = true;
fmt = '.nii.gz';
end
if ischar(fmt) && strcmpi(fmt,'BIDSNII')
bids = true;
fmt = '.nii';
end
if bids && verLessThanOctave
fprintf('BIDS conversion is easier with MATLAB R2018a or later.\n')
end
if (isnumeric(fmt) && any(fmt==[0 1 4 5])) || ...
(ischar(fmt) && containsI(fmt, 'nii'))
ext = '.nii';
elseif (isnumeric(fmt) && any(fmt==[2 3 6 7])) || (ischar(fmt) && containsI(fmt, {'hdr' 'img'}))
ext = '.img';
else
error(' Invalid output file format (the 3rd input).');
end
if (isnumeric(fmt) && mod(fmt,2)) || (ischar(fmt) && containsI(fmt, '.gz'))
ext = [ext '.gz']; % gzip file
end
rst3D = (isnumeric(fmt) && fmt>3) || (ischar(fmt) && containsI(fmt, '3D'));
if nargin<1 || isempty(src) || (nargin<2 || isempty(niiFolder))
create_gui; % show GUI if input is not enough
return;
end
%% Deal with niiFolder
if ~isfolder(niiFolder), mkdir(niiFolder); end
niiFolder = strcat(fullName(niiFolder), filesep);
converter = ['dicm2nii.m ' getVersion];
if errorLog('', niiFolder) && ~no_save % remember niiFolder for later call
more off;
disp(['Xiangrui Li''s ' converter ' (feedback to [email protected])']);
end
%% Deal with data source
tic;
if isnumeric(src)
error('Invalid dicom source.');
elseif iscellstr(src) %#ok<*ISCLSTR> % multiple files/folders
fnames = {};
for i = 1:numel(src)
if isfolder(src{i})
fnames = [fnames filesInDir(src{i})];
else
a = dir(src{i});
if isempty(a), continue; end
dcmFolder = fileparts(fullName(src{i}));
fnames = [fnames fullfile(dcmFolder, a.name)];
end
end
elseif isfolder(src) % folder
fnames = filesInDir(src);
elseif ~exist(src, 'file') % like input: run1*.dcm
fnames = dir(src);
if isempty(fnames), error('%s does not exist.', src); end
fnames([fnames.isdir]) = [];
dcmFolder = fileparts(fullName(src));
fnames = strcat(dcmFolder, filesep, {fnames.name});
elseif ischar(src) % 1 dicom or zip/tgz file
dcmFolder = fileparts(fullName(src));
unzip_cmd = compress_func(src);
if isempty(unzip_cmd)
fnames = dir(src);
fnames = strcat(dcmFolder, filesep, {fnames.name});
else % unzip if compressed file is the source
[~, fname, ext1] = fileparts(src);
dcmFolder = sprintf('%stmpDcm%s/', niiFolder, fname);
if ~isfolder(dcmFolder)
mkdir(dcmFolder);
delTmpDir = onCleanup(@() rmdir(dcmFolder, 's'));
end
fprintf('Extracting files from %s%s ...\n', fname, ext1);
if strcmp(unzip_cmd, 'unzip')
cmd = sprintf('unzip -qq -o %s -d %s', src, dcmFolder);
err = system(cmd); % first try system unzip
if err, unzip(src, dcmFolder); end % Matlab's unzip is too slow
elseif strcmp(unzip_cmd, 'untar')
if isempty(which('untar'))
error('No untar found in matlab path.');
end
untar(src, dcmFolder);
end
fnames = filesInDir(dcmFolder);
end
else
error('Unknown dicom source.');
end
nFile = numel(fnames);
if nFile<1, error(' No files found in the data source.'); end
%% user preference
pf.save_patientName = getpref('dicm2nii_gui_para', 'save_patientName', true);
pf.save_json = getpref('dicm2nii_gui_para', 'save_json', false);
pf.use_parfor = getpref('dicm2nii_gui_para', 'use_parfor', true);
pf.use_seriesUID = getpref('dicm2nii_gui_para', 'use_seriesUID', true);
pf.lefthand = getpref('dicm2nii_gui_para', 'lefthand', true);
pf.scale_16bit = getpref('dicm2nii_gui_para', 'scale_16bit', false);
pf.reorient = getpref('dicm2nii_gui_para', 'reorient', true);
pf.dicom_ext = getpref('dicm2nii_gui_para', 'dicom_ext', false);
%% Check each file, store partial header in cell array hh
% first 2 fields are must. First 10 indexed in code
flds = {'Columns' 'Rows' 'BitsAllocated' 'SeriesInstanceUID' 'SeriesNumber' ...
'ImageOrientationPatient' 'ImagePositionPatient' 'PixelSpacing' ...
'SliceThickness' 'SpacingBetweenSlices' ... % these 10 indexed in code
'PixelRepresentation' 'BitsStored' 'HighBit' 'SamplesPerPixel' ...
'PlanarConfiguration' 'EchoTime' 'RescaleIntercept' 'RescaleSlope' ...
'InstanceNumber' 'NumberOfFrames' 'B_value' 'DiffusionGradientDirection' ...
'TriggerTime' 'RTIA_timer' 'RBMoCoTrans' 'RBMoCoRot' 'AcquisitionNumber' ...
'CoilString' 'TemporalPositionIdentifier' ...
'PerFrameFunctionalGroupsSequence' ...
'MRImageGradientOrientationNumber' 'MRImageLabelType' 'SliceNumberMR' 'PhaseNumber'};
dict = dicm_dict('SIEMENS', flds); % dicm_hdr will update vendor if needed
% read header for all files, use parpool if available and worthy
if ~no_save, fprintf('Validating %g files ... ', nFile); end
hh = cell(1, nFile); errStr = cell(1, nFile);
doParFor = pf.use_parfor && nFile>2000 && useParTool;
for k = 1:nFile
[hh{k}, errStr{k}, dict] = dicm_hdr(fnames{k}, dict);
if doParFor && ~isempty(hh{k}) % parfor wont allow updating dict
parfor i = k+1:nFile
[hh{i}, errStr{i}] = dicm_hdr(fnames{i}, dict);
end
break;
end
end
hh(cellfun(@(c)isempty(c) || any(~isfield(c, flds(1:2))) || ~isfield(c, 'PixelData') ...
|| (isstruct(c.PixelData) && c.PixelData.Bytes<1), hh)) = [];
if ~no_save, fprintf('(%g valid)\n', numel(hh)); end
%% sort headers into cell h by SeriesInstanceUID/SeriesNumber
h = {}; % in case of no dicom files at all
if pf.use_seriesUID % use UID unless asked not to do so
hasID = cellfun(@(c)isfield(c,'SeriesInstanceUID'), hh);
hh0 = hh(hasID);
sUID = cellfun(@(c)c.SeriesInstanceUID, hh0, 'UniformOutput', false);
[sUID, ~, ic] = unique(sUID);
for k = 1:numel(sUID), h{k} = hh0(ic==k); end
hh = hh(~hasID); % likely none after UID
end
hasSN = cellfun(@(c)isfield(c,'SeriesNumber'), hh);
hh0 = hh(hasSN);
sNs = cellfun(@(c)c.SeriesNumber, hh0);
[sNs, ~, ic] = unique(sNs);
n = numel(h);
for k = 1:numel(sNs), h{k+n} = hh0(ic==k); end % rely on SN
hh = hh(~hasSN);
n = numel(h);
for k = 1:numel(hh), h{k+n} = hh(k); end % treat as separate series if no SN
%% Split each series by CoilString (seen for uncombined Siemens)
hSuf = repmat({''}, 1, numel(h));
for i = 1:numel(h)
hh = h{i};
try
cs = cellfun(@(c)c.CoilString, hh, 'UniformOutput', false);
[cs, ~, ic] = unique(cs);
if numel(cs)<2, continue; end
for k = 1:numel(cs)
h{end+1} = hh(ic==k); hSuf{end+1} = ['_c' cs{k}]; % like dcm2niix
end
h{i} = [];
end
end
a = cellfun(@isempty, h);
h(a) = []; hSuf(a) = [];
%% Split series by ComplexImageComponent
for i = 1:numel(h)
hh = h{i};
try
cs = cellfun(@(c)c.ComplexImageComponent, hh, 'UniformOutput', false);
[cs, ~, ic] = unique(cs);
if numel(cs)<2, continue; end
for k = 1:numel(cs)
h{end+1} = hh(ic==k); hSuf{end+1} = ['_' cs{k}];
end
h{i} = [];
end
end
a = cellfun(@isempty, h);
h(a) = []; hSuf(a) = [];
%% Split series by EchoTime
for i = 1:numel(h)
hh = h{i};
try
[ETs, ~, ic] = unique(cellfun(@(c)c.EchoTime, hh));
if numel(ETs)<2, continue; end
for k = 1:numel(ETs)
h{end+1} = hh(ic==k); hSuf{end+1} = [hSuf{i} '_e' num2str(k)];
end
h{i} = [];
end
end
a = cellfun(@isempty, h);
h(a) = []; hSuf(a) = [];
%% sort each series by InstanceNumber
for i = 1:numel(h)
try
[~, ia] = sort(cellfun(@(c)c.InstanceNumber, h{i}));
h{i} = h{i}(ia);
end
end
%% remove last instance if it is different from 1st one (stopped scan by user)
for i = 1:numel(h)
if ~isfield(h{i}{1}.PixelData, 'Bytes'), continue; end
if h{i}{1}.PixelData.Bytes ~= h{i}{end}.PixelData.Bytes
h{i}(end) = [];
end
end
%% Check headers: remove dim-inconsistent series
nRun = numel(h);
if nRun<1 % no valid series
errorLog(sprintf('No valid files found:\n%s.', strjoin(unique(errStr), '\n')));
return;
end
keep = true(1, nRun); % true for useful runs
subjs = cell(1, nRun); vendor = cell(1, nRun);
sNs = ones(1, nRun); studyIDs = cell(1, nRun);
fldsCk = {'ImageOrientationPatient' 'NumberOfFrames' 'Columns' 'Rows' ...
'PixelSpacing' 'RescaleIntercept' 'RescaleSlope' 'SamplesPerPixel' ...
'SpacingBetweenSlices' 'SliceThickness'}; % last for thickness
for i = 1:nRun
s = h{i}{1};
if ~isfield(s, 'LastFile') % avoid re-read for PAR/HEAD/BV file
s = dicm_hdr(s.Filename); % full header for 1st file
end
if ~isfield(s, 'Manufacturer'), s.Manufacturer = 'Unknown'; end
subjs{i} = PatientName(s);
acqs{i} = AcquisitionDateField(s);
vendor{i} = s.Manufacturer;
if isfield(s, 'SeriesNumber'), sNs(i) = s.SeriesNumber;
else, sNs(i) = fix(toc*1e6);
end
studyIDs{i} = tryGetField(s, 'StudyID', '1');
series = sprintf('Subject %s, %s (Series %g)', subjs{i}, ProtocolName(s), sNs(i));
[s, err] = multiFrameFields(s); % no-op if non multi-frame
if ~isempty(err), keep(i) = 0; continue; end % invalid multiframe series
s.isDTI = isDTI(s);
s.isEnh = isfield(s, 'PerFrameFunctionalGroupsSequence');
if ~isfield(s, 'AcquisitionDateTime') % assumption: 1st instance is earliest
try s.AcquisitionDateTime = [s.AcquisitionDate s.AcquisitionTime]; end
end
h{i}{1} = s; % update record in case of full hdr or multiframe
nFile = numel(h{i});
% check consistency in 'fldsCk' (skip Siemens if isEnh
nFlds = numel(fldsCk);
if isfield(s, 'SpacingBetweenSlices'), nFlds = nFlds - 1; end % check 1 of 2
for k = 1:nFlds*(nFile>1 && ~(s.isEnh && strncmpi(s.Manufacturer, 'Siemens', 7)))
if isfield(s, fldsCk{k}), val = s.(fldsCk{k}); else, continue; end
val = repmat(double(val), [1 nFile]);
for j = 2:nFile
if isfield(h{i}{j}, fldsCk{k}), val(:,j) = h{i}{j}.(fldsCk{k});
else, keep(i) = 0; break;
end
end
if ~keep(i), break; end % skip silently
ind = sum(abs(val - val(:,2)), 1) / sum(abs(val(:,2))) > 0.01;
if ~any(ind), continue; end % good
if any(strcmp(fldsCk{k}, {'RescaleIntercept' 'RescaleSlope'}))
h{i}{1}.ApplyRescale = true;
continue;
end
if numel(ind)>2 && sum(ind)==1 % 2+ files but only 1 inconsistent
h{i}(ind) = []; % remove first or last, but keep the series
nFile = nFile - 1;
if ind(1) % re-do full header for new 1st file
s = dicm_hdr(h{i}{1}.Filename);
s.isDTI = isDTI(s);
s.isEnh = isfield(s, 'PerFrameFunctionalGroupsSequence');
h{i}{1} = s;
end
else
errorLog(['Inconsistent ''' fldsCk{k} ''' for ' series '. Series skipped.']);
keep(i) = 0; break;
end
end
nSL = nMosaic(s); % nSL>1 for mosaic
if ~isempty(nSL) && nSL>1
h{i}{1}.isMos = true;
h{i}{1}.LocationsInAcquisition = nSL;
if s.isDTI, continue; end % allow missing directions for DTI
a = zeros(1, nFile);
for j = 1:nFile, a(j) = tryGetField(h{i}{j}, 'InstanceNumber', 1); end
if numel(unique(diff(4)))>1 % like CMRR ISSS seq or multi echo. Error for UIH
errorLog(['InstanceNumber discontinuity detected for ' series '.' ...
'See VolumeTiming in NIfTI ext or dcmHeaders.mat.']);
dict = dicm_dict('', {'AcquisitionDate' 'AcquisitionTime'});
vTime = nan(1, nFile);
for j = 1:nFile
s2 = dicm_hdr(h{i}{j}.Filename, dict);
dt = [s2.AcquisitionDate s2.AcquisitionTime];
vTime(j) = datenum(dt, 'yyyymmddHHMMSS.fff'); %#ok<*DATNM>
end
vTime = vTime - min(vTime);
h{i}{1}.VolumeTiming = vTime * 86400; % day to seconds
end
continue; % no other check for mosaic
end
if ~keep(i) || nFile<2 || ~isfield(s, 'ImagePositionPatient'), continue; end
if s.isEnh, continue; end % Siemens enhanced dicom
[err, h{i}] = checkImagePosition(h{i}); % may re-oder h{i} for Philips
if ~isempty(err)
errorLog([err ' for ' series '. Series skipped.']);
keep(i) = 0; continue; % skip
end
end
h = h(keep); sNs = sNs(keep); studyIDs = studyIDs(keep); hSuf = hSuf(keep);
subjs = subjs(keep); vendor = vendor(keep); acqs = acqs(keep);
subj = unique(subjs);
% sort h by PatientName, then StudyID, then SeriesNumber
% Also get correct order for subjs/studyIDs/nStudy/sNs for nii file names
[~, ind] = sortrows([subjs' studyIDs' num2cell(sNs')]);
h = h(ind); subjs = subjs(ind); studyIDs = studyIDs(ind); sNs = sNs(ind); hSuf = hSuf(ind); acqs = acqs(ind);
multiStudy = cellfun(@(c)numel(unique(studyIDs(strcmp(subjs,c))))>1, subjs);
%% Generate unique result file names
% Unique names are in format of SeriesDescription[_hSuf]_s007. Special cases are:
% for phase image, such as field_map phase, append '_phase' to the name;
% for MoCo series, append '_MoCo' to the name if both series are present.
% for multiple subjs, it is SeriesDescription_subj_s007
% for multiple Study, it is SeriesDescription_subj_Study1_s007
nRun = numel(h); % update it, since we have removed some
if nRun<1
errorLog('No valid series found');
return;
end
rNames = cell(1, nRun);
multiSubj = numel(subj)>1;
j_s = nan(nRun, 1); % index-1 for _s003. needed if 4+ length SeriesNumbers
for i = 1:nRun
s = h{i}{1};
sN = sNs(i);
a = [ProtocolName(s) hSuf{i}];
if isPhase(s), a = [a '_phase']; end % phase image
if i>1 && sN-sNs(i-1)==1 && isType(s, '\MOCO\') && strncmp(a, rNames{i-1}, numel(a))
a = [a '_MoCo'];
end
if asc_header(s, 'sPreScanNormalizeFilter.ucSaveUnfiltered', 0) && isType(s, '\NORM')
a = [a '_NORM'];
end
if multiSubj, a = [a '_' subjs{i}]; end
if multiStudy(i), a = [a '_Study' studyIDs{i}]; end
if ~isstrprop(a(1), 'alpha'), a = ['x' a]; end % genvarname behavior
% a = regexprep(a, '(?<=\S)\s+([a-z])', '${upper($1)}'); % camel case
a = regexprep(regexprep(a, '[^a-zA-Z0-9_]', '_'), '_{2,}', '_');
if sN>100 && strncmp(s.Manufacturer, 'Philips', 7)
sN = tryGetField(s, 'AcquisitionNumber', floor(sN/100));
end
j_s(i) = numel(a);
rNames{i} = sprintf('%s_s%03i', a, sN);
d = numel(rNames{i}) - 255; % file max len = 255
if d>0, rNames{i}(j_s(i)+(-d+1:0)) = ''; j_s(i) = j_s(i)-d; end % keep _s007
end
vendor = strtok(unique(vendor));
if nargout>0, varargout{1} = subj; end % return converted subject IDs
% After following sort, we need to compare only neighboring names. Remove
% _s007 if there is no conflict. Have to ignore letter case for Windows & MAC
fnames = rNames; % copy it, reserve letter cases
[rNames, iRuns] = sort(lower(fnames));
j_s = j_s(iRuns);
for i = 1:nRun
if i>1 && strcmp(rNames{i}, rNames{i-1}) % truncated StudyID to PatientName
a = num2str(i);
rNames{i}(j_s(i)+(-numel(a)+1:0)) = a; % not 100% unique
end
a = rNames{i}(1:j_s(i)); % remove _s003
% no conflict with both previous and next name
if nRun==1 || ... % only one run
(i==1 && ~strcmpi(a, rNames{2}(1:j_s(2)))) || ... % first
(i==nRun && ~strcmpi(a, rNames{i-1}(1:j_s(i-1)))) || ... % last
(i>1 && i<nRun && ~strcmpi(a, rNames{i-1}(1:j_s(i-1))) ...
&& ~strcmpi(a, rNames{i+1}(1:j_s(i+1)))) % middle ones
fnames{iRuns(i)}(j_s(i)+1:end) = [];
end
end
if numel(unique(fnames)) < nRun % may happen to user-modified dicom/par
fnames = matlab.lang.makeUniqueStrings(fnames);
end
fmtStr = sprintf(' %%-%gs %%dx%%dx%%dx%%d\n', max(cellfun(@numel, fnames))+12);
%% Now ready to convert nii series by series
subjStr = sprintf('''%s'', ', subj{:}); subjStr(end+(-1:0)) = [];
vendor = sprintf('%s, ', vendor{:}); vendor(end+(-1:0)) = [];
if ~no_save
fprintf('Converting %g series (%s) into %g-D %s: subject %s\n', ...
nRun, vendor, 4-rst3D, ext, subjStr);
end
%% Parse BIDS
if bids
pf.save_json = true; % force to save json for BIDS
% Manage Multiple SUBJECT or SESSION
if multiSubj
fprintf(['Multiple subjects detected!!!!! Skipping...\n' ...
'Please convert subjects one by one with BIDS options\n'])
fprintf('%s\n',subj{:})
for isub = 1:length(subj)
fprintf('Converting subject one by one... %s\n',subj{isub})
isublist = strcmp(subjs,subj{isub});
FileNames = cellfun(@(y) cellfun(@(x) x.Filename,y,'uni',0),h(isublist),'uni',0);
dicm2nii([FileNames{:}],niiFolder,'bids')
end
return;
end
acq = unique(acqs);
if numel(acq)>1
fprintf('Multiple acquitisition detected!!!!! \n')
for iacq = 1:length(acq)
fprintf('Converting sessions one by one... %s\n',acq{iacq})
iacqlist = strcmp(acqs,acq{iacq});
FileNames = cellfun(@(y) cellfun(@(x) x.Filename,y,'uni',0),h(iacqlist),'uni',0);
dicm2nii([FileNames{:}],niiFolder,'bids')
end
return;
end
% Table: subject Name
Subject = regexprep(subj, '[^0-9a-zA-Z]', '');
Session = {''};
AcquisitionDate = {[acq{1}(1:4) '-' acq{1}(5:6) '-' acq{1}(7:8)]};
Comment = {'N/A'};
S = table(Subject,Session,AcquisitionDate,Comment);
types = {'skip' 'anat' 'dwi' 'fmap' 'func' 'perf'};
modalities = {'skip' 'FLAIR' 'FLASH' 'PD' 'PDmap' 'T1map' 'T1rho' 'T1w' 'T2map' ...
'T2star' 'T2w' 'asl' 'dwi' 'fieldmap' 'm0scan' 'magnitude1' 'magnitude2' ...
'phase1' 'phase2' 'phasediff' 'task-motor_bold' 'task-rest_bold'};
Modality = categorical(repmat({'skip'}, [length(fnames) 1]), modalities);
Type = categorical(repmat({'skip'},[length(fnames),1]), types);
Name = regexprep(fnames', '_s\d+$', '');
T = table(Name,Type,Modality);
ModalityTablePref = getpref('dicm2nii_gui_para', 'ModalityTable', T);
[Lia, Locb] = ismember(T.Name, ModalityTablePref.Name);
for i = 1:nRun
if Lia(i)
T.Type(i) = ModalityTablePref.Type(Locb(i));
T.Modality(i) = ModalityTablePref.Modality(Locb(i));
continue;
end
seq = tryGetField(h{i}{1}, 'SequenceName', '');
seqContains = @(p)any(cellfun(@(c)~isempty(strfind(seq,c)), p));
if h{i}{1}.isDTI % do this first
T.Type(i) = {'dwi'}; T.Modality(i) = {'dwi'};
elseif seqContains({'epfid2d' 'EPI' 'epi'})
T.Type(i) = {'func'};
if containsI(T.Name{i}, 'rest')
T.Modality(i) = {'task-rest'};
else
try nam = h{i}{1}.ProtocolName;
catch, nam = ProtocolName(h{i}{1});
end
c = regexpi(nam, '(.*)?run[-_]*(\d*)', 'tokens', 'once');
if isempty(c)
c = regexprep(nam, '[^0-9a-zA-Z]', '');
else
c = regexprep(c, '[^0-9a-zA-Z]', '');
c = sprintf('%s_run-%s', c{:});
end
T.Modality(i) = {['task-' c]};
end
ec = regexp(T.Name{i}, '_e\d+', 'match', 'once');
if ~isempty(ec)
T.Modality(i) = {[char(T.Modality(i)) '_echo-' ec(3:end)]};
end
if ~isempty(regexp(T.Name{i}, '_SBRef$', 'once'))
T.Modality(i) = {[char(T.Modality(i)) '_sbref']};
else
T.Modality(i) = {[char(T.Modality(i)) '_bold']};
end
elseif seqContains({'fm2d' 'FFE'})
T.Type(i) = {'fmap'};
if strcmp(T.Name{i}(end+(-2:0)), '_e1')
T.Modality(i) = {'magnitude1'};
elseif strcmp(T.Name{i}(end+(-2:0)), '_e2')
T.Modality(i) = {'magnitude2'};
elseif isType(h{i}{1}, '\P\')
T.Modality(i) = {'phasediff'};
else
T.Modality(i) = {'fieldmap'};
end
elseif seqContains({'epse'}) % after isDTI, is it safe?
T.Type(i) = {'fmap'}; T.Modality(i) = {'fieldmap'};
elseif seqContains({'tir2d'})
T.Type(i) = {'anat'}; T.Modality(i) = {'FLAIR'};
elseif seqContains({'tfl3d' 'T1' 'EFGRE3D' 'gre_fsp'})
T.Type(i) = {'anat'}; T.Modality(i) = {'T1w'};
elseif seqContains({'spc' 'T2'})
T.Type(i) = {'anat'}; T.Modality(i) = {'T2w'};
end
end
% GUI
toSkip = any(ismember(cellfun(@char,table2cell(T(:,2:3)),'uni',0), 'skip'), 2);
uniqueNames = unique(T.Modality(~toSkip));
guiOn = getpref('dicm2nii_gui_para', 'bidsForceGUI', []);
if ~isempty(guiOn), setpref('dicm2nii_gui_para', 'bidsForceGUI', []); end
if isempty(guiOn)
guiOn = ~all(Lia) || all(toSkip) || numel(uniqueNames)<sum(~toSkip);
end
if guiOn
setappdata(0,'Canceldicm2nii',false);
scrSz = get(0, 'ScreenSize');
figargs = {'Position',[min(scrSz(4)+420,620) scrSz(4)-600 800 400],...
'Color', [1 1 1]*206/256, 'CloseRequestFcn', @my_closereq};
if verLessThanOctave
hf = figure(figargs{:});
% add help
set(hf,'ToolBar','none','MenuBar','none')
else
hf = uifigure(figargs{:});
end
uimenu(hf,'Label','help','Callback',@(src,evnt)showHelp(types,modalities))
set(hf,'Name', 'dicm2nii - BIDS Converter', 'NumberTitle', 'off')
% tables
if verLessThanOctave
SCN = S.Properties.VariableNames;
S = table2cell(S);
TCN = T.Properties.VariableNames;
T = cellfun(@char,table2cell(T),'uni',0);
end
TS = uitable(hf,'Data',S);
TT = uitable(hf,'Data',T);
TSpos = [20 hf.Position(4)-110 hf.Position(3)-160 90];
TTpos = [20 20 hf.Position(3)-160 hf.Position(4)-120];
if verLessThanOctave
setpixelposition(TS,TSpos);
set(TS,'Units','Normalized')
setpixelposition(TT,TTpos);
set(TT,'Units','Normalized')
else
TS.Position = TSpos;
TT.Position = TTpos;
end
TS.ColumnEditable = [true true true true];
if verLessThanOctave
TS.ColumnName = SCN;
TT.ColumnName = TCN;
end
TT.ColumnEditable = [false true true];
% button
Bpos = [hf.Position(3)-120 20 100 30];
BCB = @(btn,event) BtnModalityTable(hf,TT, TS);
if verLessThanOctave
B = uicontrol(hf,'Style','pushbutton','String','OK');
set(B,'Callback',BCB);
setpixelposition(B,Bpos)
set(B,'Units','Normalized')
else
B = uibutton(hf,'Position',Bpos);
B.Text = 'OK';
B.ButtonPushedFcn = BCB;
end
% preview panel
axesArgs = {hf,'Position',[hf.Position(3)-120 70 100 hf.Position(4)-90], 'Colormap',gray(64)};
ax = previewDicom([],h{1},axesArgs);
ax.YTickLabel = [];
ax.XTickLabel = [];
TT.CellSelectionCallback = @(src,event) previewDicom(ax,h{event.Indices(1)},axesArgs);
waitfor(hf);
if getappdata(0,'Canceldicm2nii'), return; end
ModalityTable = getappdata(0,'ModalityTable');
SubjectTable = getappdata(0,'SubjectTable');
rmappdata(0,'ModalityTable'); rmappdata(0,'SubjectTable');
% setpref
ModalityTablePref = [ModalityTable; ModalityTablePref];
[~, a] = unique(ModalityTablePref.Name, 'stable');
setpref('dicm2nii_gui_para', 'ModalityTable', ModalityTablePref(a,:));
else
ModalityTable = cellfun(@char, table2cell(T),'uni',0);
SubjectTable = S{1,:};
end
% participants.tsv
try
tsvfile = fullfile(niiFolder, 'participants.tsv');
participant_id = SubjectTable{1,1};
Sex = tryGetField(h{i}{1}, 'PatientSex');
Age = tryGetField(h{i}{1}, 'PatientAge');
if ischar(Age), Age = sscanf(Age, '%f'); end
Size = tryGetField(h{i}{1}, 'PatientSize');
Weight = tryGetField(h{i}{1}, 'PatientWeight');
write_tsv(participant_id,tsvfile,'Age',Age,'Sex',Sex,'Weight',Weight,'Size',Size)
catch
warning('Could not save participants.tsv');
end
if isempty(SubjectTable{2}) % no session
ses = '';
session_id='';
else
session_id=SubjectTable{2};
ses = ['ses-' session_id '_'];
end
% _session.tsv
if ~isempty(ses)
try
tsvfile = fullfile(niiFolder, ['sub-' SubjectTable{1}],['sub-' SubjectTable{1} '_sessions.tsv']);
write_tsv(session_id,tsvfile,'acq_time',SubjectTable{3},'Comment',SubjectTable{4})
catch ME
fprintf(1, '\n')
warning(['Could not save sub-' SubjectTable{1} '_sessions.tsv']);
errorMessage = sprintf('Error in function %s() at line %d.\nError Message: %s\n\n', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
end
end
end
%% Convert
for i = 1:nRun
if bids
if any(ismember(ModalityTable(i,2:3),'skip')), continue; end
modalityfolder = fullfile(['sub-' SubjectTable{1}],...
ses(1:end-1), ModalityTable{i,2});
if ~exist(fullfile(niiFolder, modalityfolder),'dir')
mkdir(fullfile(niiFolder, modalityfolder));
end
fnames{i} = fullfile(modalityfolder,...
['sub-' SubjectTable{1} '_' ses ModalityTable{i,3}]);
end
nFile = numel(h{i});
h{i}{1}.NiftiName = fnames{i};
s = h{i}{1};
if nFile>1 && ~isfield(s, 'LastFile')
h{i}{1}.LastFile = h{i}{nFile}; % store partial last header into 1st
end
for j = 1:nFile
if j==1
img = dicm_img(s, 0); % initialize img with dicm data type
if ndims(img)>4 % err out, likely won't work for other series
error('Image with 5 or more dim not supported: %s', s.Filename);
end
applyRescale = tryGetField(s, 'ApplyRescale', false);
if applyRescale, img = single(img); end
else
if j==2, img(:,:,:,:,nFile) = 0; end % pre-allocate for speed
img(:,:,:,:,j) = dicm_img(h{i}{j}, 0);
end
if applyRescale
slope = tryGetField(h{i}{j}, 'RescaleSlope', 1);
inter = tryGetField(h{i}{j}, 'RescaleIntercept', 0);
img(:,:,:,:,j) = img(:,:,:,:,j) * slope + inter;
end
end
if strcmpi(tryGetField(s, 'DataRepresentation', ''), 'COMPLEX')
img = complex(img(1:2:end), img(2:2:end));
end
[~, ~, d3, d4, ~] = size(img);
if strcmpi(tryGetField(s, 'SignalDomainColumns', ''), 'TIME') % no permute
elseif d3<2 && d4<2, img = permute(img, [1 2 5 3 4]); % remove dim3,4
elseif d4<2, img = permute(img, [1:3 5 4]); % remove dim4: Frames
elseif d3<2, img = permute(img, [1 2 4 5 3]); % remove dim3: RGB
end
nSL = double(tryGetField(s, 'LocationsInAcquisition'));
if tryGetField(s, 'SamplesPerPixel', 1) > 1 % color image
img = permute(img, [1 2 4:8 3]); % put RGB into dim8 for nii_tool
elseif tryGetField(s, 'isMos', false) % mosaic
img = mos2vol(img, nSL, strncmpi(s.Manufacturer, 'UIH', 3));
elseif ndims(img)==3 && ~isempty(nSL) % may need to reshape to 4D
if isfield(s, 'SortFrames'), img = img(:,:,s.SortFrames); end
dim = size(img);
dim(3:4) = [nSL dim(3)/nSL]; % verified integer earlier
img = reshape(img, dim);
end
if any(~isfield(s, flds(6:8))) || ~any(isfield(s, flds(9:10)))
h{i}{1} = csa2pos(h{i}{1}, size(img,3));
end
if isa(img, 'uint16') && max(img(:))<32768, img = int16(img); end % lossless
h{i}{1}.ConversionSoftware = converter;
nii = nii_tool('init', img); % create nii struct based on img
[nii, h{i}] = set_nii_hdr(nii, h{i}, pf, bids); % set most nii hdr
% Save bval and bvec files after bvec perm/sign adjusted in set_nii_hdr
fname = fullfile(niiFolder, fnames{i}); % name without ext
if s.isDTI && ~no_save, save_dti_para(h{i}{1}, fname); end
nii = split_components(nii, h{i}); % split vol components
if no_save % only return the first nii
nii(1).hdr.file_name = strcat(fnames{i}, '.nii');
nii(1).hdr.magic = 'n+1';
varargout{1} = nii_tool('update', nii(1));
return;
end
for j = 1:numel(nii)
nam = fnames{i};
if numel(nii)>1, nam = nii(j).hdr.file_name; end
fprintf(fmtStr, nam, nii(j).hdr.dim(2:5));
if pf.dicom_ext; sDcm = s; else, sDcm = ''; end
nii(j).ext = set_nii_ext(nii(j).json, sDcm); % NIfTI extension
if pf.save_json, save_json(nii(j).json, fname); end
nii_tool('save', nii(j), fullfile(niiFolder, strcat(nam, ext)), rst3D);
end
if isfield(nii(1).hdr, 'hdrTilt')
nii = nii_xform(nii(1), nii.hdr.hdrTilt);
fprintf(fmtStr, strcat(fnames{i}, '_Tilt'), nii.hdr.dim(2:5));
nii_tool('save', nii, strcat(fname, '_Tilt', ext), rst3D); % save xformed nii
end
h{i} = h{i}{1}; % keep 1st dicm header only
if isnumeric(h{i}.PixelData), h{i} = rmfield(h{i}, 'PixelData'); end % BV
end
[~, fnames] = cellfun(@fileparts, fnames, 'UniformOutput', false);
fnames = matlab.lang.makeValidName(fnames);
fnames = matlab.lang.makeUniqueStrings(fnames, {}, namelengthmax);
h = cell2struct(h, fnames, 2); % convert into struct
if bids, fname = fullfile(niiFolder, ['sub-' SubjectTable{1,1}], 'dcmHeaders.mat');
else, fname = fullfile(niiFolder, 'dcmHeaders.mat');
end
if exist(fname, 'file') % if file exists, we update fields only
S = load(fname);
for i = 1:numel(fnames), S.h.(fnames{i}) = h.(fnames{i}); end
h = S.h;
end
save(fname, 'h', '-v7'); % -v7 better compatibility
fprintf('Elapsed time by dicm2nii is %.1f seconds\n\n', toc);
return;
%% Subfunction: return PatientName
function subj = PatientName(s)
subj = tryGetField(s, 'PatientName');
if isempty(subj), subj = tryGetField(s, 'PatientID', 'Anonymous'); end
%% Subfunction: return AcquisitionDate
function acq = AcquisitionDateField(s)
acq = tryGetField(s, 'AcquisitionDate');
if isempty(acq)
acq = tryGetField(s, 'AcquisitionDateTime');
if numel(acq)>8, acq = acq(1:8); end
end
if isempty(acq), acq = tryGetField(s, 'SeriesDate'); end
if isempty(acq), acq = tryGetField(s, 'StudyDate', ''); end
%% Subfunction: return SeriesDescription
function name = ProtocolName(s)
name = tryGetField(s, 'SeriesDescription');
if isempty(name) || (strncmp(s.Manufacturer, 'SIEMENS', 7) && any(regexp(name, 'MoCoSeries$')))
name = tryGetField(s, 'ProtocolName');
end
if isempty(name), [~, name] = fileparts(s.Filename); end
name = strtrim(name);
%% Subfunction: return true if keyword is in s.ImageType
function tf = isType(s, keyword)
typ = tryGetField(s, 'ImageType', '');
tf = ~isempty(strfind(typ, keyword)); %#ok<*STREMP>
%% Subfunction: return true if series is DTI
function tf = isDTI(s)
tf = isType(s, '\DIFFUSION'); % Siemens, Philips
if tf, return; end
if isfield(s, 'ProtocolDataBlock') % GE, not labeled as \DIFFISION
IOPT = tryGetField(s.ProtocolDataBlock, 'IOPT');
if isempty(IOPT), tf = tryGetField(s, 'DiffusionDirection', 0)>0;
else, tf = ~isempty(regexp(IOPT, 'DIFF', 'once'));
end
elseif strncmpi(s.Manufacturer, 'Philips', 7)
tf = strcmp(tryGetField(s, 'MRSeriesDiffusion', 'N'), 'Y');
elseif isfield(s, 'ApplicationCategory') % UIH
tf = ~isempty(regexp(s.ApplicationCategory, 'DTI', 'once'));
elseif isfield(s, 'AcquisitionContrast') % Bruker
tf = ~isempty(regexpi(s.AcquisitionContrast, 'DIFF', 'once'));
else % Some Siemens DTI are not labeled as \DIFFUSION
tf = ~isempty(csa_header(s, 'B_value'));
end
%% Subfunction: return true if series is phase img
function tf = isPhase(s)
tf = isType(s, '\P\') || ...
strcmpi(tryGetField(s, 'ComplexImageComponent', ''), 'PHASE'); % Philips
%% Subfunction: get field if exist, return default value otherwise
function val = tryGetField(s, field, dftVal)
if isfield(s, field), val = s.(field);
elseif nargin>2, val = dftVal;
else, val = [];
end
%% Subfunction: Set most nii header and re-orient img
function [nii, h] = set_nii_hdr(nii, h, pf, bids)
dim = nii.hdr.dim(2:4); nVol = nii.hdr.dim(5);
% fld = 'NumberOfTemporalPositions';
% if ~isfield(h{1}, fld) && nVol>1, h{1}.(fld) = nVol; end
% Transformation matrix: most important feature for nii
[ixyz, R, pixdim, xyz_unit] = xform_mat(h{1}, dim); % R: dicom xform matrix
R(1:2,:) = -R(1:2,:); % dicom LPS to nifti RAS, xform matrix before reorient
% Compute bval & bvec in image reference for DTI series before reorienting
if h{1}.isDTI, [h, nii] = get_dti_para(h, nii); end
% Store CardiacTriggerDelayTime
fld = 'CardiacTriggerDelayTime';