-
-
Notifications
You must be signed in to change notification settings - Fork 686
/
Copy pathitkGDCMImageIO.cxx
1598 lines (1457 loc) · 51.2 KB
/
itkGDCMImageIO.cxx
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
/*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
/*=========================================================================
*
* Portions of this file are subject to the VTK Toolkit Version 3 copyright.
*
* Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
*
* For complete copyright, license and disclaimer of warranty information
* please refer to the NOTICE file at the top of the ITK source tree.
*
*=========================================================================*/
#include "itkVersion.h"
#include "itkGDCMImageIO.h"
#include "itkIOCommon.h"
#include "itkArray.h"
#include "itkByteSwapper.h"
#include "vnl/vnl_cross.h"
#include "itkMetaDataObject.h"
#include "itksys/SystemTools.hxx"
#include "itksys/Base64.h"
#include "gdcmImageHelper.h"
#include "gdcmFileExplicitFilter.h"
#include "gdcmImageChangeTransferSyntax.h"
#include "gdcmImageChangePhotometricInterpretation.h"
#include "gdcmDataSetHelper.h"
#include "gdcmStringFilter.h"
#include "gdcmImageApplyLookupTable.h"
#include "gdcmImageChangePlanarConfiguration.h"
#include "gdcmRescaler.h"
#include "gdcmImageReader.h"
#include "gdcmImageWriter.h"
#include "gdcmUIDGenerator.h"
#include "gdcmAttribute.h"
#include "gdcmGlobal.h"
#include "gdcmMediaStorage.h"
#include <fstream>
#include <sstream>
namespace itk
{
class InternalHeader
{
public:
InternalHeader() = default;
~InternalHeader() { delete m_Header; }
gdcm::File * m_Header{ nullptr };
};
GDCMImageIO::GDCMImageIO()
{
this->m_DICOMHeader = new InternalHeader;
this->SetNumberOfDimensions(3); // needed for getting the 3 coordinates of
// the origin, even if it is a 2D slice.
m_ByteOrder = IOByteOrderEnum::LittleEndian; // default
m_FileType = IOFileEnum::Binary; // default...always true
m_RescaleSlope = 1.0;
m_RescaleIntercept = 0.0;
// UIDPrefix is the ITK root id tacked with a ".1"
// allowing to designate a subspace of the id space for ITK generated DICOM
m_UIDPrefix = "1.2.826.0.1.3680043.2.1125."
"1";
// Purely internal use, no user access:
m_StudyInstanceUID = "";
m_SeriesInstanceUID = "";
m_FrameOfReferenceInstanceUID = "";
m_KeepOriginalUID = false;
m_LoadPrivateTags = false;
m_ReadYBRtoRGB = true;
m_InternalComponentType = IOComponentEnum::UNKNOWNCOMPONENTTYPE;
// by default assume that images will be 2D.
// This number is updated according the information
// received through the MetaDataDictionary
m_GlobalNumberOfDimensions = 2;
// By default use JPEG2000. For legacy system, one should prefer JPEG since
// JPEG2000 was only recently added to the DICOM standard
this->Self::SetCompressor("");
const char * extensions[] = { ".dcm", ".DCM", ".dicom", ".DICOM" };
for (auto ext : extensions)
{
this->AddSupportedWriteExtension(ext);
this->AddSupportedReadExtension(ext);
}
}
GDCMImageIO::~GDCMImageIO()
{
delete this->m_DICOMHeader;
}
/**
* Helper function to test for some dicom like formatting.
* @param file A stream to test if the file is dicom like
* @return true if the structure of the file is dicom like
*/
static bool
readNoPreambleDicom(std::ifstream & file) // NOTE: This file is duplicated in itkDCMTKImageIO.cxx
{
// Adapted from https://stackoverflow.com/questions/2381983/c-how-to-read-parts-of-a-file-dicom
/* This heuristic tries to determine if the file follows the basic structure of a dicom file organization.
* Any file that begins with the a byte sequence
* where groupNo matches below will be then read several SOP Instance sections.
*/
unsigned short groupNo = 0xFFFF;
unsigned short tagElementNo = 0xFFFF;
do
{
file.read(reinterpret_cast<char *>(&groupNo), sizeof(unsigned short));
ByteSwapper<unsigned short>::SwapFromSystemToLittleEndian(&groupNo);
file.read(reinterpret_cast<char *>(&tagElementNo), sizeof(unsigned short));
ByteSwapper<unsigned short>::SwapFromSystemToLittleEndian(&tagElementNo);
if (groupNo != 0x0002 && groupNo != 0x0008) // Only groupNo 2 & 8 are supported without preambles
{
return false;
}
char vrcode[3] = { '\0', '\0', '\0' };
file.read(vrcode, 2);
long length = std::numeric_limits<long>::max();
const std::string vr{ vrcode };
if (vr == "AE" || vr == "AS" || vr == "AT" || vr == "CS" || vr == "DA" || vr == "DS" || vr == "DT" || vr == "FL" ||
vr == "FD" || vr == "IS" || vr == "LO" || vr == "PN" || vr == "SH" || vr == "SL" || vr == "SS" || vr == "ST" ||
vr == "TM" || vr == "UI" || vr == "UL" || vr == "US")
{
// Explicit VR (value representation stored in the file)
unsigned short uslength = 0;
file.read(reinterpret_cast<char *>(&uslength), sizeof(unsigned short));
ByteSwapper<unsigned short>::SwapFromSystemToLittleEndian(&uslength);
length = uslength;
}
else
{
// Implicit VR (value representation not stored in the file)
char lengthChars[4] = { vrcode[0], vrcode[1], '\0', '\0' };
file.read(lengthChars + 2, 2);
auto * uilength = reinterpret_cast<unsigned int *>(lengthChars);
ByteSwapper<unsigned int>::SwapFromSystemToLittleEndian(uilength);
length = (*uilength);
}
if (length <= 0)
{
return false;
}
file.ignore(length);
if (file.eof())
{
return false;
}
} while (groupNo == 2);
#if defined(NDEBUG)
std::ostringstream itkmsg;
itkmsg << "No DICOM magic number found, but the file appears to be DICOM without a preamble.\n"
<< "Proceeding without caution.";
::itk::OutputWindowDisplayDebugText(itkmsg.str().c_str());
#endif
return true;
}
static void
YCbCr_to_RGB(unsigned char * p, const size_t len)
{
for (size_t x = 0; x < len; x += 3)
{
const unsigned char in[] = { p[x], p[x + 1], p[x + 2] };
gdcm::ImageChangePhotometricInterpretation::YBR2RGB<unsigned char>(&p[x], in);
}
}
// This method will only test if the header looks like a
// GDCM image file.
bool
GDCMImageIO::CanReadFile(const char * filename)
{
std::ifstream file;
try
{
this->OpenFileForReading(file, filename);
}
catch (ExceptionObject &)
{
return false;
}
//
// sniff for the DICM signature first at 128
// then at zero, and if either place has it then
// ask GDCM to try reading it.
//
// There isn't a definitive way to check for DICOM files;
// This was actually cribbed from DICOMParser in VTK
bool dicomsig(false);
for (long int off = 128; off >= 0; off -= 128)
{
file.seekg(off, std::ios_base::beg);
if (file.fail() || file.eof())
{
return false;
}
char buf[5];
file.read(buf, 4);
if (file.fail())
{
return false;
}
buf[4] = '\0';
const std::string sig{ buf };
if (sig == "DICM")
{
dicomsig = true;
}
}
// Do not allow CanRead to return true for non-compliant DICOM files
#define GDCMPARSER_IGNORE_MAGIC_NUMBER
#if defined(GDCMPARSER_IGNORE_MAGIC_NUMBER) && !defined(__EMSCRIPTEN__)
//
// Try it anyways...
//
if (!dicomsig)
{
file.seekg(0, std::ios_base::beg);
dicomsig = readNoPreambleDicom(file);
}
#endif // GDCMPARSER_IGNORE_MAGIC_NUMBER
if (dicomsig)
{
// Check to see if its a valid dicom file gdcm is able to parse:
// We are parsing the header one time here:
gdcm::ImageReader reader;
reader.SetFileName(filename);
if (reader.Read())
{
return true;
}
}
return false;
}
void
GDCMImageIO::Read(void * pointer)
{
// ensure file can be opened for reading, before doing any more work
std::ifstream inputFileStream;
// let any exceptions propagate
this->OpenFileForReading(inputFileStream, m_FileName);
inputFileStream.close();
itkAssertInDebugAndIgnoreInReleaseMacro(gdcm::ImageHelper::GetForceRescaleInterceptSlope());
gdcm::ImageReader reader;
reader.SetFileName(m_FileName.c_str());
if (!reader.Read())
{
itkExceptionMacro(<< "Cannot read requested file");
}
gdcm::Image & image = reader.GetImage();
#ifndef NDEBUG
gdcm::PixelFormat pixeltype_debug = image.GetPixelFormat();
itkAssertInDebugAndIgnoreInReleaseMacro(image.GetNumberOfDimensions() == 2 || image.GetNumberOfDimensions() == 3);
#endif
SizeValueType len = image.GetBufferLength();
// Decompress the Pixel Data buffer when needed. This is required here in the
// pipeline to make sure to decompress JPEGBaseline1 into YBR_FULL.
if (image.GetTransferSyntax().IsEncapsulated())
{
gdcm::ImageChangeTransferSyntax icts;
icts.SetInput(image);
icts.SetTransferSyntax(gdcm::TransferSyntax::ImplicitVRLittleEndian);
if (!icts.Change())
{
itkExceptionMacro(<< "Failed to change to Implicit Transfer Syntax");
}
image = icts.GetOutput();
}
// I think ITK only allow RGB image by pixel (and not by plane)
if (image.GetPlanarConfiguration() == 1)
{
gdcm::ImageChangePlanarConfiguration icpc;
icpc.SetInput(image);
icpc.SetPlanarConfiguration(0);
if (!icpc.Change())
{
itkExceptionMacro(<< "Failed to change to Planar Configuration");
}
image = icpc.GetOutput();
}
gdcm::PhotometricInterpretation pi = image.GetPhotometricInterpretation();
if (pi == gdcm::PhotometricInterpretation::PALETTE_COLOR)
{
gdcm::ImageApplyLookupTable ialut;
ialut.SetInput(image);
ialut.Apply();
image = ialut.GetOutput();
len *= 3;
}
else if (pi == gdcm::PhotometricInterpretation::MONOCHROME1)
{
// ITK does not carry color space associated with an image. It is pretty
// much assumed that scalar image is expressed in MONOCHROME2 (aka min-is-black)
gdcm::ImageChangePhotometricInterpretation icpi;
icpi.SetInput(image);
icpi.SetPhotometricInterpretation(gdcm::PhotometricInterpretation::MONOCHROME2);
if (!icpi.Change())
{
itkExceptionMacro(<< "Failed to change to Photometric Interpretation");
}
itkWarningMacro(<< "Converting from MONOCHROME1 to MONOCHROME2 may impact the meaning of DICOM attributes related "
"to pixel values.");
image = icpi.GetOutput();
}
if (!image.GetBuffer((char *)pointer))
{
itkExceptionMacro(<< "Failed to get the buffer!");
}
const gdcm::PixelFormat & pixeltype = image.GetPixelFormat();
#ifndef NDEBUG
// ImageApplyLookupTable is meant to change the pixel type for PALETTE_COLOR images
// (from single values to triple values per pixel)
if (pi != gdcm::PhotometricInterpretation::PALETTE_COLOR)
{
itkAssertInDebugAndIgnoreInReleaseMacro(pixeltype_debug == pixeltype);
}
#endif
if (m_RescaleSlope != 1.0 || m_RescaleIntercept != 0.0)
{
gdcm::Rescaler r;
r.SetIntercept(m_RescaleIntercept);
r.SetSlope(m_RescaleSlope);
r.SetPixelFormat(pixeltype);
gdcm::PixelFormat outputpt = r.ComputeInterceptSlopePixelType();
auto * copy = new char[len];
memcpy(copy, (char *)pointer, len);
r.Rescale((char *)pointer, copy, len);
delete[] copy;
// WARNING: sizeof(Real World Value) != sizeof(Stored Pixel)
len = len * outputpt.GetPixelSize() / pixeltype.GetPixelSize();
}
// Y'CbCr to RGB
// GDCM 3.0.3
const bool ybr =
m_NumberOfComponents == 3 &&
(pi == gdcm::PhotometricInterpretation::YBR_FULL || pi == gdcm::PhotometricInterpretation::YBR_FULL_422) &&
(pixeltype == gdcm::PixelFormat::UINT8 || pixeltype == gdcm::PixelFormat::INT8);
if (ybr && m_ReadYBRtoRGB)
{
if (len % 3 != 0)
{
itkExceptionMacro(<< "Buffer size " << len << " is not valid");
}
YCbCr_to_RGB(reinterpret_cast<unsigned char *>(pointer), static_cast<size_t>(len));
}
#ifndef NDEBUG
// \postcondition
// Now that len was updated (after unpacker 12bits -> 16bits, rescale...) ,
// can now check compat:
const SizeValueType numberOfBytesToBeRead = static_cast<SizeValueType>(this->GetImageSizeInBytes());
itkAssertInDebugAndIgnoreInReleaseMacro(numberOfBytesToBeRead == len); // programmer error
#endif
}
void
GDCMImageIO::InternalReadImageInformation()
{
// ensure file can be opened for reading, before doing any more work
std::ifstream inputFileStream;
// let any exceptions propagate
this->OpenFileForReading(inputFileStream, m_FileName);
inputFileStream.close();
// In general this should be relatively safe to assume
gdcm::ImageHelper::SetForceRescaleInterceptSlope(true);
gdcm::ImageReader reader;
reader.SetFileName(m_FileName.c_str());
if (!reader.Read())
{
itkExceptionMacro(<< "Cannot read requested file");
}
const gdcm::Image & image = reader.GetImage();
const gdcm::File & f = reader.GetFile();
const gdcm::DataSet & ds = f.GetDataSet();
const unsigned int * dims = image.GetDimensions();
const gdcm::PixelFormat & pixeltype = image.GetPixelFormat();
switch (pixeltype)
{
case gdcm::PixelFormat::INT8:
m_InternalComponentType = IOComponentEnum::CHAR; // Is it signed char ?
break;
case gdcm::PixelFormat::UINT8:
m_InternalComponentType = IOComponentEnum::UCHAR;
break;
/* INT12 / UINT12 should not happen anymore in any modern DICOM */
case gdcm::PixelFormat::INT12:
m_InternalComponentType = IOComponentEnum::SHORT;
break;
case gdcm::PixelFormat::UINT12:
m_InternalComponentType = IOComponentEnum::USHORT;
break;
case gdcm::PixelFormat::INT16:
m_InternalComponentType = IOComponentEnum::SHORT;
break;
case gdcm::PixelFormat::UINT16:
m_InternalComponentType = IOComponentEnum::USHORT;
break;
// RT / SC have 32bits
case gdcm::PixelFormat::INT32:
m_InternalComponentType = IOComponentEnum::INT;
break;
case gdcm::PixelFormat::UINT32:
m_InternalComponentType = IOComponentEnum::UINT;
break;
// case gdcm::PixelFormat::FLOAT16: // TODO
case gdcm::PixelFormat::FLOAT32:
m_InternalComponentType = IOComponentEnum::FLOAT;
break;
case gdcm::PixelFormat::FLOAT64:
m_InternalComponentType = IOComponentEnum::DOUBLE;
break;
default:
itkExceptionMacro("Unhandled PixelFormat: " << pixeltype);
}
gdcm::PixelFormat::ScalarType outputpt = pixeltype.GetScalarType();
m_RescaleIntercept = image.GetIntercept();
m_RescaleSlope = image.GetSlope();
if (m_RescaleSlope != 1.0 || m_RescaleIntercept != 0.0)
{
gdcm::Rescaler r;
r.SetIntercept(m_RescaleIntercept);
r.SetSlope(m_RescaleSlope);
r.SetPixelFormat(pixeltype);
outputpt = r.ComputeInterceptSlopePixelType();
}
if (pixeltype > outputpt)
{
itkAssertInDebugOrThrowInReleaseMacro("Pixel type larger than output type")
}
m_ComponentType = IOComponentEnum::UNKNOWNCOMPONENTTYPE;
switch (outputpt)
{
case gdcm::PixelFormat::INT8:
m_ComponentType = IOComponentEnum::CHAR; // Is it signed char ?
break;
case gdcm::PixelFormat::UINT8:
m_ComponentType = IOComponentEnum::UCHAR;
break;
/* INT12 / UINT12 should not happen anymore in any modern DICOM */
case gdcm::PixelFormat::INT12:
m_ComponentType = IOComponentEnum::SHORT;
break;
case gdcm::PixelFormat::UINT12:
m_ComponentType = IOComponentEnum::USHORT;
break;
case gdcm::PixelFormat::INT16:
m_ComponentType = IOComponentEnum::SHORT;
break;
case gdcm::PixelFormat::UINT16:
m_ComponentType = IOComponentEnum::USHORT;
break;
// RT / SC have 32bits
case gdcm::PixelFormat::INT32:
m_ComponentType = IOComponentEnum::INT;
break;
case gdcm::PixelFormat::UINT32:
m_ComponentType = IOComponentEnum::UINT;
break;
// case gdcm::PixelFormat::FLOAT16: // TODO
case gdcm::PixelFormat::FLOAT32:
m_ComponentType = IOComponentEnum::FLOAT;
break;
case gdcm::PixelFormat::FLOAT64:
m_ComponentType = IOComponentEnum::DOUBLE;
break;
default:
itkExceptionMacro("Unhandled PixelFormat: " << outputpt);
}
m_NumberOfComponents = pixeltype.GetSamplesPerPixel();
const gdcm::PhotometricInterpretation & pi = image.GetPhotometricInterpretation();
if (pi == gdcm::PhotometricInterpretation::PALETTE_COLOR)
{
// PALETTE_COLOR is always expanded in RGB image
itkAssertInDebugAndIgnoreInReleaseMacro(m_NumberOfComponents == 1);
m_NumberOfComponents = 3;
}
if (m_NumberOfComponents == 1)
{
this->SetPixelType(IOPixelEnum::SCALAR);
}
else if (m_NumberOfComponents == 3)
{
// GDCM 3.0.3
const bool rgb_from_ybr =
m_ReadYBRtoRGB &&
(pi == gdcm::PhotometricInterpretation::YBR_FULL || pi == gdcm::PhotometricInterpretation::YBR_FULL_422) &&
(outputpt == gdcm::PixelFormat::UINT8 || outputpt == gdcm::PixelFormat::INT8);
const bool ybr_jp2 =
pi == gdcm::PhotometricInterpretation::YBR_ICT || pi == gdcm::PhotometricInterpretation::YBR_RCT;
const bool rgb = pi == gdcm::PhotometricInterpretation::RGB ||
pi == gdcm::PhotometricInterpretation::PALETTE_COLOR || rgb_from_ybr || ybr_jp2;
if (rgb)
{
this->SetPixelType(IOPixelEnum::RGB);
}
else
{
this->SetPixelType(IOPixelEnum::VECTOR);
}
}
else
{
this->SetPixelType(IOPixelEnum::VECTOR);
}
m_Dimensions[0] = dims[0];
m_Dimensions[1] = dims[1];
double spacing[3];
// FIXME
//
// This is a WORKAROUND for a bug in GDCM -- in
// ImageHeplper::GetSpacingTagFromMediaStorage it was not
// handling some MediaStorage types
// so we have to punt here.
gdcm::MediaStorage ms;
ms.SetFromFile(f);
switch (ms)
{
case gdcm::MediaStorage::HardcopyGrayscaleImageStorage:
case gdcm::MediaStorage::GEPrivate3DModelStorage:
case gdcm::MediaStorage::Philips3D:
case gdcm::MediaStorage::VideoEndoscopicImageStorage:
case gdcm::MediaStorage::UltrasoundMultiFrameImageStorage:
case gdcm::MediaStorage::UltrasoundImageStorage: // ??
case gdcm::MediaStorage::UltrasoundImageStorageRetired:
case gdcm::MediaStorage::UltrasoundMultiFrameImageStorageRetired:
{
std::vector<double> sp;
gdcm::Tag spacingTag(0x0028, 0x0030);
if (ds.FindDataElement(spacingTag) && !ds.GetDataElement(spacingTag).IsEmpty())
{
gdcm::DataElement de = ds.GetDataElement(spacingTag);
std::stringstream m_Ss;
gdcm::Element<gdcm::VR::DS, gdcm::VM::VM1_n> m_El;
const gdcm::ByteValue * bv = de.GetByteValue();
assert(bv);
std::string s = std::string(bv->GetPointer(), bv->GetLength());
m_Ss.str(s);
// Erroneous file CT-MONO2-8-abdo.dcm,
// The spacing is something like that [0.2\0\0.200000],
// TODO throw an exception that VM is not compatible.
m_El.SetLength(16);
m_El.Read(m_Ss);
assert(m_El.GetLength() == 2);
for (unsigned long i = 0; i < m_El.GetLength(); ++i)
sp.push_back(m_El.GetValue(i));
std::swap(sp[0], sp[1]);
assert(sp.size() == 2);
spacing[0] = sp[0];
spacing[1] = sp[1];
}
else
{
spacing[0] = 1.0;
spacing[1] = 1.0;
}
spacing[2] = 1.0; // punt?
}
break;
default:
{
const double * sp;
sp = image.GetSpacing();
spacing[0] = sp[0];
spacing[1] = sp[1];
spacing[2] = sp[2];
}
break;
}
const double * origin = image.GetOrigin();
for (unsigned i = 0; i < 3; ++i)
{
m_Spacing[i] = spacing[i];
m_Origin[i] = origin[i];
}
if (image.GetNumberOfDimensions() == 3)
{
m_Dimensions[2] = dims[2];
}
else
{
m_Dimensions[2] = 1;
}
const double * dircos = image.GetDirectionCosines();
vnl_vector<double> rowDirection(3), columnDirection(3);
rowDirection[0] = dircos[0];
rowDirection[1] = dircos[1];
rowDirection[2] = dircos[2];
columnDirection[0] = dircos[3];
columnDirection[1] = dircos[4];
columnDirection[2] = dircos[5];
vnl_vector<double> sliceDirection = vnl_cross_3d(rowDirection, columnDirection);
// orthogonalize
sliceDirection.normalize();
rowDirection = vnl_cross_3d(columnDirection, sliceDirection).normalize();
columnDirection = vnl_cross_3d(sliceDirection, rowDirection);
this->SetDirection(0, rowDirection);
this->SetDirection(1, columnDirection);
this->SetDirection(2, sliceDirection);
// Now copying the gdcm dictionary to the itk dictionary:
MetaDataDictionary & dico = this->GetMetaDataDictionary();
// in the case of re-use by ImageSeriesReader, clear the dictionary
// before populating it.
dico.Clear();
gdcm::StringFilter sf;
sf.SetFile(f);
auto it = ds.Begin();
// Copy of the header->content
for (; it != ds.End(); ++it)
{
const gdcm::DataElement & ref = *it;
const gdcm::Tag & tag = ref.GetTag();
// Compute VR from the toplevel file, and the currently processed dataset:
gdcm::VR vr = gdcm::DataSetHelper::ComputeVR(f, ds, tag);
// Process binary field and encode them as mime64: only when we do not know
// of any better
// representation. VR::US is binary, but user want ASCII representation.
if (vr & (gdcm::VR::OB | gdcm::VR::OF | gdcm::VR::OW | gdcm::VR::SQ | gdcm::VR::UN))
{
// itkAssertInDebugAndIgnoreInReleaseMacro( vr & gdcm::VR::VRBINARY );
/*
* Old behavior was to skip SQ, Pixel Data element. I decided that it is not safe to mime64
* VR::UN element. There used to be a bug in gdcm 1.2.0 and VR:UN element.
*/
if ((m_LoadPrivateTags || tag.IsPublic()) && vr != gdcm::VR::SQ &&
tag != gdcm::Tag(0x7fe0, 0x0010) /* && vr != gdcm::VR::UN*/)
{
const gdcm::ByteValue * bv = ref.GetByteValue();
if (bv)
{
// base64 streams have to be a multiple of 4 bytes in length
int encodedLengthEstimate = 2 * bv->GetLength();
encodedLengthEstimate = ((encodedLengthEstimate / 4) + 1) * 4;
auto * bin = new char[encodedLengthEstimate];
auto encodedLengthActual =
static_cast<unsigned int>(itksysBase64_Encode((const unsigned char *)bv->GetPointer(),
static_cast<SizeValueType>(bv->GetLength()),
(unsigned char *)bin,
static_cast<int>(0)));
std::string encodedValue(bin, encodedLengthActual);
EncapsulateMetaData<std::string>(dico, tag.PrintAsPipeSeparatedString(), encodedValue);
delete[] bin;
}
}
}
else /* if ( vr & gdcm::VR::VRASCII ) */
{
// Only copying field from the public DICOM dictionary
if (m_LoadPrivateTags || tag.IsPublic())
{
EncapsulateMetaData<std::string>(dico, tag.PrintAsPipeSeparatedString(), sf.ToString(tag));
}
}
}
#if defined(ITKIO_DEPRECATED_GDCM1_API)
// Now is a good time to fill in the class member:
char name[512];
this->GetPatientName(name, 512);
this->GetPatientID(name, 512);
this->GetPatientSex(name, 512);
this->GetPatientAge(name, 512);
this->GetStudyID(name, 512);
this->GetPatientDOB(name, 512);
this->GetStudyDescription(name, 512);
this->GetBodyPart(name, 512);
this->GetNumberOfSeriesInStudy(name, 512);
this->GetNumberOfStudyRelatedSeries(name, 512);
this->GetStudyDate(name, 512);
this->GetModality(name, 512);
this->GetManufacturer(name, 512);
this->GetInstitution(name, 512);
this->GetModel(name, 512);
this->GetScanOptions(name, 512);
#endif
}
void
GDCMImageIO::ReadImageInformation()
{
this->InternalReadImageInformation();
}
bool
GDCMImageIO::CanWriteFile(const char * name)
{
std::string filename = name;
if (filename.empty())
{
itkDebugMacro(<< "No filename specified.");
return false;
}
return this->HasSupportedWriteExtension(name, false);
}
void
GDCMImageIO::WriteImageInformation()
{}
void
GDCMImageIO::Write(const void * buffer)
{
// ensure file can be opened for writing, before doing any more work
std::ofstream outputFileStream;
// let any exceptions propagate
this->OpenFileForWriting(outputFileStream, m_FileName);
outputFileStream.close();
// global static:
gdcm::UIDGenerator::SetRoot(m_UIDPrefix.c_str());
// echo "ITK" | od -b
gdcm::FileMetaInformation::AppendImplementationClassUID("111.124.113");
const std::string project_name = std::string("GDCM/ITK ") + itk::Version::GetITKVersion();
gdcm::FileMetaInformation::SetSourceApplicationEntityTitle(project_name.c_str());
gdcm::ImageWriter writer;
gdcm::FileMetaInformation & fmi = writer.GetFile().GetHeader();
gdcm::DataSet & header = writer.GetFile().GetDataSet();
gdcm::Global & g = gdcm::Global::GetInstance();
const gdcm::Dicts & dicts = g.GetDicts();
const gdcm::Dict & pubdict = dicts.GetPublicDict();
MetaDataDictionary & dict = this->GetMetaDataDictionary();
gdcm::Tag tag;
itk::MetaDataDictionary::ConstIterator itr = dict.Begin();
const itk::MetaDataDictionary::ConstIterator end = dict.End();
gdcm::StringFilter sf;
sf.SetFile(writer.GetFile());
while (itr != end)
{
std::string value;
const std::string & key = itr->first; // Needed for bcc32
ExposeMetaData<std::string>(dict, key, value);
// Convert DICOM name to DICOM (group,element)
bool b = tag.ReadFromPipeSeparatedString(key.c_str());
// Anything that has been changed in the MetaData Dict will be pushed
// into the DICOM header:
if (b /*tag != gdcm::Tag(0xffff,0xffff)*/ /*dictEntry*/)
{
const gdcm::DictEntry & dictEntry = pubdict.GetDictEntry(tag);
gdcm::VR::VRType vrtype = dictEntry.GetVR();
if (dictEntry.GetVR() == gdcm::VR::SQ)
{
// How did we reach here ?
}
else if (vrtype & (gdcm::VR::OB | gdcm::VR::OF | gdcm::VR::OW /*|
gdcm::VR::SQ*/
| gdcm::VR::UN))
{
// Custom VR::VRBINARY
// convert value from Base64
auto * bin = new uint8_t[value.size()];
auto decodedLengthActual =
static_cast<unsigned int>(itksysBase64_Decode((const unsigned char *)value.c_str(),
static_cast<SizeValueType>(0),
(unsigned char *)bin,
static_cast<SizeValueType>(value.size())));
if (/*tag.GetGroup() != 0 ||*/ tag.GetElement() != 0) // ?
{
gdcm::DataElement de(tag);
de.SetByteValue((char *)bin, decodedLengthActual);
de.SetVR(dictEntry.GetVR());
if (tag.GetGroup() == 0x2)
{
fmi.Insert(de);
}
else
{
header.Insert(de);
}
}
delete[] bin;
}
else // VRASCII
{
// TODO, should we keep:
// (0028,0106) US/SS 0 #2, 1
// SmallestImagePixelValue
// (0028,0107) US/SS 4095 #2, 1
// LargestImagePixelValue
if (!tag.IsGroupLength()) // Get rid of group length, they are not
// useful
{
gdcm::DataElement de(tag);
if (dictEntry.GetVR().IsVRFile())
{
de.SetVR(dictEntry.GetVR());
}
#if GDCM_MAJOR_VERSION == 2 && GDCM_MINOR_VERSION == 0 && GDCM_BUILD_VERSION <= 12
// This will not work in the vast majority of cases but to get at
// least something working in GDCM 2.0.12
de.SetByteValue(value.c_str(), static_cast<uint32_t>(value.size()));
#else
// Even padding string with space. If string is not even, SetByteValue() will
// pad it with '\0' which is not what is expected except for VR::UI
// (see standard section 6.2).
if (vrtype & (gdcm::VR::UI))
{
const std::string si = sf.FromString(tag, value.c_str(), value.size());
de.SetByteValue(si.c_str(), static_cast<uint32_t>(si.size()));
}
else
{
const gdcm::String<> si = sf.FromString(tag, value.c_str(), value.size());
de.SetByteValue(si.c_str(), static_cast<uint32_t>(si.size()));
}
#endif
if (tag.GetGroup() == 0x2)
{
fmi.Insert(de);
}
else
{
header.Insert(de); // value, tag.GetGroup(), tag.GetElement());
}
}
}
}
else
{
// This is not a DICOM entry, then check if it is one of the
// ITK standard ones
if (key == ITK_NumberOfDimensions)
{
unsigned int numberOfDimensions = 0;
ExposeMetaData<unsigned int>(dict, key, numberOfDimensions);
m_GlobalNumberOfDimensions = numberOfDimensions;
m_Origin.resize(m_GlobalNumberOfDimensions);
m_Spacing.resize(m_GlobalNumberOfDimensions);
m_Direction.resize(m_GlobalNumberOfDimensions);
for (unsigned int i = 0; i < m_GlobalNumberOfDimensions; i++)
{
m_Direction[i].resize(m_GlobalNumberOfDimensions);
}
}
else if (key == ITK_Origin)
{
using DoubleArrayType = Array<double>;
DoubleArrayType originArray(3);
ExposeMetaData<DoubleArrayType>(dict, key, originArray);
m_Origin.resize(3);
m_Origin[0] = originArray[0];
m_Origin[1] = originArray[1];
m_Origin[2] = originArray[2];
}
else if (key == ITK_Spacing)
{
using DoubleArrayType = Array<double>;
DoubleArrayType spacingArray(3);
ExposeMetaData<DoubleArrayType>(dict, key, spacingArray);
m_Spacing.resize(3);
m_Spacing[0] = spacingArray[0];
m_Spacing[1] = spacingArray[1];
m_Spacing[2] = spacingArray[2];
}
else if (key == ITK_ZDirection)
{
using DoubleMatrixType = Matrix<double>;
DoubleMatrixType directionMatrix;
ExposeMetaData<DoubleMatrixType>(dict, key, directionMatrix);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
m_Direction[i][j] = directionMatrix[i][j];
}
}
}
else
{
itkDebugMacro(<< "GDCMImageIO: non-DICOM and non-ITK standard key = " << key);
}
}
++itr;
}
gdcm::SmartPointer<gdcm::Image> simage = new gdcm::Image;
gdcm::Image & image = *simage;
image.SetNumberOfDimensions(2); // good default
image.SetDimension(0, static_cast<unsigned int>(m_Dimensions[0]));
image.SetDimension(1, static_cast<unsigned int>(m_Dimensions[1]));
// image.SetDimension(2, m_Dimensions[2] );
image.SetSpacing(0, m_Spacing[0]);
image.SetSpacing(1, m_Spacing[1]);
if (m_Spacing.size() > 2)
{
image.SetSpacing(2, m_Spacing[2]);
}
// Set the origin (image position patient)
// If the meta dictionary contains the tag "0020 0032", use it
std::string tempString;
const bool hasIPP = ExposeMetaData<std::string>(dict, "0020|0032", tempString);
if (hasIPP)
{
double origin3D[3];
sscanf(tempString.c_str(), "%lf\\%lf\\%lf", &(origin3D[0]), &(origin3D[1]), &(origin3D[2]));
image.SetOrigin(0, origin3D[0]);
image.SetOrigin(1, origin3D[1]);
image.SetOrigin(2, origin3D[2]);
}
else
{
image.SetOrigin(0, m_Origin[0]);
image.SetOrigin(1, m_Origin[1]);
if (m_Origin.size() == 3)
{
image.SetOrigin(2, m_Origin[2]);
}
else
{
image.SetOrigin(2, 0);
}
}
if (m_NumberOfDimensions > 2 && m_Dimensions[2] != 1)
{
// resize num of dim to 3:
image.SetNumberOfDimensions(3);
image.SetDimension(2, static_cast<unsigned int>(m_Dimensions[2]));