forked from NeuroJSON/dcm2niix
/
nii_dicom_batch.cpp
2275 lines (2170 loc) · 94.1 KB
/
nii_dicom_batch.cpp
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
//#define myNoSave //do not save images to disk
#ifdef _MSC_VER
#include <direct.h>
#define getcwd _getcwd
#define chdir _chrdir
#include "io.h"
//#include <math.h>
#define MiniZ
#else
#include <unistd.h>
#ifdef myDisableMiniZ
#undef MiniZ
#else
#define MiniZ
#endif
#endif
#if defined(__APPLE__) && defined(__MACH__)
//#include "nii_foreign.h"
#endif
#ifndef myDisableZLib
#ifdef MiniZ
#include "miniz.c" //single file clone of libz
#else
#include <zlib.h>
#endif
#endif
#ifdef myUseCOut
#include <iostream>
#endif
#include "nifti1_io_core.h"
#include "nifti1.h"
#include "nii_dicom_batch.h"
#include "nii_dicom.h"
#include "tinydir.h"
#include <ctype.h> //toupper
#include <float.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifdef myEnableOtsu
#include "nii_ostu_ml.h" //provide better brain crop, but artificially reduces signal variability in air
#endif
#include <time.h> // clock_t, clock, CLOCKS_PER_SEC
#include "nii_ortho.h"
#if defined(_WIN64) || defined(_WIN32)
#include <windows.h> //write to registry
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//gcc -O3 -o main main.c nii_dicom.c
#if defined(_WIN64) || defined(_WIN32)
const char kPathSeparator ='\\';
const char kFileSep[2] = "\\";
#else
const char kPathSeparator ='/';
const char kFileSep[2] = "/";
#endif
struct TDCMsort {
uint64_t indx, img;
};
struct TSearchList {
unsigned long numItems, maxItems;
char **str;
};
void dropFilenameFromPath(char *path) { //
const char *dirPath = strrchr(path, '/'); //UNIX
if (dirPath == 0)
dirPath = strrchr(path, '\\'); //Windows
if (dirPath == NULL) {
strcpy(path,"");
} else
path[dirPath - path] = 0; // please make sure there is enough space in TargetDirectory
if (strlen(path) == 0) { //file name did not specify path, assume relative path and return current working directory
//strcat (path,"."); //relative path - use cwd <- not sure if this works on Windows!
char cwd[1024];
getcwd(cwd, sizeof(cwd));
strcat (path,cwd);
}
}
void getFileName( char *pathParent, const char *path) //if path is c:\d1\d2 then filename is 'd2'
{
const char *filename = strrchr(path, '/'); //UNIX
if (filename == 0) {
filename = strrchr(path, '\\'); //Windows
if (filename == NULL) filename = strrchr(path, ':'); //Windows
}
//const char *filename = strrchr(path, kPathSeparator); //x
if (filename == NULL) {//no path separator
strcpy(pathParent,path);
return;
}
filename++;
strcpy(pathParent,filename);
}
bool is_fileexists(const char * filename) {
FILE * fp = NULL;
if ((fp = fopen(filename, "r"))) {
fclose(fp);
return true;
}
return false;
}
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
#endif
bool is_fileNotDir(const char* path) { //returns false if path is a folder; requires #include <sys/stat.h>
struct stat buf;
stat(path, &buf);
return S_ISREG(buf.st_mode);
} //is_file()
bool is_exe(const char* path) { //requires #include <sys/stat.h>
struct stat buf;
if (stat(path, &buf) != 0) return false; //file does not eist
if (!S_ISREG(buf.st_mode)) return false; //not regular file, e.g. '..'
return (buf.st_mode & 0111) ;
//return (S_ISREG(buf.st_mode) && (buf.st_mode & 0111) );
} //is_exe()
int is_dir(const char *pathname, int follow_link) {
struct stat s;
if ((NULL == pathname) || (0 == strlen(pathname)))
return 0;
int err = stat(pathname, &s);
if(-1 == err)
return 0; /* does not exist */
else {
if(S_ISDIR(s.st_mode)) {
return 1; /* it's a dir */
} else {
return 0;/* exists but is no dir */
}
}
} //is_dir
/*int is_dir(const char *pathname, int follow_link) {
//http://sources.gentoo.org/cgi-bin/viewvc.cgi/path-sandbox/trunk/libsbutil/get_tmp_dir.c?revision=260
struct stat buf;
int retval;
if ((NULL == pathname) || (0 == strlen(pathname)))
return 0;
retval = follow_link ? stat(pathname, &buf) : lstat(pathname, &buf);
if ((-1 != retval) && (S_ISDIR(buf.st_mode)))
return 1;
if ((-1 == retval) && (ENOENT != errno)) // Some or other error occurred
return -1;
return 0;
} //is_dir()
*/
void geCorrectBvecs(struct TDICOMdata *d, int sliceDir, struct TDTI *vx){
//0018,1312 phase encoding is either in row or column direction
//0043,1039 (or 0043,a039). b value (as the first number in the string).
//0019,10bb (or 0019,a0bb). phase diffusion direction
//0019,10bc (or 0019,a0bc). frequency diffusion direction
//0019,10bd (or 0019,a0bd). slice diffusion direction
//These directions are relative to freq,phase,slice, so although no
//transformations are required, you need to check the direction of the
//phase encoding. This is in DICOM message 0018,1312. If this has value
//COL then if swap the x and y value and reverse the sign on the z value.
//If the phase encoding is not COL, then just reverse the sign on the x value.
if (d->manufacturer != kMANUFACTURER_GE) return;
if (d->CSA.numDti < 1) return;
if ((toupper(d->patientOrient[0])== 'H') && (toupper(d->patientOrient[1])== 'F') && (toupper(d->patientOrient[2])== 'S'))
; //participant was head first supine
else {
#ifdef myUseCOut
std::cout<<"GE DTI directions require head first supine acquisition" <<std::endl;
#else
printf("GE DTI directions require head first supine acquisition\n");
#endif
return;
}
bool col = false;
if (d->phaseEncodingRC== 'C')
col = true;
else if (d->phaseEncodingRC!= 'R') {
#ifdef myUseCOut
std::cout<<"Error: Unable to determine DTI gradients, 0018,1312 should be either R or C" <<std::endl;
#else
printf("Error: Unable to determine DTI gradients, 0018,1312 should be either R or C");
#endif
return;
}
if (abs(sliceDir) != 3)
#ifdef myUseCOut
std::cout<<"GE DTI gradients only tested for axial acquisitions" <<std::endl;
#else
printf("GE DTI gradients only tested for axial acquisitions");
#endif
//printf("GE row(0) or column(1) = %d",col);
#ifdef myUseCOut
std::cout<<"Reorienting "<< d->CSA.numDti << "GE DTI gradients. Please validate if you are conducting DTI analyses. isCol="<<col <<std::endl;
#else
printf("Reorienting %d GE DTI gradients. Please validate if you are conducting DTI analyses. isCol=%d\n", d->CSA.numDti, col);
#endif
for (int i = 0; i < d->CSA.numDti; i++) {
float vLen = sqrt( (vx[i].V[1]*vx[i].V[1])
+ (vx[i].V[2]*vx[i].V[2])
+ (vx[i].V[3]*vx[i].V[3]));
if ((vx[i].V[0] <= FLT_EPSILON)|| (vLen <= FLT_EPSILON) ) { //bvalue=0
for (int v= 0; v < 4; v++)
vx[i].V[v] =0.0f;
continue; //do not normalize or reorient b0 vectors
}
vx[i].V[1] = -vx[i].V[1];
if (!col) { //rows need to be swizzled
float swap = vx[i].V[1];
vx[i].V[1] = -vx[i].V[2];
vx[i].V[2] = swap;
}
if (sliceDir < 0)
vx[i].V[3] = -vx[i].V[3];
if (isSameFloat(vx[i].V[1],-0)) vx[i].V[1] = 0.0f;
if (isSameFloat(vx[i].V[2],-0)) vx[i].V[2] = 0.0f;
if (isSameFloat(vx[i].V[3],-0)) vx[i].V[3] = 0.0f;
}
} //geCorrectBvecs()
void siemensPhilipsCorrectBvecs(struct TDICOMdata *d, int sliceDir, struct TDTI *vx){
//see Matthew Robson's http://users.fmrib.ox.ac.uk/~robson/internal/Dicom2Nifti111.m
//convert DTI vectors from scanner coordinates to image frame of reference
//Uses 6 orient values from ImageOrientationPatient (0020,0037)
// requires PatientPosition 0018,5100 is HFS (head first supine)
if ((d->manufacturer != kMANUFACTURER_SIEMENS) && (d->manufacturer != kMANUFACTURER_PHILIPS)) return;
if (d->CSA.numDti < 1) return;
if ((toupper(d->patientOrient[0])== 'H') && (toupper(d->patientOrient[1])== 'F') && (toupper(d->patientOrient[2])== 'S'))
; //participant was head first supine
else {
#ifdef myUseCOut
std::cout<<"Siemens/Philips DTI directions require head first supine acquisition"<<std::endl;
#else
printf("Siemens/Philips DTI directions require head first supine acquisition\n");
#endif
return;
}
vec3 read_vector = setVec3(d->orient[1],d->orient[2],d->orient[3]);
vec3 phase_vector = setVec3(d->orient[4],d->orient[5],d->orient[6]);
vec3 slice_vector = crossProduct(read_vector ,phase_vector);
read_vector = nifti_vect33_norm(read_vector);
phase_vector = nifti_vect33_norm(phase_vector);
slice_vector = nifti_vect33_norm(slice_vector);
for (int i = 0; i < d->CSA.numDti; i++) {
float vLen = sqrt( (vx[i].V[1]*vx[i].V[1])
+ (vx[i].V[2]*vx[i].V[2])
+ (vx[i].V[3]*vx[i].V[3]));
if ((vx[i].V[0] <= FLT_EPSILON)|| (vLen <= FLT_EPSILON) ) { //bvalue=0
if (vx[i].V[0] > FLT_EPSILON)
printf("Warning: volume %d appears to be an ADC map (non-zero b-value with zero vector length)\n", i);
//for (int v= 0; v < 4; v++)
// vx[i].V[v] =0.0f;
continue; //do not normalize or reorient b0 vectors
}//if bvalue=0
vec3 bvecs_old =setVec3(vx[i].V[1],vx[i].V[2],vx[i].V[3]);
vec3 bvecs_new =setVec3(dotProduct(bvecs_old,read_vector),dotProduct(bvecs_old,phase_vector),dotProduct(bvecs_old,slice_vector) );
bvecs_new = nifti_vect33_norm(bvecs_new);
vx[i].V[1] = bvecs_new.v[0];
vx[i].V[2] = -bvecs_new.v[1];
vx[i].V[3] = bvecs_new.v[2];
if (sliceDir == kSliceOrientMosaicNegativeDeterminant) vx[i].V[2] = -vx[i].V[2];
for (int v= 0; v < 4; v++)
if (vx[i].V[v] == -0.0f) vx[i].V[v] = 0.0f; //remove sign from values that are virtually zero
} //for each direction
#ifdef myUseCOut
if (sliceDir == kSliceOrientMosaicNegativeDeterminant)
std::cout<<"WARNING: please validate DTI vectors (matrix had a negative determinant, perhaps Siemens sagittal)."<<std::endl;
else if ( d->sliceOrient == kSliceOrientTra)
std::cout<<"Saving "<<d->CSA.numDti<<" DTI gradients. Please validate if you are conducting DTI analyses."<<std::endl;
else
std::cout<<"WARNING: DTI gradient directions only tested for axial (transverse) acquisitions. Please validate bvec files."<<std::endl;
#else
if (sliceDir == kSliceOrientMosaicNegativeDeterminant)
printf("WARNING: please validate DTI vectors (matrix had a negative determinant, perhaps Siemens sagittal).\n");
else if ( d->sliceOrient == kSliceOrientTra)
printf("Saving %d DTI gradients. Please validate if you are conducting DTI analyses.\n", d->CSA.numDti);
else
printf("WARNING: DTI gradient directions only tested for axial (transverse) acquisitions. Please validate bvec files.\n");
#endif
} //siemensPhilipsCorrectBvecs()
bool isNanPosition (struct TDICOMdata d) { //in 2007 some Siemens RGB DICOMs did not include the PatientPosition 0020,0032 tag
if (isnan(d.patientPosition[1])) return true;
if (isnan(d.patientPosition[2])) return true;
if (isnan(d.patientPosition[3])) return true;
return false;
}
bool isSamePosition (struct TDICOMdata d, struct TDICOMdata d2){
if ( isNanPosition(d) || isNanPosition(d2)) return false;
if (!isSameFloat(d.patientPosition[1],d2.patientPosition[1])) return false;
if (!isSameFloat(d.patientPosition[2],d2.patientPosition[2])) return false;
if (!isSameFloat(d.patientPosition[3],d2.patientPosition[3])) return false;
return true;
} //isSamePosition()
void nii_SaveText(char pathoutname[], struct TDICOMdata d, struct TDCMopts opts, struct nifti_1_header *h, char * dcmname) {
if (!opts.isCreateText) return;
char txtname[2048] = {""};
strcpy (txtname,pathoutname);
strcat (txtname,".txt");
//printf("Saving text %s\n",txtname);
FILE *fp = fopen(txtname, "w");
fprintf(fp, "%s\tField Strength:\t%g\tProtocolName:\t%s\tScanningSequence00180020:\t%s\tTE:\t%g\tTR:\t%g\tSeriesNum:\t%ld\tAcquNum:\t%d\tImageNum:\t%d\tImageComments:\t%s\tDateTime:\t%F\tName:\t%s\tConvVers:\t%s\tDoB:\t%s\tGender:\t%s\tAge:\t%s\tDimXYZT:\t%d\t%d\t%d\t%d\tCoil:\t%d\tEchoNum:\t%d\tOrient(6)\t%g\t%g\t%g\t%g\t%g\t%g\tbitsAllocated\t%d\tInputName\t%s\n",
pathoutname, d.fieldStrength, d.protocolName, d.scanningSequence, d.TE, d.TR, d.seriesNum, d.acquNum, d.imageNum, d.imageComments,
d.dateTime, d.patientName, kDCMvers, d.birthDate, d.gender, d.age, h->dim[1], h->dim[2], h->dim[3], h->dim[4],
d.coilNum,d.echoNum, d.orient[1], d.orient[2], d.orient[3], d.orient[4], d.orient[5], d.orient[6],
d.bitsAllocated, dcmname);
fclose(fp);
}
void nii_SaveBIDS(char pathoutname[], struct TDICOMdata d, struct TDCMopts opts, int sliceDir, struct TDTI4D *dti4D, struct nifti_1_header *h) {
//https://docs.google.com/document/d/1HFUkAEE-pB-angVcYe6pf_-fVf4sCpOHKesUvfb8Grc/edit#
// Generate Brain Imaging Data Structure (BIDS) info
// sidecar JSON file (with the same filename as the .nii.gz file, but with .json extension).
// we will use %g for floats since exponents are allowed
// we will not set the locale, so decimal separator is always a period, as required
// https://www.ietf.org/rfc/rfc4627.txt
if (!opts.isCreateBIDS) return;
char txtname[2048] = {""};
strcpy (txtname,pathoutname);
strcat (txtname,".json");
//printf("Saving DTI %s\n",txtname);
FILE *fp = fopen(txtname, "w");
fprintf(fp, "{\n");
fprintf(fp, "\t\"EchoTime\": %g,\n", d.TE / 1000.0 );
fprintf(fp, "\t\"RepetitionTime\": %g,\n", d.TR / 1000.0 );
if ((d.CSA.bandwidthPerPixelPhaseEncode > 0.0) && (h->dim[2] > 0) && (h->dim[1] > 0)) {
float dwellTime = 0;
if (d.phaseEncodingRC =='C')
dwellTime = 1.0/d.CSA.bandwidthPerPixelPhaseEncode/h->dim[2];
else
dwellTime = 1.0/d.CSA.bandwidthPerPixelPhaseEncode/h->dim[1];
fprintf(fp, "\t\"EffectiveEchoSpacing\": %g,\n", dwellTime );
}
bool first = 1;
if (dti4D->S[0].sliceTiming >= 0.0) {
fprintf(fp, "\t\"SliceTiming\": [\n");
for (int i = 0; i < kMaxDTI4D; i++) {
if (dti4D->S[i].sliceTiming >= 0.0){
if (!first)
fprintf(fp, ",\n");
else
first = 0;
fprintf(fp, "\t\t%g", dti4D->S[i].sliceTiming / 1000.0 );
}
}
fprintf(fp, "\t],\n");
}
if (d.phaseEncodingRC == 'C')
fprintf(fp, "\t\"PhaseEncodingDirection\": \"j");
else
fprintf(fp, "\t\"PhaseEncodingDirection\": \"i");
//phaseEncodingDirectionPositive has one of three values: UNKNOWN (-1), NEGATIVE (0), POSITIVE (1)
//However, DICOM and NIfTI are reversed in the j (ROW) direction
//Equivalent to dicm2nii's "if flp(iPhase), phPos = ~phPos; end"
if ((d.CSA.phaseEncodingDirectionPositive == 1) && ((opts.isFlipY)))
fprintf(fp, "-");
if ((d.CSA.phaseEncodingDirectionPositive == 0) && ((!opts.isFlipY)))
fprintf(fp, "-");
fprintf(fp, "\"\n");
fprintf(fp, "}\n");
fclose(fp);
}
int nii_SaveDTI(char pathoutname[],int nConvert, struct TDCMsort dcmSort[],struct TDICOMdata dcmList[], struct TDCMopts opts, int sliceDir, struct TDTI4D *dti4D) {
//reports non-zero if last volumes should be excluded (e.g. philip stores an ADC maps)
//to do: works with 3D mosaics and 4D files, must remove repeated volumes for 2D sequences....
uint64_t indx0 = dcmSort[0].indx; //first volume
int numDti = dcmList[indx0].CSA.numDti;
if (numDti < 1) return false;
if ((numDti < 3) && (nConvert < 3)) return false;
TDTI * vx = NULL;
if (numDti > 2) {
vx = (TDTI *)malloc(numDti * sizeof(TDTI));
for (int i = 0; i < numDti; i++) //for each direction
for (int v = 0; v < 4; v++) //for each vector+B-value
vx[i].V[v] = dti4D->S[i].V[v];
} else { //if (numDti == 1) {//extract DTI from different slices
vx = (TDTI *)malloc(nConvert * sizeof(TDTI));
numDti = 0;
for (int i = 0; i < nConvert; i++) { //for each image
if ((dcmList[indx0].CSA.mosaicSlices > 1) || (isSamePosition(dcmList[indx0],dcmList[dcmSort[i].indx]))) {
//if (numDti < kMaxDTIv)
for (int v = 0; v < 4; v++) //for each vector+B-value
vx[numDti].V[v] = dcmList[dcmSort[i].indx].CSA.dtiV[v]; //dcmList[indx0].CSA.dtiV[numDti][v] = dcmList[dcmSort[i].indx].CSA.dtiV[0][v];
numDti++;
} //for slices with repeats
}//for each file
dcmList[indx0].CSA.numDti = numDti;
}
bool bValueVaries = false;
for (int i = 1; i < numDti; i++) //check if all bvalues match first volume
if (vx[i].V[0] != vx[0].V[0]) bValueVaries = true;
if (!bValueVaries) {
bool bVecVaries = false;
for (int i = 1; i < numDti; i++) {//check if all bvalues match first volume
if (vx[i].V[1] != vx[0].V[1]) bVecVaries = true;
if (vx[i].V[2] != vx[0].V[2]) bVecVaries = true;
if (vx[i].V[3] != vx[0].V[3]) bVecVaries = true;
}
if (!bVecVaries) {
free(vx);
return false;
}
for (int i = 1; i < numDti; i++)
printf("bxyz %g %g %g %g\n",vx[i].V[0],vx[i].V[1],vx[i].V[2],vx[i].V[3]);
printf("Error: only one B-value reported for all volumes: %g\n",vx[0].V[0]);
free(vx);
return false;
}
int firstB0 = -1;
for (int i = 0; i < numDti; i++) //check if all bvalues match first volume
if (isSameFloat(vx[i].V[0],0) ) {
firstB0 = i;
break;
}
//printf("2015ALPHA %d -> %d\n",numDti, nConvert);
#ifdef myUseCOut
if (firstB0 < 0)
std::cout<<"Warning: this diffusion series does not have a B0 (reference) volume"<<std::endl;
if (firstB0 > 0)
std::cout<<"Note: B0 not the first volume in the series (FSL eddy reference volume is "<<firstB0<<")"<<std::endl;
#else
if (firstB0 < 0) printf("Warning: this diffusion series does not have a B0 (reference) volume\n");
if (firstB0 > 0) printf("Note: B0 not the first volume in the series (FSL eddy reference volume is %d)\n", firstB0);
#endif
int numFinalADC = 0;
if (dcmList[dcmSort[0].indx].manufacturer == kMANUFACTURER_PHILIPS) {
int i = numDti - 1;
while ((i > 0) && (!isSameFloat(vx[i].V[0],0.0f)) && //not a B-0 image
((isSameFloat(vx[i].V[1],0.0f)) &&
(isSameFloat(vx[i].V[2],0.0f)) &&
(isSameFloat(vx[i].V[3],0.0f)) ) ){//yet all vectors are zero!!!! must be ADC
numFinalADC++; //final volume is ADC map
numDti --; //remove final volume - it is a computed ADC map!
dcmList[indx0].CSA.numDti = numDti;
i --;
} //
if (numFinalADC > 0)
printf("Note: final %d volumes appear to be ADC images that will be removed to allow processing\n", numFinalADC);
/*for (int i = 0; i < (numDti); i++) {
if ((!isSameFloat(vx[i].V[0],0.0f)) && //not a B-0 image
((isSameFloat(vx[i].V[1],0.0f)) &&
(isSameFloat(vx[i].V[2],0.0f)) &&
(isSameFloat(vx[i].V[3],0.0f)) ) )
printf("Warning: volume %d appears to be an ADC volume %g %g %g\n", i+1, vx[i].V[1], vx[i].V[2], vx[i].V[3]);
}*/
}
// philipsCorrectBvecs(&dcmList[indx0]); //<- replaced by unified siemensPhilips solution
geCorrectBvecs(&dcmList[indx0],sliceDir, vx);
siemensPhilipsCorrectBvecs(&dcmList[indx0],sliceDir, vx);
if (!opts.isFlipY ) { //!FLIP_Y&& (dcmList[indx0].CSA.mosaicSlices < 2) mosaics are always flipped in the Y direction
for (int i = 0; i < (numDti); i++) {
if (fabs(vx[i].V[2]) > FLT_EPSILON)
vx[i].V[2] = -vx[i].V[2];
} //for each direction
} //if not a mosaic
if (opts.isVerbose) {
for (int i = 0; i < (numDti); i++) {
#ifdef myUseCOut
std::cout<<i<<"\tB=\t"<<dcmList[indx0].CSA.dtiV[i][0]<<"\tVec=\t"<<
dcmList[indx0].CSA.dtiV[i][1]<<"\t"<<dcmList[indx0].CSA.dtiV[i][2]
<<"\t"<<dcmList[indx0].CSA.dtiV[i][3]<<std::endl;
#else
printf("%d\tB=\t%g\tVec=\t%g\t%g\t%g\n",i, vx[i].V[0],
vx[i].V[1],vx[i].V[2],vx[i].V[3]);
#endif
} //for each direction
}
//printf("%f\t%f\t%f",dcmList[indx0].CSA.dtiV[1][1],dcmList[indx0].CSA.dtiV[1][2],dcmList[indx0].CSA.dtiV[1][3]);
char txtname[2048] = {""};
strcpy (txtname,pathoutname);
strcat (txtname,".bval");
//printf("Saving DTI %s\n",txtname);
FILE *fp = fopen(txtname, "w");
if (fp == NULL) {
free(vx);
return numFinalADC;
}
for (int i = 0; i < (numDti-1); i++) {
if (opts.isCreateBIDS) {
fprintf(fp, "%g ", vx[i].V[0]);
} else {
fprintf(fp, "%g\t", vx[i].V[0]);
}
}
fprintf(fp, "%g\n", vx[numDti-1].V[0]);
fclose(fp);
strcpy(txtname,pathoutname);
strcat (txtname,".bvec");
//printf("Saving DTI %s\n",txtname);
fp = fopen(txtname, "w");
if (fp == NULL) {
free(vx);
return numFinalADC;
}
for (int v = 1; v < 4; v++) {
for (int i = 0; i < (numDti-1); i++) {
if (opts.isCreateBIDS) {
fprintf(fp, "%g ", vx[i].V[v]);
} else {
fprintf(fp, "%g\t", vx[i].V[v]);
}
}
fprintf(fp, "%g\n", vx[numDti-1].V[v]);
}
fclose(fp);
free(vx);
return numFinalADC;
} //nii_SaveDTI()
float sqr(float v){
return v*v;
} //sqr()
float intersliceDistance(struct TDICOMdata d1, struct TDICOMdata d2) {
//some MRI scans have gaps between slices, some CT have overlapping slices. Comparing adjacent slices provides measure for dx between slices
if ( isNanPosition(d1) || isNanPosition(d2))
return d1.xyzMM[3];
float tilt = 1.0;
if (d1.gantryTilt != 0)
tilt = (float) cos(d1.gantryTilt * M_PI/180); //for CT scans with gantry tilt, we need to compute distance between slices, not distance along bed
return tilt * sqrt( sqr(d1.patientPosition[1]-d2.patientPosition[1])+
sqr(d1.patientPosition[2]-d2.patientPosition[2])+
sqr(d1.patientPosition[3]-d2.patientPosition[3]));
} //intersliceDistance()
void swapDim3Dim4(int d3, int d4, struct TDCMsort dcmSort[]) {
//swap space and time: input A0,A1...An,B0,B1...Bn output A0,B0,A1,B1,...
int nConvert = d3 * d4;
#ifdef _MSC_VER
TDCMsort * dcmSortIn = (TDCMsort *)malloc(nConvert * sizeof(TDCMsort));
#else
struct TDCMsort dcmSortIn[nConvert];
#endif
for (int i = 0; i < nConvert; i++) dcmSortIn[i] = dcmSort[i];
int i = 0;
for (int b = 0; b < d3; b++)
for (int a = 0; a < d4; a++) {
int k = (a *d3) + b;
//printf("%d -> %d %d ->%d\n",i,a, b, k);
dcmSort[k] = dcmSortIn[i];
i++;
}
#ifdef _MSC_VER
free(dcmSortIn);
#endif
} //swapDim3Dim4()
bool intensityScaleVaries(int nConvert, struct TDCMsort dcmSort[],struct TDICOMdata dcmList[]){
//detect whether some DICOM images report different intensity scaling
//some Siemens PET scanners generate 16-bit images where slice has its own scaling factor.
// since NIfTI provides a single scaling factor for each file, these images require special consideration
if (nConvert < 2) return false;
bool iVaries = false;
float iScale = dcmList[dcmSort[0].indx].intenScale;
float iInter = dcmList[dcmSort[0].indx].intenIntercept;
for (int i = 1; i < nConvert; i++) { //stack additional images
uint64_t indx = dcmSort[i].indx;
if (fabs (dcmList[indx].intenScale - iScale) > FLT_EPSILON) iVaries = true;
if (fabs (dcmList[indx].intenIntercept- iInter) > FLT_EPSILON) iVaries = true;
}
return iVaries;
} //intensityScaleVaries()
/*unsigned char * nii_bgr2rgb(unsigned char* bImg, struct nifti_1_header *hdr) {
//DICOM planarappears to be BBB..B,GGG..G,RRR..R, NIfTI RGB saved in planes RRR..RGGG..GBBBB..B
// see http://www.barre.nom.fr/medical/samples/index.html US-RGB-8-epicard
if (hdr->datatype != DT_RGB24) return bImg;
int dim3to7 = 1;
for (int i = 3; i < 8; i++)
if (hdr->dim[i] > 1) dim3to7 = dim3to7 * hdr->dim[i];
int sliceBytes24 = hdr->dim[1]*hdr->dim[2] * hdr->bitpix/8;
int sliceBytes8 = hdr->dim[1]*hdr->dim[2];
//Byte bImg[ bSz ];
//[img getBytes:&bImg length:bSz];
unsigned char slice24[sliceBytes24];
int sliceOffsetR = 0;
for (int sl = 0; sl < dim3to7; sl++) { //for each 2D slice
memcpy(&slice24, &bImg[sliceOffsetR], sliceBytes24);
memcpy( &bImg[sliceOffsetR], &slice24[sliceBytes8*2], sliceBytes8);
sliceOffsetR += sliceBytes8;
memcpy( &bImg[sliceOffsetR], &slice24[sliceBytes8], sliceBytes8);
sliceOffsetR += sliceBytes8;
memcpy( &bImg[sliceOffsetR], &slice24[0], sliceBytes8);
sliceOffsetR += sliceBytes8;
} //for each slice
return bImg;
} //nii_ImgBytes()*/
bool niiExists(const char*pathoutname) {
char niiname[2048] = {""};
strcat (niiname,pathoutname);
strcat (niiname,".nii");
if (is_fileexists(niiname)) return true;
char gzname[2048] = {""};
strcat (gzname,pathoutname);
strcat (gzname,".nii.gz");
if (is_fileexists(gzname)) return true;
return false;
} //niiExists()
#ifndef W_OK
#define W_OK 2 /* write mode check */
#endif
int nii_createFilename(struct TDICOMdata dcm, char * niiFilename, struct TDCMopts opts) {
char pth[1024] = {""};
if (strlen(opts.outdir) > 0) {
strcpy(pth, opts.outdir);
int w =access(pth,W_OK);
if (w != 0) {
if (getcwd(pth, sizeof(pth)) != NULL) {
w =access(pth,W_OK);
if (w != 0) {
#ifdef myUseCOut
std::cout<<"Error: you do not have write permissions for the directory "<<opts.outdir<<std::endl;
#else
printf("Error: you do not have write permissions for the directory %s\n",opts.outdir);
#endif
return EXIT_FAILURE;
}
#ifdef myUseCOut
std::cout<<"Warning: "<<opts.outdir<<" write permission denied. Saving to working directory "<<pth<<std::endl;
#else
printf("Warning: %s write permission denied. Saving to working directory %s \n", opts.outdir, pth);
#endif
}
}
}
char inname[1024] = {""};//{"test%t_%av"}; //% a = acquisition, %n patient name, %t time
strcpy(inname, opts.filename);
char outname[1024] = {""};
char newstr[256];
if (strlen(inname) < 1) {
strcpy(inname, "T%t_N%n_S%s");
}
int start = 0;
int pos = 0;
while (pos < strlen(inname)) {
if (inname[pos] == '%') {
if (pos > start) {
strncpy(&newstr[0], &inname[0] + start, pos - start);
newstr[pos - start] = '\0';
strcat (outname,newstr);
}
pos++; //extra increment: skip both % and following character
char f = 'P';
if (pos < strlen(inname)) f = toupper(inname[pos]);
if (f == 'C')
strcat (outname,dcm.imageComments);
//if (f == 'E') {
// sprintf(newstr, "%d", dcm.echoNum);
// strcat (outname,newstr);
//}
if (f == 'F')
strcat (outname,opts.indirParent);
if (f == 'I')
strcat (outname,dcm.patientID);
if (f == 'M') {
if (dcm.manufacturer == kMANUFACTURER_GE)
strcat (outname,"GE");
else if (dcm.manufacturer == kMANUFACTURER_TOSHIBA)
strcat (outname,"To");
else if (dcm.manufacturer == kMANUFACTURER_PHILIPS)
strcat (outname,"Ph");
else if (dcm.manufacturer == kMANUFACTURER_SIEMENS)
strcat (outname,"Si");
else
strcat (outname,"NA"); //manufacturer name not available
}
if (f == 'N')
strcat (outname,dcm.patientName);
if (f == 'P')
strcat (outname,dcm.protocolName);
if (f == 'Q')
strcat (outname,dcm.scanningSequence);
if ((f >= '0') && (f <= '9')) {
if ((pos<strlen(inname)) && (toupper(inname[pos+1]) == 'S')) {
char zeroPad[12] = {""};
sprintf(zeroPad,"%%0%dd",atoi(&f));
sprintf(newstr, zeroPad, dcm.seriesNum);
strcat (outname,newstr);
pos++; // e.g. %3f requires extra increment: skip both number and following character
}
}
if (f == 'S') {
sprintf(newstr, "%ld", dcm.seriesNum);
strcat (outname,newstr);
}
if (f == 'T') {
sprintf(newstr, "%0.0f", dcm.dateTime);
strcat (outname,newstr);
}
start = pos + 1;
} //found a % character
pos++;
} //for each character in input
if (dcm.coilNum > 1) {
sprintf(newstr, "_c%d", dcm.coilNum);
strcat (outname,newstr);
}
if (dcm.echoNum > 1) {
sprintf(newstr, "_e%d", dcm.echoNum);
strcat (outname,newstr);
}
if (dcm.isHasPhase)
strcat (outname,"_ph"); //manufacturer name not available
if (pos > start) { //append any trailing characters
strncpy(&newstr[0], &inname[0] + start, pos - start);
newstr[pos - start] = '\0';
strcat (outname,newstr);
}
if (strlen(outname) < 1) strcpy(outname, "dcm2nii_invalidName");
if (outname[0] == '.') outname[0] = '_'; //make sure not a hidden file
//eliminate illegal characters http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
for (int pos = 0; pos<strlen(outname); pos ++)
if ((outname[pos] == '<') || (outname[pos] == '>') || (outname[pos] == ':')
|| (outname[pos] == '"') || (outname[pos] == '\\') || (outname[pos] == '/')
|| (outname[pos] == '^')
|| (outname[pos] == '*') || (outname[pos] == '|') || (outname[pos] == '?'))
outname[pos] = '_';
//printf("outname=*%s* %d %d\n", outname, pos,start);
char baseoutname[2048] = {""};
strcat (baseoutname,pth);
char appendChar[2] = {"a"};
appendChar[0] = kPathSeparator;
if (pth[strlen(pth)-1] != kPathSeparator)
strcat (baseoutname,appendChar);
strcat (baseoutname,outname);
char pathoutname[2048] = {""};
strcat (pathoutname,baseoutname);
int i = 0;
while (niiExists(pathoutname) && (i < 26)) {
strcpy(pathoutname,baseoutname);
appendChar[0] = 'a'+i;
strcat (pathoutname,appendChar);
i++;
}
if (i >= 26) {
#ifdef myUseCOut
std::cout<<"Error: too many NIFTI images with the name "<<baseoutname<<std::endl;
#else
printf("Error: too many NIFTI images with the name %s\n", baseoutname);
#endif
return EXIT_FAILURE;
}
//printf("-->%s\n",pathoutname); return EXIT_SUCCESS;
//printf("outname=%s\n", pathoutname);
strcpy(niiFilename,pathoutname);
return EXIT_SUCCESS;
} //nii_createFilename()
void nii_createDummyFilename(char * niiFilename, struct TDCMopts opts) {
//generate string that illustrating sample of filename
struct TDICOMdata dcm = clear_dicom_data();
strcpy(opts.indirParent,"myFolder");
char niiFilenameBase[1024] = {"/usr/myFolder/dicom.dcm"};
nii_createFilename(dcm, niiFilenameBase, opts) ;
strcpy(niiFilename,"Example output filename: '");
strcat(niiFilename,niiFilenameBase);
if (opts.isGz)
strcat(niiFilename,".nii.gz'");
else
strcat(niiFilename,".nii'");
} //nii_createDummyFilename()
#ifndef myDisableZLib
#ifndef MiniZ
unsigned long mz_compressBound(unsigned long source_len) {
return compressBound(source_len);
}
unsigned long mz_crc32(unsigned long crc, const unsigned char *ptr, size_t buf_len) {
return crc32(crc, ptr, (uInt) buf_len);
}
#endif
void writeNiiGz (char * baseName, struct nifti_1_header hdr, unsigned char* src_buffer, unsigned long src_len) {
//create gz file in RAM, save to disk http://www.zlib.net/zlib_how.html
// in general this single-threaded approach is slower than PIGZ but is useful for slow (network attached) disk drives
char fname[2048] = {""};
strcpy (fname,baseName);
strcat (fname,".nii.gz");
unsigned long hdrPadBytes = sizeof(hdr) + 4; //348 byte header + 4 byte pad
unsigned long cmp_len = mz_compressBound(src_len+hdrPadBytes);
unsigned char *pCmp = (unsigned char *)malloc(cmp_len);
z_stream strm;
strm.total_in = 0;
strm.total_out = 0;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_out = pCmp; // output char array
strm.avail_out = (unsigned int)cmp_len; // size of output
//if ( deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY)!= Z_OK) return;
if (deflateInit(&strm, Z_DEFAULT_COMPRESSION)!= Z_OK) {
free(pCmp);
return;
}
//add header
unsigned char *pHdr = (unsigned char *)malloc(hdrPadBytes);
pHdr[hdrPadBytes-1] = 0; pHdr[hdrPadBytes-2] = 0; pHdr[hdrPadBytes-3] = 0; pHdr[hdrPadBytes-4] = 0;
memcpy(pHdr,&hdr, sizeof(hdr));
strm.avail_in = (unsigned int)hdrPadBytes; // size of input
strm.next_in = (uint8_t *)pHdr; // input header -- TPX strm.next_in = (Bytef *)pHdr; uint32_t
deflate(&strm, Z_NO_FLUSH);
//add image
strm.avail_in = (unsigned int)src_len; // size of input
strm.next_in = (uint8_t *)src_buffer; // input image -- TPX strm.next_in = (Bytef *)src_buffer;
deflate(&strm, Z_FINISH); //Z_NO_FLUSH;
//finish up
deflateEnd(&strm);
unsigned long file_crc32 = mz_crc32(0L, Z_NULL, 0);
file_crc32 = mz_crc32(file_crc32, pHdr, (unsigned int)hdrPadBytes);
file_crc32 = mz_crc32(file_crc32, src_buffer, (unsigned int)src_len);
cmp_len = strm.total_out;
if (cmp_len <= 0) {
free(pCmp);
free(src_buffer);
return;
}
FILE *fileGz = fopen(fname, "wb");
if (!fileGz) {
free(pCmp);
free(src_buffer);
return;
}
//write header http://www.gzip.org/zlib/rfc-gzip.html
fputc((char)0x1f, fileGz); //ID1
fputc((char)0x8b, fileGz); //ID2
fputc((char)0x08, fileGz); //CM - use deflate compression method
fputc((char)0x00, fileGz); //FLG - no addition fields
fputc((char)0x00, fileGz); //MTIME0
fputc((char)0x00, fileGz); //MTIME1
fputc((char)0x00, fileGz); //MTIME2
fputc((char)0x00, fileGz); //MTIME2
fputc((char)0x00, fileGz); //XFL
fputc((char)0xff, fileGz); //OS
//write Z-compressed data
fwrite (&pCmp[2] , sizeof(char), cmp_len-6, fileGz); //-6 as LZ78 format has 2 bytes header (typically 0x789C) and 4 bytes tail (ADLER 32)
//write tail: write redundancy check and uncompressed size as bytes to ensure LITTLE-ENDIAN order
fputc((unsigned char)(file_crc32), fileGz);
fputc((unsigned char)(file_crc32 >> 8), fileGz);
fputc((unsigned char)(file_crc32 >> 16), fileGz);
fputc((unsigned char)(file_crc32 >> 24), fileGz);
fputc((unsigned char)(strm.total_in), fileGz);
fputc((unsigned char)(strm.total_in >> 8), fileGz);
fputc((unsigned char)(strm.total_in >> 16), fileGz);
fputc((unsigned char)(strm.total_in >> 24), fileGz);
fclose(fileGz);
free(pCmp);
free(pHdr);
} //writeNiiGz()
#endif
int nii_saveNII(char * niiFilename, struct nifti_1_header hdr, unsigned char* im, struct TDCMopts opts) {
hdr.vox_offset = 352;
size_t imgsz = nii_ImgBytes(hdr);
#ifndef myDisableZLib
if ((opts.isGz) && (strlen(opts.pigzname) < 1) && ((imgsz+hdr.vox_offset) < 2147483647) ) { //use internal compressor
//if (true) {//TPX
writeNiiGz (niiFilename, hdr, im,imgsz);
return EXIT_SUCCESS;
}
#endif
char fname[2048] = {""};
strcpy (fname,niiFilename);
strcat (fname,".nii");
FILE *fp = fopen(fname, "wb");
if (!fp) return EXIT_FAILURE;
fwrite(&hdr, sizeof(hdr), 1, fp);
uint32_t pad = 0;
fwrite(&pad, sizeof( pad), 1, fp);
fwrite(&im[0], imgsz, 1, fp);
fclose(fp);
if ((opts.isGz) && (strlen(opts.pigzname) > 0) ) {
char command[768];
strcpy(command, "\"" );
strcat(command, opts.pigzname );
strcat(command, "\" -n -f \""); //current versions of pigz (2.3) built on Windows can hang if the filename is included, presumably because it is not finding the path characters ':\'
strcat(command, fname);
strcat(command, "\""); //add quotes in case spaces in filename 'pigz "c:\my dir\img.nii"'
#if defined(_WIN64) || defined(_WIN32) //using CreateProcess instead of system to run in background (avoids screen flicker)
DWORD exitCode;
PROCESS_INFORMATION ProcessInfo = {0};
STARTUPINFO startupInfo= {0};
startupInfo.cb = sizeof(startupInfo);
//StartupInfo.cb = sizeof StartupInfo ; //Only compulsory field
if(CreateProcess(NULL, command, NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW,NULL, NULL,&startupInfo,&ProcessInfo)) {
//printf("compression --- %s\n",command);
WaitForSingleObject(ProcessInfo.hProcess,INFINITE);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
} else
printf("compression failed %s\n",command);
#else //if win else linux
system(command);
#endif //else linux
#ifdef myUseCOut
std::cout<<"compress: "<<command<<std::endl;
#else
printf("compress: %s\n",command);
#endif
}
return EXIT_SUCCESS;
} //nii_saveNII()
int nii_saveNII3D(char * niiFilename, struct nifti_1_header hdr, unsigned char* im, struct TDCMopts opts) {
//save 4D series as sequence of 3D volumes
struct nifti_1_header hdr1 = hdr;
int nVol = 1;
for (int i = 4; i < 8; i++) {
if (hdr.dim[i] > 1) nVol = nVol * hdr.dim[i];
hdr1.dim[i] = 0;
}
hdr1.dim[0] = 3; //save as 3D file
size_t imgsz = nii_ImgBytes(hdr1);
size_t pos = 0;
char fname[2048] = {""};
char zeroPad[1024] = {""};
double fnVol = nVol;
int zeroPadLen = (1 + log10( fnVol));
sprintf(zeroPad,"%%s_%%0%dd",zeroPadLen);
for (int i = 1; i <= nVol; i++) {
sprintf(fname,zeroPad,niiFilename,i);
if (nii_saveNII(fname, hdr1, (unsigned char*)&im[pos], opts) == EXIT_FAILURE) return EXIT_FAILURE;
pos += imgsz;
}
return EXIT_SUCCESS;
} //nii_saveNII3D
void nii_check16bitUnsigned(unsigned char *img, struct nifti_1_header *hdr){
//default NIfTI 16-bit is signed, set to unusual 16-bit unsigned if required...
if (hdr->datatype != DT_UINT16) return;
int dim3to7 = 1;
for (int i = 3; i < 8; i++)
if (hdr->dim[i] > 1) dim3to7 = dim3to7 * hdr->dim[i];
int nVox = hdr->dim[1]*hdr->dim[2]* dim3to7;
if (nVox < 1) return;
unsigned short * img16 = (unsigned short*) img;
unsigned short max16 = img16[0];
//clock_t start = clock();
for (int i=0; i < nVox; i++)
if (img16[i] > max16)
max16 = img16[i];
//printf("max16= %d vox=%d %fms\n",max16, nVox, ((double)(clock()-start))/1000);
if (max16 > 32767)
#ifdef myUseCOut
std::cout<<"Note: intensity range requires saving as rare 16-bit UNSIGNED integer. Subsequent tools may require 32-bit conversion"<<std::endl;
#else
printf("Note: intensity range requires saving as rare 16-bit UNSIGNED integer. Subsequent tools may require 32-bit conversion\n");
#endif
else
hdr->datatype = DT_INT16;
} //nii_check16bitUnsigned()
int siemensCtKludge(int nConvert, struct TDCMsort dcmSort[],struct TDICOMdata dcmList[]) {
//Siemens CT bug: when a user draws an open object graphics object onto a 2D slice this is appended as an additional image,