-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSortDicomFiles.cpp
More file actions
1294 lines (975 loc) · 39.8 KB
/
SortDicomFiles.cpp
File metadata and controls
1294 lines (975 loc) · 39.8 KB
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
/*-
* Nathan Lay
* Imaging Biomarkers and Computer-Aided Diagnosis Laboratory
* National Institutes of Health
* March 2017
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*-
* Nathan Lay
* AI Resource at National Cancer Institute
* National Institutes of Health
* February 2022
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cstdlib>
#include <cstdint>
#include <cctype>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <set>
#include <limits>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#include "Common.h"
#include "bsdgetopt.h"
#include "strcasestr.h"
// ITK stuff
#include "itkGDCMImageIO.h"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.h"
#include "itkRGBPixel.h"
#include "itkRGBAPixel.h"
#ifdef USE_MD5
#include "itkTestingHashImageFilter.h"
#endif // USE_MD5
#if ITK_VERSION_MAJOR > 4
using IOFileModeEnum = itk::IOFileModeEnum;
using IOComponentEnum = itk::IOComponentEnum;
using IOPixelEnum = itk::IOPixelEnum;
#else // ITK_VERSION_MAJOR <= 4
using IOFileModeEnum = itk::ImageIOFactory;
using IOComponentEnum = itk::ImageIOBase;
using IOPixelEnum = itk::ImageIOBase;
#endif // ITK_VERSION_MAJOR > 4
#include "gdcmBase64.h"
#include "gdcmCSAHeader.h"
#include "gdcmCSAElement.h"
std::map<std::string, std::string> g_mNameToTagMap;
std::unordered_map<std::string, itk::ImageBase<3>::Pointer> g_mSeriesUIDToImageBase;
std::unordered_map<std::string, std::unordered_map<std::string, unsigned int>> g_mSeriesUIDToInstanceUIDVolumeNumberMap;
#ifdef USE_MD5
std::unordered_map<std::string, std::string> g_mSeriesUIDToMD5;
#endif // USE_MD5
void Usage(const char *p_cArg0) {
std::cerr << "Usage: " << p_cArg0 << " [-cehlr] folder|filePattern [folder2|filePattern2 ...] destinationPattern" << std::endl;
std::cerr << "\nOptions:" << std::endl;
std::cerr << "-c -- Copy instead of move." << std::endl;
std::cerr << "-e -- Try to remove empty folders." << std::endl;
std::cerr << "-l -- List supported patterns." << std::endl;
std::cerr << "-h -- This help message." << std::endl;
std::cerr << "-r -- Search for DICOMs recursively." << std::endl;
exit(1);
}
void PrintSupportedPatterns() {
std::cout << "Supported patterns:" << std::endl;
for (auto itr = g_mNameToTagMap.begin(); itr != g_mNameToTagMap.end(); ++itr)
std::cout << '<' << itr->first << "> (" << itr->second << ')' << std::endl;
std::cout << "<diffusion b-value> (0018|9087 or vendor-specific)" << std::endl;
std::cout << "<volume number> (volume acquisition ordinal in time series scans)" << std::endl;
std::cout << "<z spacing> (z voxel spacing)" << std::endl;
std::cout << "<z coordinate> (z voxel coordinate)" << std::endl;
std::cout << "<z origin> (z patient origin)" << std::endl;
std::cout << "<x dim> (x voxel dimension)" << std::endl;
std::cout << "<y dim> (y voxel dimension)" << std::endl;
std::cout << "<z dim> (z voxel dimension)" << std::endl;
#ifdef USE_MD5
std::cout << "<slice md5> (MD5 hash of pixel data)" << std::endl;
std::cout << "<volume md5> (MD5 hash of voxel data)" << std::endl;
#endif // USE_MD5
std::cout << "<file> (file's basename)" << std::endl;
std::cout << "<folder> (file's dirname)" << std::endl;
}
bool IsHexDigit(char c);
bool ParseITKTag(const std::string &strKey, uint16_t &ui16Group, uint16_t &ui16Element);
template<typename ValueType>
bool ExposeCSAMetaData(gdcm::CSAHeader &clHeader, const char *p_cKey, ValueType &value);
template<>
bool ExposeCSAMetaData<std::string>(gdcm::CSAHeader &clHeader, const char *p_cKey, std::string &strValue);
bool GetCSAHeaderFromElement(const itk::MetaDataDictionary &clDicomTags, const std::string &strKey, gdcm::CSAHeader &clCSAHeader);
void EnsureRmDir(const std::string &strPath);
void MakeFoldersForFile(const std::string &strPath);
std::string MakeFailedValue(const std::string &strTag);
std::string MakeValue(const std::string &strTag, const itk::MetaDataDictionary &clDicomTags, const std::string &strPath = "");
bool ProcessString(std::string &strPattern, const itk::MetaDataDictionary &clDicomTags, const std::string &strPath = "");
bool MoveDicomFile(const std::string &strFileName, const std::string &strPattern, bool bCopy);
// Special handling
itk::ImageBase<3>::Pointer LoadImageBase(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
std::string ComputeZCoordinate(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
std::string ComputeZOrigin(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
std::string ComputeZSpacing(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
std::string ComputeDimension(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath, int iDim);
std::string ComputeDiffusionBValue(const itk::MetaDataDictionary &clDicomTags);
std::string ComputeDiffusionBValueSiemens(const itk::MetaDataDictionary &clDicomTags);
std::string ComputeDiffusionBValueGE(const itk::MetaDataDictionary &clDicomTags);
std::string ComputeDiffusionBValueProstateX(const itk::MetaDataDictionary &clDicomTags); // Same as Skyra and Verio
std::string ComputeDiffusionBValuePhilips(const itk::MetaDataDictionary &clDicomTags);
void ComputeVolumeNumberByTemporalPosition(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
void ComputeVolumeNumberByAcquisitionTime(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
std::string ComputeVolumeNumber(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath);
#ifdef USE_MD5
template<typename PixelType, unsigned int Dimension>
std::string ComputeMD5HashHelper(const std::string &strFilePath);
template<unsigned int Dimension>
std::string ComputeMD5Hash(const itk::MetaDataDictionary &clDicomTags, const std::string &strFilePath);
#endif // USE_MD5
int main(int argc, char **argv) {
const char * const p_cArg0 = argv[0];
// Populate the description -> tag map
// http://dicom.nema.org/medical/dicom/current/output/chtml/part06/chapter_6.html
g_mNameToTagMap["patient id"] = "0010|0020";
g_mNameToTagMap["patient name"] = "0010|0010";
g_mNameToTagMap["series description"] = "0008|103e"; // Must be lowercase hex!
g_mNameToTagMap["series number"] = "0020|0011";
g_mNameToTagMap["sequence name"] = "0018|0024"; // Used in ProstateX for encoding b-value
g_mNameToTagMap["instance number"] = "0020|0013";
g_mNameToTagMap["instance uid"] = "0008|0018";
g_mNameToTagMap["study date"] = "0008|0020";
g_mNameToTagMap["accession number"] = "0008|0050";
g_mNameToTagMap["series uid"] = "0020|000e";
g_mNameToTagMap["body part examined"] = "0018|0015";
g_mNameToTagMap["acquisition date"] = "0008|0022";
g_mNameToTagMap["acquisition time"] = "0008|0032";
g_mNameToTagMap["temporal position"] = "0020|0100";
g_mNameToTagMap["repetition time"] = "0018|0080";
g_mNameToTagMap["echo time"] = "0018|0081";
g_mNameToTagMap["magnetic field strength"] = "0018|0087";
g_mNameToTagMap["field of view"] = "0018|0094";
g_mNameToTagMap["manufacturer"] = "0008|0070";
g_mNameToTagMap["flip angle"] = "0018|1314";
g_mNameToTagMap["slice thickness"] = "0018|0050";
g_mNameToTagMap["acquisition matrix"] = "0018|1310";
bool bEraseFolders = false;
bool bRecursive = false;
bool bCopy = false;
int c = 0;
while ((c = getopt(argc, argv, "cehlr")) != -1) {
switch (c) {
case 'c':
bCopy = true;
break;
case 'h':
Usage(p_cArg0);
break;
case 'e':
bEraseFolders = true;
break;
case 'l':
PrintSupportedPatterns();
return 0;
case 'r':
bRecursive = true;
break;
case '?':
default:
Usage(p_cArg0); // Exits
break;
}
}
argc -= optind;
argv += optind;
if (argc < 2)
Usage(p_cArg0); // Exits
const std::string strDestPattern = argv[argc-1];
--argc;
std::vector<std::string> vFiles;
for (int i = 0; i < argc; ++i) {
const char * const p_cFile = argv[i];
if (strpbrk(p_cFile, "?*") != nullptr) {
// DOS wildcard pattern
FindFiles(DirName(p_cFile).c_str(), p_cFile, vFiles, bRecursive);
}
else if (IsFolder(p_cFile)) {
// Directory
FindFiles(p_cFile, "*", vFiles, bRecursive);
}
else {
// Individual file
vFiles.push_back(p_cFile);
}
}
if (bCopy)
std::cout << "Copying DICOM files to '" << strDestPattern << "' ..." << std::endl;
else
std::cout << "Moving DICOM files to '" << strDestPattern << "' ..." << std::endl;
for (size_t i = 0; i < vFiles.size(); ++i)
MoveDicomFile(vFiles[i], strDestPattern, bCopy);
if (bEraseFolders) {
std::unordered_set<std::string> sFolders;
for (size_t i = 0; i < vFiles.size(); ++i) {
#if defined(_WIN32)
std::vector<std::string> vParts = SplitString(vFiles[i], "/\\");
#elif defined(__unix__)
std::vector<std::string> vParts = SplitString(vFiles[i], "/");
#endif
vParts.pop_back();
std::string strFolder;
for (size_t j = 0; j < vParts.size(); ++j) {
strFolder += vParts[j];
strFolder += '/';
sFolders.insert(strFolder);
}
}
std::vector<std::string> vFolders(sFolders.begin(), sFolders.end());
std::sort(vFolders.begin(), vFolders.end(),
[](const std::string &strString1, const std::string &strString2) -> bool {
return strString1.size() > strString2.size();
});
for (size_t i = 0; i < vFolders.size(); ++i)
EnsureRmDir(vFolders[i]);
}
std::cout << "Done." << std::endl;
return 0;
}
void EnsureRmDir(const std::string &strPath) {
const int iMaxTries = 100;
if (RmDir(strPath)) {
int i = 0;
for (i = 0; i < iMaxTries && FileExists(strPath); ++i)
USleep(100000);
if (i < iMaxTries)
std::cout << "Removed empty folder '" << strPath << "'." << std::endl;
}
}
void MakeFoldersForFile(const std::string &strPath) {
#if defined(_WIN32)
std::vector<std::string> vFolders = SplitString(strPath, "/\\");
#elif defined(__unix__)
std::vector<std::string> vFolders = SplitString(strPath, "/");
#endif
vFolders.pop_back(); // Pop off the filename
std::string strTmpPath;
for (size_t i = 0; i < vFolders.size(); ++i) {
strTmpPath += vFolders[i];
strTmpPath += '/';
if (MkDir(strTmpPath))
std::cout << "Created folder '" << strTmpPath << "'." << std::endl;
}
}
std::string MakeFailedValue(const std::string &strTag) {
std::string strValue = "EMPTY_";
for (size_t i = 0; i < strTag.size(); ++i) {
switch (strTag[i]) {
case ' ':
strValue.push_back('_');
break;
default:
strValue.push_back(std::toupper(strTag[i]));
break;
}
}
return strValue;
}
std::string MakeValue(const std::string &strTag, const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
if (strTag == "file") {
const std::string strValue = BaseName(strPath);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "folder") {
const std::string strValue = DirName(strPath);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "diffusion b-value") {
const std::string strValue = ComputeDiffusionBValue(clDicomTags);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "volume number") {
const std::string strValue = ComputeVolumeNumber(clDicomTags, DirName(strPath));
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "z spacing") {
const std::string strValue = ComputeZSpacing(clDicomTags, DirName(strPath));
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "z coordinate") {
const std::string strValue = ComputeZCoordinate(clDicomTags, DirName(strPath));
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "z origin") {
const std::string strValue = ComputeZOrigin(clDicomTags, DirName(strPath));
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "x dim") {
const std::string strValue = ComputeDimension(clDicomTags, DirName(strPath), 0);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "y dim") {
const std::string strValue = ComputeDimension(clDicomTags, DirName(strPath), 1);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "z dim") {
const std::string strValue = ComputeDimension(clDicomTags, DirName(strPath), 2);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
#ifdef USE_MD5
else if (strTag == "slice md5") {
const std::string strValue = ComputeMD5Hash<2>(clDicomTags, strPath);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
else if (strTag == "volume md5") {
const std::string strValue = ComputeMD5Hash<3>(clDicomTags, strPath);
return strValue.size() > 0 ? strValue : MakeFailedValue(strTag);
}
#endif // USE_MD5
else {
auto itr = g_mNameToTagMap.find(strTag);
if (itr == g_mNameToTagMap.end())
return std::string();
const std::string &strDicomTag = itr->second;
std::string strValue;
if (!itk::ExposeMetaData(clDicomTags, strDicomTag, strValue))
return MakeFailedValue(strTag);
Trim(strValue);
SanitizeFileName(strValue);
return strValue;
}
return std::string(); // Not reached
}
bool ProcessString(std::string &strPattern, const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
// Sanity check
int iParity = 0;
// NOTE: Nesting <> is not supported
for (size_t i = 0; i < strPattern.size() && (iParity == 0 || iParity == 1); ++i) {
switch (strPattern[i]) {
case '<':
++iParity;
break;
case '>':
--iParity;
break;
}
}
if (iParity != 0) {
std::cerr << "Error: Mismatch between '<' and '>' in '" << strPattern << "'. Aborting ..." << std::endl;
return false;
}
std::string strTag, strValue;
size_t p = 0;
while (p < strPattern.size()) {
p = strPattern.find('<', p); // < can never be the last character from sanity check
if (p == std::string::npos) // Nothing left to do
break;
size_t q = strPattern.find('>', p+1); // > must accompany a found < as per sanity check
strTag = strPattern.substr(p+1, q-p-1);
strValue = MakeValue(strTag, clDicomTags, strPath);
if (strValue.empty()) {
std::cerr << "Error: Failed to process tag '" << strTag << "'. Aborting ..." << std::endl;
return false;
}
strPattern.replace(p, q+1-p, strValue);
p += strValue.size();
}
return true;
}
bool MoveDicomFile(const std::string &strFileName, const std::string &strPattern, bool bCopy) {
typedef itk::GDCMImageIO ImageIOType;
ImageIOType::Pointer p_clImageIO = ImageIOType::New();
if (!p_clImageIO->CanReadFile(strFileName.c_str()))
return false; // Not a DICOM file
p_clImageIO->SetFileName(strFileName.c_str());
p_clImageIO->LoadPrivateTagsOn();
try {
p_clImageIO->ReadImageInformation();
}
catch (itk::ExceptionObject &e) {
std::cerr << "Error: Failed to read DICOM file '" << strFileName << "': " << e << std::endl;
return false;
}
itk::MetaDataDictionary clDicomTags = p_clImageIO->GetMetaDataDictionary();
std::string strDestPath = strPattern;
if (!ProcessString(strDestPath, clDicomTags, strFileName)) {
std::cerr << "Error: Failed to form destination path." << std::endl;
return false;
}
MakeFoldersForFile(strDestPath);
if (bCopy) {
if (!Copy(strFileName, strDestPath, false)) {
std::cerr << "Error: Failed to copy file '" << strFileName << "' to '" << strDestPath << "'." << std::endl;
return false;
}
}
else {
if (!Rename(strFileName, strDestPath, false)) {
std::cerr << "Error: Failed to move file '" << strFileName << "' to '" << strDestPath << "'." << std::endl;
return false;
}
}
std::cout << strFileName << " --> " << strDestPath << std::endl;
return true;
}
itk::ImageBase<3>::Pointer LoadImageBase(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
typedef itk::ImageBase<3> ImageType;
std::string strSeriesUID;
if (!itk::ExposeMetaData(clDicomTags, "0020|000e", strSeriesUID))
return ImageType::Pointer();
Trim(strSeriesUID);
ImageType::Pointer p_clImageBase;
auto itr = g_mSeriesUIDToImageBase.find(strSeriesUID);
if (itr == g_mSeriesUIDToImageBase.end()) {
itk::Image<short, 3>::Pointer p_clImage = LoadDicomImage<short, 3>(strPath, strSeriesUID);
if (!p_clImage) {
// Cache the failure so we don't try this again
g_mSeriesUIDToImageBase[strSeriesUID] = ImageType::Pointer();
return ImageType::Pointer();
}
p_clImageBase = ImageType::New();
p_clImageBase->SetRegions(p_clImage->GetLargestPossibleRegion());
p_clImageBase->SetSpacing(p_clImage->GetSpacing());
p_clImageBase->SetDirection(p_clImage->GetDirection());
p_clImageBase->SetOrigin(p_clImage->GetOrigin());
g_mSeriesUIDToImageBase[strSeriesUID] = p_clImageBase;
}
else {
p_clImageBase = itr->second;
}
return p_clImageBase;
}
std::string ComputeZSpacing(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
typedef itk::ImageBase<3> ImageType;
ImageType::Pointer p_clImageBase = LoadImageBase(clDicomTags, strPath);
if (!p_clImageBase)
return std::string();
const ImageType::SpacingType &clSpacing = p_clImageBase->GetSpacing();
std::stringstream spacingStream;
spacingStream << std::setprecision(3) << clSpacing[2];
return spacingStream.str();
}
std::string ComputeDimension(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath, int iDim) {
if (iDim < 0 || iDim > 2)
return std::string();
if (iDim == 2) {
typedef itk::ImageBase<3> ImageType;
ImageType::Pointer p_clImageBase = LoadImageBase(clDicomTags, strPath);
if (!p_clImageBase)
return std::string();
const ImageType::SizeType &clSize = p_clImageBase->GetLargestPossibleRegion().GetSize();
return std::to_string((long long)clSize[iDim]); // long long for VS 2010
}
// Calculate X and Y based on DICOM since some images could be inconsistent and share the same series UID
const char * const a_cSizeTags[2] = {
"0028|0011",
"0028|0010"
};
std::string strValue;
if (!itk::ExposeMetaData(clDicomTags, a_cSizeTags[iDim], strValue))
return std::string();
Trim(strValue);
return strValue;
}
std::string ComputeDiffusionBValue(const itk::MetaDataDictionary &clDicomTags) {
std::string strBValue;
if (itk::ExposeMetaData(clDicomTags, "0018|9087", strBValue)) {
Trim(strBValue);
return strBValue;
}
std::string strPatientName;
std::string strPatientId;
std::string strManufacturer;
itk::ExposeMetaData(clDicomTags, "0010|0010", strPatientName);
itk::ExposeMetaData(clDicomTags, "0010|0020", strPatientId);
if (strcasestr(strPatientName.c_str(), "prostatex") != nullptr || strcasestr(strPatientId.c_str(), "prostatex") != nullptr)
return ComputeDiffusionBValueProstateX(clDicomTags);
if (!itk::ExposeMetaData(clDicomTags, "0008|0070", strManufacturer)) {
std::cerr << "Error: Could not determine manufacturer." << std::endl;
return std::string();
}
if (strcasestr(strManufacturer.c_str(), "siemens") != nullptr)
return ComputeDiffusionBValueSiemens(clDicomTags);
else if (strcasestr(strManufacturer.c_str(), "ge") != nullptr)
return ComputeDiffusionBValueGE(clDicomTags);
else if (strcasestr(strManufacturer.c_str(), "philips") != nullptr)
return ComputeDiffusionBValuePhilips(clDicomTags);
return std::string();
}
std::string ComputeZCoordinate(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
typedef itk::ImageBase<3> ImageType;
std::string strImagePosition; // Try to grab this first before doing expensive stuff
if (!itk::ExposeMetaData(clDicomTags, "0020|0032", strImagePosition))
return std::string();
Trim(strImagePosition);
ImageType::Pointer p_clImageBase = LoadImageBase(clDicomTags, strPath);
if (!p_clImageBase)
return std::string();
ImageType::PointType clOrigin;
{
float a_fTmp[3] = { 0.0f, 0.0f, 0.0f };
if (sscanf(strImagePosition.c_str(), "%f\\%f\\%f", a_fTmp+0, a_fTmp+1, a_fTmp+2) != 3)
return std::string();
clOrigin[0] = itk::SpacePrecisionType(a_fTmp[0]);
clOrigin[1] = itk::SpacePrecisionType(a_fTmp[1]);
clOrigin[2] = itk::SpacePrecisionType(a_fTmp[2]);
}
// Now transform the physical origin to an index (fail if not in the volume)
ImageType::IndexType clIndex;
if (!p_clImageBase->TransformPhysicalPointToIndex(clOrigin, clIndex))
return std::string();
return std::to_string((long long)clIndex[2]);
}
std::string ComputeZOrigin(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
std::string strImagePosition; // Try to grab this first before doing expensive stuff
if (!itk::ExposeMetaData(clDicomTags, "0020|0032", strImagePosition))
return std::string();
float a_fTmp[3] = { 0.0f, 0.0f, 0.0f };
if (sscanf(strImagePosition.c_str(), "%f\\%f\\%f", a_fTmp+0, a_fTmp+1, a_fTmp+2) != 3)
return std::string();
return std::to_string(a_fTmp[2]);
}
std::string ComputeDiffusionBValueSiemens(const itk::MetaDataDictionary &clDicomTags) {
std::string strModel;
if (itk::ExposeMetaData(clDicomTags, "0008|1090", strModel)) {
if ((strcasestr(strModel.c_str(), "skyra") != nullptr || strcasestr(strModel.c_str(), "verio") != nullptr)) {
std::string strTmp = ComputeDiffusionBValueProstateX(clDicomTags);
if (strTmp.size() > 0)
return strTmp;
}
}
gdcm::CSAHeader clCSAHeader;
if (!GetCSAHeaderFromElement(clDicomTags, "0029|1010", clCSAHeader)) // Nothing to do
return std::string();
std::string strTmp;
if (ExposeCSAMetaData(clCSAHeader, "B_value", strTmp))
return strTmp;
return std::string();
}
std::string ComputeDiffusionBValueGE(const itk::MetaDataDictionary &clDicomTags) {
std::string strValue;
if (!itk::ExposeMetaData(clDicomTags, "0043|1039", strValue))
return std::string(); // Nothing to do
size_t p = strValue.find('\\');
if (p == std::string::npos)
return std::string(); // Not sure what to do
strValue.erase(p);
std::stringstream valueStream;
valueStream.str(strValue);
double dValue = 0.0;
if (!(valueStream >> dValue) || dValue < 0.0) // Bogus value
return std::string();
// Something is screwed up here ... let's try to remove the largest significant digit
if (dValue > 3000.0) {
p = strValue.find_first_not_of(" \t0");
strValue.erase(strValue.begin(), strValue.begin()+p+1);
valueStream.clear();
valueStream.str(strValue);
if (!(valueStream >> dValue) || dValue < 0.0 || dValue > 3000.0)
return std::string();
}
return std::to_string((long long)dValue);
}
std::string ComputeDiffusionBValueProstateX(const itk::MetaDataDictionary &clDicomTags) {
std::string strSequenceName;
if (!itk::ExposeMetaData(clDicomTags, "0018|0024", strSequenceName)) {
std::cerr << "Error: Could not extract sequence name (0018,0024)." << std::endl;
return std::string();
}
Trim(strSequenceName);
if (strSequenceName.empty()) {
std::cerr << "Error: Empty sequence name (0018,0024)." << std::endl;
return std::string();
}
std::stringstream valueStream;
unsigned int uiBValue = 0;
size_t i = 0, j = 0;
while (i < strSequenceName.size()) {
i = strSequenceName.find('b', i);
if (i == std::string::npos || ++i >= strSequenceName.size())
break;
j = strSequenceName.find_first_not_of("0123456789", i);
// Should end with a 't' or a '\0'
if (j == std::string::npos)
j = strSequenceName.size();
else if (strSequenceName[j] != 't')
break;
if (j > i) {
std::string strBValue = strSequenceName.substr(i, j-i);
valueStream.clear();
valueStream.str(strBValue);
uiBValue = 0;
if (valueStream >> uiBValue) {
if (uiBValue < 3000)
return strBValue;
else
std::cerr << "Error: B-value of " << uiBValue << " seems bogus. Continuing to parse." << std::endl;
}
}
i = j;
}
std::cerr << "Error: Could not parse sequence name '" << strSequenceName << "'." << std::endl;
return std::string();
}
std::string ComputeDiffusionBValuePhilips(const itk::MetaDataDictionary &clDicomTags) {
std::string strBValue;
if (!itk::ExposeMetaData(clDicomTags, "2001|1003", strBValue))
return std::string();
return strBValue;
}
bool IsHexDigit(char c) {
if (std::isdigit(c))
return true;
switch (std::tolower(c)) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
return true;
}
return false;
}
void ComputeVolumeNumberByTemporalPosition(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
typedef itk::GDCMImageIO ImageIOType;
typedef itk::GDCMSeriesFileNames NamesGeneratorType;
std::string strSeriesUID;
if (!itk::ExposeMetaData(clDicomTags, "0020|000e", strSeriesUID))
return; // Uhh?
if (g_mSeriesUIDToInstanceUIDVolumeNumberMap.find(strSeriesUID) != g_mSeriesUIDToInstanceUIDVolumeNumberMap.end())
return; // Already computed
auto &mSOPToVolumeNumber = g_mSeriesUIDToInstanceUIDVolumeNumberMap[strSeriesUID]; // Insert
ImageIOType::Pointer p_clImageIO = ImageIOType::New();
if (!p_clImageIO)
return;
NamesGeneratorType::Pointer p_clNamesGenerator = NamesGeneratorType::New();
if (!p_clNamesGenerator)
return;
// Collect all files in this series so we can verify their membership in the more specialized series
p_clNamesGenerator->SetUseSeriesDetails(false);
p_clNamesGenerator->SetDirectory(strPath);
std::unordered_set<std::string> sAllFiles;
std::vector<std::string> vAllFiles = p_clNamesGenerator->GetFileNames(strSeriesUID);
sAllFiles.insert(vAllFiles.begin(), vAllFiles.end());
if (sAllFiles.empty())
return; // What?
// Old data gets re-used... make a new one
p_clNamesGenerator = NamesGeneratorType::New();
if (!p_clNamesGenerator)
return;
p_clNamesGenerator->SetUseSeriesDetails(true);
p_clNamesGenerator->AddSeriesRestriction("0020|0100"); // Temporal position
p_clNamesGenerator->SetDirectory(strPath);
// These are fake versions of the series UID!
std::vector<std::string> vAllSeriesUIDs = p_clNamesGenerator->GetSeriesUIDs();
typedef std::map<int, std::vector<std::string>> MapType; // temporal position --> SOP instance UID
MapType mVolumeMap;
std::string strTemporalPosition;
std::string strSOPInstanceUID;
try {
for (const std::string &strFakeSeriesUID : vAllSeriesUIDs) {
vAllFiles = p_clNamesGenerator->GetFileNames(strFakeSeriesUID);
if (vAllFiles.empty() || sAllFiles.find(vAllFiles[0]) == sAllFiles.end())
continue;
p_clImageIO->SetFileName(vAllFiles[0]);
p_clImageIO->ReadImageInformation();
if (!itk::ExposeMetaData(p_clImageIO->GetMetaDataDictionary(), "0020|0100", strTemporalPosition))
return; // Should not happen!
Trim(strTemporalPosition);
char *p = nullptr;
const int iTemporalPosition = std::strtol(strTemporalPosition.c_str(), &p, 10);
if (*p != '\0')
return; // What?
auto &vSOPs = mVolumeMap[iTemporalPosition];
vSOPs.reserve(vAllFiles.size());
for (const std::string &strFileName : vAllFiles) {
p_clImageIO->SetFileName(strFileName);
p_clImageIO->ReadImageInformation();
if (!itk::ExposeMetaData(p_clImageIO->GetMetaDataDictionary(), "0008|0018", strSOPInstanceUID))
return;
Trim(strSOPInstanceUID);
vSOPs.emplace_back(strSOPInstanceUID);
}
}
}
catch (itk::ExceptionObject &) {
return;
}
unsigned int uiVolumeNumber = 1;
for (const auto &stPair : mVolumeMap) {
for (const std::string &strSOPInstanceUID : stPair.second)
mSOPToVolumeNumber.emplace(strSOPInstanceUID, uiVolumeNumber);
++uiVolumeNumber;
}
}
void ComputeVolumeNumberByAcquisitionTime(const itk::MetaDataDictionary &clDicomTags, const std::string &strPath) {
typedef itk::GDCMImageIO ImageIOType;
typedef itk::GDCMSeriesFileNames NamesGeneratorType;
std::string strSeriesUID;
if (!itk::ExposeMetaData(clDicomTags, "0020|000e", strSeriesUID))
return; // Uhh?
if (g_mSeriesUIDToInstanceUIDVolumeNumberMap.find(strSeriesUID) != g_mSeriesUIDToInstanceUIDVolumeNumberMap.end())
return; // Already computed
auto &mSOPToVolumeNumber = g_mSeriesUIDToInstanceUIDVolumeNumberMap[strSeriesUID]; // Insert
ImageIOType::Pointer p_clImageIO = ImageIOType::New();
if (!p_clImageIO)
return;
NamesGeneratorType::Pointer p_clNamesGenerator = NamesGeneratorType::New();
if (!p_clNamesGenerator)
return;
// Collect all files in this series so we can verify their membership in the more specialized series
p_clNamesGenerator->SetUseSeriesDetails(false);
p_clNamesGenerator->SetDirectory(strPath);
std::unordered_set<std::string> sAllFiles;
std::vector<std::string> vAllFiles = p_clNamesGenerator->GetFileNames(strSeriesUID);
sAllFiles.insert(vAllFiles.begin(), vAllFiles.end());
if (sAllFiles.empty())
return; // What?
// Old data gets re-used... make a new one
p_clNamesGenerator = NamesGeneratorType::New();
if (!p_clNamesGenerator)
return;
p_clNamesGenerator->SetUseSeriesDetails(true);
p_clNamesGenerator->AddSeriesRestriction("0008|0022"); // Acquisition date
p_clNamesGenerator->AddSeriesRestriction("0008|0032"); // Acquisition time
p_clNamesGenerator->SetDirectory(strPath);
// These are fake versions of the series UID!
std::vector<std::string> vAllSeriesUIDs = p_clNamesGenerator->GetSeriesUIDs();
typedef std::map<time_t, std::vector<std::string>> MapType; // time stamp --> SOP instance UID
MapType mVolumeMap;
std::string strAcquisitionDate;
std::string strAcquisitionTime;
std::string strSOPInstanceUID;
try {
for (const std::string &strFakeSeriesUID : vAllSeriesUIDs) {
vAllFiles = p_clNamesGenerator->GetFileNames(strFakeSeriesUID);
if (vAllFiles.empty() || sAllFiles.find(vAllFiles[0]) == sAllFiles.end())
continue;
p_clImageIO->SetFileName(vAllFiles[0]);