1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/10/18 12:58:28 $
7 Version: $Revision: 1.277 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
20 // -------------- Remember ! ----------------------------------
22 // Image Position Patient (0020,0032):
23 // If not found (ACR_NEMA) we try Image Position (0020,0030)
24 // If not found (ACR-NEMA), we consider Slice Location (0020,1041)
25 // or Location (0020,0050)
26 // as the Z coordinate,
27 // 0. for all the coordinates if nothing is found
29 // Image Position (Patient) (0020,0032) VM=3 What is it used for?
31 // The attribute Patient Orientation (0020,0020) from the General Image Module
32 // is of type 2C and has the condition Required if image does not require
33 // Image Orientation (0020,0037) and Image Position (0020,0032).
34 // However, if the image does require the attributes
35 // - Image Orientation (Patient) (0020,0037), VM=6
36 // - Image Position Patient (0020,0032), VM=3
37 // then attribute Patient Orientation (0020,0020) should not be present
41 // Patient Position (0018,5100) values :
43 // HFS = Head First-Supine, where increasing (positive axis direction) :
44 // X -> to the direction pointed to by the patient's oustretched left arm
45 // Y -> to the anterior-to-posterior direction in the patient's body
46 // Z -> to the feet-to-head direction in the patient's body
48 // HFP = Head First-Prone, where increasing (positive axis direction) :
49 // X -> to the direction pointed to by the patient's oustretched left arm
50 // Y -> to the anterior-to-posterior direction in the patient's body
51 // Z -> to the feet-to-head direction in the patient's body
53 // FFS = Feet First-Supine, where increasing (positive axis direction) :
54 // X -> to the direction pointed to by the patient's oustretched left arm
55 // Y -> to the anterior-to-posterion direction in the patient's body
56 // Z -> to the feet-to-head direction in the patient's body
58 // FFP = Feet First-Prone, where increasing (positive axis direction) :
59 // X -> to the direction pointed to by the patient's oustretched left arm
60 // Y -> to the posterior-to-anterior direction in the patient's body
61 // Z -> to the feet-to-head direction in the patient's body
63 // HFDR = Head First-Decubitus Right
64 // HFDL = Head First-Decubitus Left
65 // FFDR = Feet First-Decubitus Right
66 // FFDL = Feet First-Decubitus Left
73 // CS 2 Patient Orientation (0020 0020)
74 // When the coordinates of the image
75 // are always present, this field is almost never used.
76 // Better we don't trust it too much ...
85 // (0020|0037) [Image Orientation (Patient)] [1\0\0\0\1\0 ]
88 // ---------------------------------------------------------------
91 #include "gdcmGlobal.h"
93 #include "gdcmDebug.h"
95 #include "gdcmSeqEntry.h"
96 #include "gdcmRLEFramesInfo.h"
97 #include "gdcmJPEGFragmentsInfo.h"
98 #include "gdcmDataEntry.h"
101 #include <stdio.h> //sscanf
102 #include <stdlib.h> // for atoi
107 //-----------------------------------------------------------------------------
108 // Constructor / Destructor
111 * \brief Constructor used when we want to generate dicom files from scratch
116 RLEInfo = new RLEFramesInfo;
117 JPEGInfo = new JPEGFragmentsInfo;
118 GrPixel = 0x7fe0; // to avoid further troubles
120 BasicOffsetTableItemValue = 0;
125 * \brief Canonical destructor.
133 delete[] BasicOffsetTableItemValue;
136 //-----------------------------------------------------------------------------
140 * @return false if file cannot be open or no swap info was found,
141 * or no tag was found.
145 if ( ! this->Document::Load( ) )
148 return DoTheLoadingJob( );
152 * \brief Does the Loading Job (internal use only)
153 * @return false if file cannot be open or no swap info was found,
154 * or no tag was found.
156 bool File::DoTheLoadingJob( )
159 // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
160 // We may encounter the 'RETired' (0x0028, 0x0200) tag
161 // (Image Location") . This entry contains the number of
162 // the group that contains the pixel data (hence the "Pixel Data"
163 // is found by indirection through the "Image Location").
164 // Inside the group pointed by "Image Location" the searched element
165 // is conventionally the element 0x0010 (when the norm is respected).
166 // When the "Image Location" is missing we default to group 0x7fe0.
167 // Note: this IS the right place for the code
170 const std::string &imgLocation = GetEntryString(0x0028, 0x0200);
171 if ( imgLocation == GDCM_UNFOUND )
178 GrPixel = (uint16_t) atoi( imgLocation.c_str() );
181 // sometimes Image Location value doesn't follow
182 // the supposed processor endianness.
183 // see gdcmData/cr172241.dcm
184 if ( GrPixel == 0xe07f )
189 if ( GrPixel != 0x7fe0 )
191 // This is a kludge for old dirty Philips imager.
199 // Now, we know GrPixel and NumPixel.
200 // Let's create a VirtualDictEntry to allow a further VR modification
201 // and force VR to match with BitsAllocated.
202 DocEntry *entry = GetDocEntry(GrPixel, NumPixel);
205 // Compute the RLE or JPEG info
207 const std::string &ts = GetTransferSyntax();
208 Fp->seekg( entry->GetOffset(), std::ios::beg );
209 if ( Global::GetTS()->IsRLELossless(ts) )
211 else if ( Global::GetTS()->IsJPEG(ts) )
212 ComputeJPEGFragmentInfo();
215 // Create a new DataEntry to change the DictEntry
216 // The changed DictEntry will have
217 // - a correct PixelVR OB or OW)
218 // - the name to "Pixel Data"
219 DataEntry *oldEntry = dynamic_cast<DataEntry *>(entry);
223 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
224 // more than 8 (i.e 12, 16) is a 'O Words'
225 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
230 // Change only made if usefull
231 if ( PixelVR != oldEntry->GetVR() )
233 DictEntry* newDict = NewVirtualDictEntry(GrPixel,NumPixel,
234 PixelVR,"1","Pixel Data");
236 DataEntry *newEntry = new DataEntry(newDict);
237 newEntry->Copy(entry);
238 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
239 oldEntry->SetSelfArea(false);
241 RemoveEntry(oldEntry);
249 * \brief This predicate, based on hopefully reasonable heuristics,
250 * decides whether or not the current File was properly parsed
251 * and contains the mandatory information for being considered as
252 * a well formed and usable Dicom/Acr File.
253 * @return true when File is the one of a reasonable Dicom/Acr file,
256 bool File::IsReadable()
258 if ( !Document::IsReadable() )
263 const std::string &res = GetEntryString(0x0028, 0x0005);
264 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
266 gdcmWarningMacro("Wrong Image Dimensions" << res);
267 return false; // Image Dimensions
269 bool b0028_0100 = true;
270 if ( !GetDocEntry(0x0028, 0x0100) )
272 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
273 //return false; // "Bits Allocated"
276 bool b0028_0101 = true;
277 if ( !GetDocEntry(0x0028, 0x0101) )
279 gdcmWarningMacro("Bits Stored (0028|0101) not found");
280 //return false; // "Bits Stored"
283 bool b0028_0102 = true;
284 if ( !GetDocEntry(0x0028, 0x0102) )
286 gdcmWarningMacro("Hight Bit (0028|0102) not found");
287 //return false; // "High Bit"
290 bool b0028_0103 = true;
291 if ( !GetDocEntry(0x0028, 0x0103) )
293 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
294 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
298 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
300 gdcmWarningMacro("Too much mandatory Tags missing !");
304 if ( !GetDocEntry(GrPixel, NumPixel) )
306 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
307 GrPixel << "|" << NumPixel << "not found");
308 return false; // Pixel Dicom Element not found :-(
314 * \brief gets the info from 0020,0013 : Image Number else 0.
315 * @return image number
317 int File::GetImageNumber()
319 //0020 0013 : Image Number
320 std::string strImNumber = GetEntryString(0x0020,0x0013);
321 if ( strImNumber != GDCM_UNFOUND )
323 return atoi( strImNumber.c_str() );
329 * \brief gets the info from 0008,0060 : Modality
330 * @return Modality Type
332 ModalityType File::GetModality()
334 // 0008 0060 : Modality
335 std::string strModality = GetEntryString(0x0008,0x0060);
336 if ( strModality != GDCM_UNFOUND )
338 if ( strModality.find("AU") < strModality.length()) return AU;
339 else if ( strModality.find("AS") < strModality.length()) return AS;
340 else if ( strModality.find("BI") < strModality.length()) return BI;
341 else if ( strModality.find("CF") < strModality.length()) return CF;
342 else if ( strModality.find("CP") < strModality.length()) return CP;
343 else if ( strModality.find("CR") < strModality.length()) return CR;
344 else if ( strModality.find("CT") < strModality.length()) return CT;
345 else if ( strModality.find("CS") < strModality.length()) return CS;
346 else if ( strModality.find("DD") < strModality.length()) return DD;
347 else if ( strModality.find("DF") < strModality.length()) return DF;
348 else if ( strModality.find("DG") < strModality.length()) return DG;
349 else if ( strModality.find("DM") < strModality.length()) return DM;
350 else if ( strModality.find("DS") < strModality.length()) return DS;
351 else if ( strModality.find("DX") < strModality.length()) return DX;
352 else if ( strModality.find("ECG") < strModality.length()) return ECG;
353 else if ( strModality.find("EPS") < strModality.length()) return EPS;
354 else if ( strModality.find("FA") < strModality.length()) return FA;
355 else if ( strModality.find("FS") < strModality.length()) return FS;
356 else if ( strModality.find("HC") < strModality.length()) return HC;
357 else if ( strModality.find("HD") < strModality.length()) return HD;
358 else if ( strModality.find("LP") < strModality.length()) return LP;
359 else if ( strModality.find("LS") < strModality.length()) return LS;
360 else if ( strModality.find("MA") < strModality.length()) return MA;
361 else if ( strModality.find("MR") < strModality.length()) return MR;
362 else if ( strModality.find("NM") < strModality.length()) return NM;
363 else if ( strModality.find("OT") < strModality.length()) return OT;
364 else if ( strModality.find("PT") < strModality.length()) return PT;
365 else if ( strModality.find("RF") < strModality.length()) return RF;
366 else if ( strModality.find("RG") < strModality.length()) return RG;
367 else if ( strModality.find("RTDOSE")
368 < strModality.length()) return RTDOSE;
369 else if ( strModality.find("RTIMAGE")
370 < strModality.length()) return RTIMAGE;
371 else if ( strModality.find("RTPLAN")
372 < strModality.length()) return RTPLAN;
373 else if ( strModality.find("RTSTRUCT")
374 < strModality.length()) return RTSTRUCT;
375 else if ( strModality.find("SM") < strModality.length()) return SM;
376 else if ( strModality.find("ST") < strModality.length()) return ST;
377 else if ( strModality.find("TG") < strModality.length()) return TG;
378 else if ( strModality.find("US") < strModality.length()) return US;
379 else if ( strModality.find("VF") < strModality.length()) return VF;
380 else if ( strModality.find("XA") < strModality.length()) return XA;
381 else if ( strModality.find("XC") < strModality.length()) return XC;
385 /// \todo throw error return value ???
386 /// specified <> unknown in our database
394 * \brief Retrieve the number of columns of image.
395 * @return The encountered size when found, 0 by default.
396 * 0 means the file is NOT USABLE. The caller will have to check
400 DataEntry *entry = GetDataEntry(0x0028,0x0011);
402 return (int)entry->GetValue(0);
407 * \brief Retrieve the number of lines of image.
408 * \warning The defaulted value is 1 as opposed to File::GetXSize()
409 * @return The encountered size when found, 1 by default
410 * (The ACR-NEMA file contains a Signal, not an Image).
414 DataEntry *entry = GetDataEntry(0x0028,0x0010);
416 return (int)entry->GetValue(0);
423 // The Rows (0028,0010) entry was optional for ACR/NEMA.
424 // (at least some images didn't have it.)
425 // It might hence be a signal (1D image). So we default to 1:
430 * \brief Retrieve the number of planes of volume or the number
431 * of frames of a multiframe.
432 * \warning When present we consider the "Number of Frames" as the third
433 * dimension. When missing we consider the third dimension as
434 * being the ACR-NEMA "Planes" tag content.
435 * @return The encountered size when found, 1 by default (single image).
439 // Both DicomV3 and ACR/Nema consider the "Number of Frames"
440 // as the third dimension.
441 DataEntry *entry = GetDataEntry(0x0028,0x0008);
443 return (int)entry->GetValue(0);
445 // We then consider the "Planes" entry as the third dimension
446 entry = GetDataEntry(0x0028,0x0012);
448 return (int)entry->GetValue(0);
453 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
454 * then 0028,0030 : Pixel Spacing
456 * @return X dimension of a pixel
458 float File::GetXSpacing()
460 float xspacing = 1.0;
463 // To follow David Clunie's advice, we first check ImagerPixelSpacing
465 DataEntry *entry = GetDataEntry(0x0018,0x1164);
468 nbValue = entry->GetValueCount();
470 xspacing = (float)entry->GetValue(2);
472 xspacing = (float)entry->GetValue(1);
474 xspacing = (float)entry->GetValue(0);
476 if ( xspacing == 0.0 )
482 gdcmWarningMacro( "Unfound Pixel Spacing (0018,1164)" );
485 /* const std::string &strImagerPixelSpacing = GetEntryString(0x0018,0x1164);
486 if ( strImagerPixelSpacing != GDCM_UNFOUND )
488 if ( ( nbValues = sscanf( strImagerPixelSpacing.c_str(),
489 "%f\\%f", &yspacing, &xspacing)) != 2 )
491 // if no values, xspacing is set to 1.0
494 // if single value is found, xspacing is defaulted to yspacing
498 if ( xspacing == 0.0 )
504 entry = GetDataEntry(0x0028,0x0030);
507 nbValue = entry->GetValueCount();
509 xspacing = (float)entry->GetValue(2);
511 xspacing = (float)entry->GetValue(1);
513 xspacing = (float)entry->GetValue(0);
515 if ( xspacing == 0.0 )
521 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
524 /* const std::string &strSpacing = GetEntryString(0x0028,0x0030);
525 if ( strSpacing == GDCM_UNFOUND )
527 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
531 if ( ( nbValues = sscanf( strSpacing.c_str(),
532 "%f \\%f ", &yspacing, &xspacing)) != 2 )
534 // if no values, xspacing is set to 1.0
537 // if single value is found, xspacing is defaulted to yspacing
541 if ( xspacing == 0.0 )
547 // to avoid troubles with David Clunie's-like images (at least one)
548 /* if ( xspacing == 0.0 && yspacing == 0.0)
551 if ( xspacing == 0.0)
553 gdcmWarningMacro("gdcmData/CT-MONO2-8-abdo.dcm-like problem");
554 // seems to be a bug in the header ...
555 nbValues = sscanf( strSpacing.c_str(), "%f \\0\\%f ", &yspacing, &xspacing);
556 gdcmAssertMacro( nbValues == 2 );
563 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
564 * then from 0028,0030 : Pixel Spacing
566 * @return Y dimension of a pixel
568 float File::GetYSpacing()
570 float yspacing = 1.0;
571 // To follow David Clunie's advice, we first check ImagerPixelSpacing
573 DataEntry *entry = GetDataEntry(0x0018,0x1164);
576 yspacing = (float)entry->GetValue(0);
578 if ( yspacing == 0.0 )
584 gdcmWarningMacro( "Unfound Pixel Spacing (0018,1164)" );
586 /* const std::string &strImagerPixelSpacing = GetEntryString(0x0018,0x1164);
587 if ( strImagerPixelSpacing != GDCM_UNFOUND )
589 nbValues = sscanf( strImagerPixelSpacing.c_str(), "%f", &yspacing);
591 // if sscanf cannot read any float value, it won't affect yspacing
595 if ( yspacing == 0.0 )
601 entry = GetDataEntry(0x0028,0x0030);
604 yspacing = (float)entry->GetValue(0);
606 if ( yspacing == 0.0 )
612 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
614 /* std::string strSpacing = GetEntryString(0x0028,0x0030);
615 if ( strSpacing == GDCM_UNFOUND )
617 gdcmWarningMacro("Unfound Pixel Spacing (0028,0030)");
621 // if sscanf cannot read any float value, it won't affect yspacing
622 nbValues = sscanf( strSpacing.c_str(), "%f", &yspacing);
624 // if no values, yspacing is set to 1.0
628 if ( yspacing == 0.0 )
635 * \brief gets the info from 0018,0088 : Space Between Slices
636 * else from 0018,0050 : Slice Thickness
638 * @return Z dimension of a voxel-to be
640 float File::GetZSpacing()
645 // For *Dicom* images, ZSpacing should be calculated using
646 // XOrigin, YOrigin, ZOrigin (of the top left image corner)
647 // of 2 consecutive images, and the Orientation
649 // Computing ZSpacing on a single image is not really meaningfull !
651 float zspacing = 1.0f;
653 // Spacing Between Slices : distance between the middle of 2 slices
655 // jointives (Spacing between Slices = Slice Thickness)
656 // overlapping (Spacing between Slices < Slice Thickness)
657 // disjointes (Spacing between Slices > Slice Thickness)
658 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
659 // It only concerns the MRI guys, not people wanting to visualize volumes
660 // If Spacing Between Slices is missing,
661 // we suppose slices joint together
662 DataEntry *entry = GetDataEntry(0x0018,0x0088);
665 zspacing = (float)entry->GetValue(0);
667 if ( zspacing == 0.0 )
672 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
674 // if no 'Spacing Between Slices' is found,
675 // we assume slices join together
676 // (no overlapping, no interslice gap)
677 // if they don't, we're fucked up
678 entry = GetDataEntry(0x0018,0x0050);
681 zspacing = (float)entry->GetValue(0);
683 if ( zspacing == 0.0 )
688 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
692 /* const std::string &strSpacingBSlices = GetEntryString(0x0018,0x0088);
693 if ( strSpacingBSlices == GDCM_UNFOUND )
695 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
696 const std::string &strSliceThickness = GetEntryString(0x0018,0x0050);
697 if ( strSliceThickness == GDCM_UNFOUND )
699 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
704 // if no 'Spacing Between Slices' is found,
705 // we assume slices join together
706 // (no overlapping, no interslice gap)
707 // if they don't, we're fucked up
708 return (float)atof( strSliceThickness.c_str() );
712 float zsp = (float)atof( strSpacingBSlices.c_str());
713 if (zsp == 0.0) // last change not to break further computations ...
719 * \brief gets the info from 0020,0032 : Image Position Patient
720 * else from 0020,0030 : Image Position (RET)
722 * @return up-left image corner X position
724 float File::GetXOrigin()
726 DataEntry *entry = GetDataEntry(0x0020,0x0032);
729 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
730 entry = GetDataEntry(0x0020,0x0030);
733 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
738 if( entry->GetValueCount() == 3 )
739 return (float)entry->GetValue(0);
742 /* std::string strImPos = GetEntryString(0x0020,0x0032);
743 if ( strImPos == GDCM_UNFOUND )
745 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
746 strImPos = GetEntryString(0x0020,0x0030); // For ACR-NEMA images
747 if ( strImPos == GDCM_UNFOUND )
749 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
754 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
763 * \brief gets the info from 0020,0032 : Image Position Patient
764 * else from 0020,0030 : Image Position (RET)
766 * @return up-left image corner Y position
768 float File::GetYOrigin()
770 DataEntry *entry = GetDataEntry(0x0020,0x0032);
773 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
774 entry = GetDataEntry(0x0020,0x0030);
777 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
782 if( entry->GetValueCount() == 3 )
783 return (float)entry->GetValue(1);
785 /* float xImPos, yImPos, zImPos;
786 std::string strImPos = GetEntryString(0x0020,0x0032);
788 if ( strImPos == GDCM_UNFOUND)
790 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
791 strImPos = GetEntryString(0x0020,0x0030); // For ACR-NEMA images
792 if ( strImPos == GDCM_UNFOUND )
794 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
799 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
808 * \brief gets the info from 0020,0032 : Image Position Patient
809 * else from 0020,0030 : Image Position (RET)
810 * else from 0020,1041 : Slice Location
811 * else from 0020,0050 : Location
813 * @return up-left image corner Z position
815 float File::GetZOrigin()
817 DataEntry *entry = GetDataEntry(0x0020,0x0032);
820 if( entry->GetValueCount() == 3 )
821 return (float)entry->GetValue(0);
822 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
825 /* float xImPos, yImPos, zImPos;
826 std::string strImPos = GetEntryString(0x0020,0x0032);
828 if ( strImPos != GDCM_UNFOUND )
830 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3)
832 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
833 return 0.; // bug in the element 0x0020,0x0032
841 entry = GetDataEntry(0x0020,0x0030);
844 if( entry->GetValueCount() == 3 )
845 return (float)entry->GetValue(0);
846 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
849 /* strImPos = GetEntryString(0x0020,0x0030); // For ACR-NEMA images
850 if ( strImPos != GDCM_UNFOUND )
852 if ( sscanf( strImPos.c_str(),
853 "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos ) != 3 )
855 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
856 return 0.; // bug in the element 0x0020,0x0032
864 // for *very* old ACR-NEMA images
865 entry = GetDataEntry(0x0020,0x1041);
868 if( entry->GetValueCount() == 1 )
869 return (float)entry->GetValue(0);
870 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
873 /* std::string strSliceLocation = GetEntryString(0x0020,0x1041);
874 if ( strSliceLocation != GDCM_UNFOUND )
876 if ( sscanf( strSliceLocation.c_str(), "%f ", &zImPos) != 1)
878 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
879 return 0.; // bug in the element 0x0020,0x1041
886 gdcmWarningMacro( "Unfound Slice Location (0020,1041)");*/
888 entry = GetDataEntry(0x0020,0x0050);
891 gdcmWarningMacro( "Unfound Location (0020,0050)");
892 if( entry->GetValueCount() == 1 )
893 return (float)entry->GetValue(0);
894 gdcmWarningMacro( "Wrong Location (0020,0050)");
897 /* std::string strLocation = GetEntryString(0x0020,0x0050);
898 if ( strLocation != GDCM_UNFOUND )
900 if ( sscanf( strLocation.c_str(), "%f ", &zImPos) != 1 )
902 gdcmWarningMacro( "Wrong Location (0020,0050)");
903 return 0.; // bug in the element 0x0020,0x0050
910 gdcmWarningMacro( "Unfound Location (0020,0050)");*/
912 return 0.; // Hopeless
916 * \brief gets the info from 0020,0037 : Image Orientation Patient
917 * or from 0020 0035 : Image Orientation (RET)
918 * (needed to organize DICOM files based on their x,y,z position)
919 * @param iop adress of the (6)float array to receive values
920 * @return true when one of the tag is found
921 * false when nothing is found
923 bool File::GetImageOrientationPatient( float iop[6] )
925 std::string strImOriPat;
926 //iop is supposed to be float[6]
927 iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
929 // 0020 0037 DS REL Image Orientation (Patient)
930 if ( (strImOriPat = GetEntryString(0x0020,0x0037)) != GDCM_UNFOUND )
932 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
933 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
935 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
936 << " Less than 6 values were found." );
941 // 0020 0035 DS REL Image Orientation (RET)
942 else if ( (strImOriPat = GetEntryString(0x0020,0x0035)) != GDCM_UNFOUND )
944 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
945 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
947 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
948 << "Less than 6 values were found." );
958 * \brief Retrieve the number of Bits Stored (actually used)
959 * (as opposed to number of Bits Allocated)
960 * @return The encountered number of Bits Stored, 0 by default.
961 * 0 means the file is NOT USABLE. The caller has to check it !
963 int File::GetBitsStored()
965 DataEntry *entry = GetDataEntry(0x0028,0x0101);
968 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
971 return (int)entry->GetValue(0);
973 /* std::string strSize = GetEntryString( 0x0028, 0x0101 );
974 if ( strSize == GDCM_UNFOUND )
976 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
977 return 0; // It's supposed to be mandatory
978 // the caller will have to check
980 return atoi( strSize.c_str() );*/
984 * \brief Retrieve the number of Bits Allocated
985 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
986 * @return The encountered Number of Bits Allocated, 0 by default.
987 * 0 means the file is NOT USABLE. The caller has to check it !
989 int File::GetBitsAllocated()
991 DataEntry *entry = GetDataEntry(0x0028,0x0100);
994 gdcmWarningMacro("(0028,0100) is supposed to be mandatory");
997 return (int)entry->GetValue(0);
999 /* std::string strSize = GetEntryString(0x0028,0x0100);
1000 if ( strSize == GDCM_UNFOUND )
1002 gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
1003 return 0; // It's supposed to be mandatory
1004 // the caller will have to check
1006 return atoi( strSize.c_str() );*/
1010 * \brief Retrieve the high bit position.
1011 * \warning The method defaults to 0 when information is missing.
1012 * The responsability of checking this value is left to the caller.
1013 * @return The high bit position when present. 0 when missing.
1015 int File::GetHighBitPosition()
1017 DataEntry *entry = GetDataEntry(0x0028,0x0102);
1020 gdcmWarningMacro("(0028,0102) is supposed to be mandatory");
1023 return (int)entry->GetValue(0);
1025 /* std::string strSize = GetEntryString( 0x0028, 0x0102 );
1026 if ( strSize == GDCM_UNFOUND )
1028 gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
1031 return atoi( strSize.c_str() );*/
1035 * \brief Retrieve the number of Samples Per Pixel
1036 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
1037 * @return The encountered number of Samples Per Pixel, 1 by default.
1038 * (we assume Gray level Pixels)
1040 int File::GetSamplesPerPixel()
1042 DataEntry *entry = GetDataEntry(0x0028,0x0002);
1045 gdcmWarningMacro("(0028,0002) is supposed to be mandatory");
1046 return 1; // Well, it's supposed to be mandatory ...
1047 // but sometimes it's missing : *we* assume Gray pixels
1049 return (int)entry->GetValue(0);
1051 /* const std::string &strSize = GetEntryString(0x0028,0x0002);
1052 if ( strSize == GDCM_UNFOUND )
1054 gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
1055 return 1; // Well, it's supposed to be mandatory ...
1056 // but sometimes it's missing : *we* assume Gray pixels
1058 return atoi( strSize.c_str() );*/
1062 * \brief Retrieve the Planar Configuration for RGB images
1063 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1064 * @return The encountered Planar Configuration, 0 by default.
1066 int File::GetPlanarConfiguration()
1068 DataEntry *entry = GetDataEntry(0x0028,0x0006);
1071 gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
1074 return (int)entry->GetValue(0);
1076 /* std::string strSize = GetEntryString(0x0028,0x0006);
1077 if ( strSize == GDCM_UNFOUND )
1079 gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
1082 return atoi( strSize.c_str() );*/
1086 * \brief Return the size (in bytes) of a single pixel of data.
1087 * @return The size in bytes of a single pixel of data; 0 by default
1088 * 0 means the file is NOT USABLE; the caller will have to check
1090 int File::GetPixelSize()
1092 // 0028 0100 US IMG Bits Allocated
1093 // (in order no to be messed up by old ACR-NEMA RGB images)
1094 assert( !(GetEntryString(0x0028,0x0100) == "24") );
1096 std::string pixelType = GetPixelType();
1097 if ( pixelType == "8U" || pixelType == "8S" )
1101 if ( pixelType == "16U" || pixelType == "16S")
1105 if ( pixelType == "32U" || pixelType == "32S")
1109 if ( pixelType == "FD" )
1113 gdcmWarningMacro( "Unknown pixel type: " << pixelType);
1118 * \brief Build the Pixel Type of the image.
1119 * Possible values are:
1120 * - 8U unsigned 8 bit,
1121 * - 8S signed 8 bit,
1122 * - 16U unsigned 16 bit,
1123 * - 16S signed 16 bit,
1124 * - 32U unsigned 32 bit,
1125 * - 32S signed 32 bit,
1126 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
1127 * \warning 12 bit images appear as 16 bit.
1128 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
1129 * + Planar Configuration = 0
1130 * @return 0S if nothing found. NOT USABLE file. The caller has to check
1132 std::string File::GetPixelType()
1134 std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
1135 if ( bitsAlloc == GDCM_UNFOUND )
1137 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
1138 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
1141 if ( bitsAlloc == "64" )
1145 else if ( bitsAlloc == "12" )
1147 // It will be unpacked
1150 else if ( bitsAlloc == "24" )
1152 // (in order no to be messed up by old RGB images)
1157 if( IsSignedPixelData() )
1166 /* std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
1167 if ( bitsAlloc == GDCM_UNFOUND )
1169 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
1170 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
1173 if ( bitsAlloc == "64" )
1177 else if ( bitsAlloc == "12" )
1179 // It will be unpacked
1182 else if ( bitsAlloc == "24" )
1184 // (in order no to be messed up by old RGB images)
1188 std::string sign = GetEntryString(0x0028, 0x0103);//"Pixel Representation"
1190 if (sign == GDCM_UNFOUND )
1192 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
1193 sign = "U"; // default and arbitrary value, not to polute the output
1195 else if ( sign == "0" )
1203 return bitsAlloc + sign;
1207 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
1208 * \warning The method defaults to false (UNsigned) when tag 0028|0103
1210 * The responsability of checking this value is left to the caller
1211 * (NO transformation is performed on the pixels to make then >0)
1212 * @return True when signed, false when UNsigned
1214 bool File::IsSignedPixelData()
1216 DataEntry *entry = GetDataEntry(0x0028, 0x0103);//"Pixel Representation"
1219 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
1222 return entry->GetValue(0) != 0;
1223 /* std::string strSign = GetEntryString( 0x0028, 0x0103 );
1224 if ( strSign == GDCM_UNFOUND )
1226 gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
1229 int sign = atoi( strSign.c_str() );
1238 * \brief Check whether this a monochrome picture (gray levels) or not,
1239 * using "Photometric Interpretation" tag (0x0028,0x0004).
1240 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1242 bool File::IsMonochrome()
1244 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1245 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1246 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1250 if ( PhotometricInterp == GDCM_UNFOUND )
1252 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1258 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1259 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1260 * @return true when "MONOCHROME1" . False otherwise.
1262 bool File::IsMonochrome1()
1264 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1265 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1269 if ( PhotometricInterp == GDCM_UNFOUND )
1271 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1277 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1278 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1279 * @return true when "PALETTE COLOR". False otherwise.
1281 bool File::IsPaletteColor()
1283 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1284 if ( PhotometricInterp == "PALETTE COLOR " )
1288 if ( PhotometricInterp == GDCM_UNFOUND )
1290 gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1296 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1297 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1298 * @return true when "YBR_FULL". False otherwise.
1300 bool File::IsYBRFull()
1302 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1303 if ( PhotometricInterp == "YBR_FULL" )
1307 if ( PhotometricInterp == GDCM_UNFOUND )
1309 gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1315 * \brief tells us if LUT are used
1316 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1317 * are NOT considered as LUT, since nobody knows
1318 * how to deal with them
1319 * Please warn me if you know sbdy that *does* know ... jprx
1320 * @return true if LUT Descriptors and LUT Tables were found
1324 // Check the presence of the LUT Descriptors, and LUT Tables
1326 if ( !GetDocEntry(0x0028,0x1101) )
1330 // LutDescriptorGreen
1331 if ( !GetDocEntry(0x0028,0x1102) )
1335 // LutDescriptorBlue
1336 if ( !GetDocEntry(0x0028,0x1103) )
1340 // Red Palette Color Lookup Table Data
1341 if ( !GetDocEntry(0x0028,0x1201) )
1345 // Green Palette Color Lookup Table Data
1346 if ( !GetDocEntry(0x0028,0x1202) )
1350 // Blue Palette Color Lookup Table Data
1351 if ( !GetDocEntry(0x0028,0x1203) )
1356 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1357 // NOT taken into account, but we don't know how to use it ...
1362 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1364 * @return Lookup Table number of Bits , 0 by default
1365 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1366 * @ return bit number of each LUT item
1368 int File::GetLUTNbits()
1370 std::vector<std::string> tokens;
1373 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1374 // = Lookup Table Desc-Blue
1375 // Consistency already checked in GetLUTLength
1376 std::string lutDescription = GetEntryString(0x0028,0x1101);
1377 if ( lutDescription == GDCM_UNFOUND )
1382 tokens.clear(); // clean any previous value
1383 Util::Tokenize ( lutDescription, tokens, "\\" );
1384 //LutLength=atoi(tokens[0].c_str());
1385 //LutDepth=atoi(tokens[1].c_str());
1387 lutNbits = atoi( tokens[2].c_str() );
1394 *\brief gets the info from 0028,1052 : Rescale Intercept
1395 * @return Rescale Intercept
1397 float File::GetRescaleIntercept()
1399 // 0028 1052 DS IMG Rescale Intercept
1400 DataEntry *entry = GetDataEntry(0x0028, 0x1052);
1403 gdcmWarningMacro( "Missing Rescale Intercept (0028,1052)");
1406 return (float)entry->GetValue(0);
1408 /* float resInter = 0.;
1409 /// 0028 1052 DS IMG Rescale Intercept
1410 const std::string &strRescInter = GetEntryString(0x0028,0x1052);
1411 if ( strRescInter != GDCM_UNFOUND )
1413 if ( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1415 // bug in the element 0x0028,0x1052
1416 gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1424 *\brief gets the info from 0028,1053 : Rescale Slope
1425 * @return Rescale Slope
1427 float File::GetRescaleSlope()
1429 // 0028 1053 DS IMG Rescale Slope
1430 DataEntry *entry = GetDataEntry(0x0028, 0x1053);
1433 gdcmWarningMacro( "Missing Rescale Slope (0028,1053)");
1436 return (float)entry->GetValue(0);
1437 /* float resSlope = 1.;
1438 //0028 1053 DS IMG Rescale Slope
1439 std::string strRescSlope = GetEntryString(0x0028,0x1053);
1440 if ( strRescSlope != GDCM_UNFOUND )
1442 if ( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1 )
1444 // bug in the element 0x0028,0x1053
1445 gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1453 * \brief This function is intended to user who doesn't want
1454 * to have to manage a LUT and expects to get an RBG Pixel image
1455 * (or a monochrome one ...)
1456 * \warning to be used with GetImagePixels()
1457 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1459 int File::GetNumberOfScalarComponents()
1461 if ( GetSamplesPerPixel() == 3 )
1466 // 0028 0100 US IMG Bits Allocated
1467 // (in order no to be messed up by old RGB images)
1468 if ( GetEntryString(0x0028,0x0100) == "24" )
1473 std::string strPhotometricInterpretation = GetEntryString(0x0028,0x0004);
1475 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1477 if ( HasLUT() )// PALETTE COLOR is NOT enough
1487 // beware of trailing space at end of string
1488 // DICOM tags are never of odd length
1489 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1490 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1491 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1497 // we assume that *all* kinds of YBR are dealt with
1503 * \brief This function is intended to user that DOESN'T want
1504 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1505 * - the (vtk) user is supposed to know how deal with LUTs -
1506 * \warning to be used with GetImagePixelsRaw()
1507 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1509 int File::GetNumberOfScalarComponentsRaw()
1511 // 0028 0100 US IMG Bits Allocated
1512 // (in order no to be messed up by old RGB images)
1513 if ( File::GetEntryString(0x0028,0x0100) == "24" )
1518 // we assume that *all* kinds of YBR are dealt with
1519 return GetSamplesPerPixel();
1523 * \brief Recover the offset (from the beginning of the file)
1524 * of *image* pixels (not *icone image* pixels, if any !)
1525 * @return Pixel Offset
1527 size_t File::GetPixelOffset()
1529 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1532 return pxlElement->GetOffset();
1536 gdcmDebugMacro( "Big trouble : Pixel Element ("
1537 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1543 * \brief Recover the pixel area length (in Bytes)
1544 * @return Pixel Element Length, as stored in the header
1545 * (NOT the memory space necessary to hold the Pixels
1546 * -in case of embeded compressed image-)
1547 * 0 : NOT USABLE file. The caller has to check.
1549 size_t File::GetPixelAreaLength()
1551 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1554 return pxlElement->GetLength();
1558 gdcmDebugMacro( "Big trouble : Pixel Element ("
1559 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1565 * \brief Adds the characteristics of a new element we want to anonymize
1566 * @param group Group number of the target tag.
1567 * @param elem Element number of the target tag.
1568 * @param value new value (string) to substitute with
1570 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1571 std::string const &value)
1577 UserAnonymizeList.push_back(el);
1581 * \brief Overwrites in the file the values of the DicomElements
1584 void File::AnonymizeNoLoad()
1586 std::fstream *fp = new std::fstream(Filename.c_str(),
1587 std::ios::in | std::ios::out | std::ios::binary);
1591 uint32_t valLgth = 0;
1592 std::string *spaces;
1593 for (ListElements::iterator it = UserAnonymizeList.begin();
1594 it != UserAnonymizeList.end();
1597 d = GetDocEntry( (*it).Group, (*it).Elem);
1602 if ( dynamic_cast<SeqEntry *>(d) )
1604 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1608 offset = d->GetOffset();
1609 lgth = d->GetLength();
1612 spaces = new std::string( lgth-valLgth, ' ');
1613 (*it).Value = (*it).Value + *spaces;
1616 fp->seekp( offset, std::ios::beg );
1617 fp->write( (*it).Value.c_str(), lgth );
1625 * \brief anonymize a File (remove Patient's personal info passed with
1626 * AddAnonymizeElement()
1627 * \note You cannot Anonymize a DataEntry (to be fixed)
1629 bool File::AnonymizeFile()
1631 // If Anonymisation list is empty, let's perform some basic anonymization
1632 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1634 // If exist, replace by spaces
1635 SetEntryString(" ",0x0010, 0x2154); // Telephone
1636 SetEntryString(" ",0x0010, 0x1040); // Adress
1637 SetEntryString(" ",0x0010, 0x0020); // Patient ID
1639 DocEntry *patientNameHE = GetDocEntry (0x0010, 0x0010);
1641 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1643 std::string studyInstanceUID = GetEntryString (0x0020, 0x000d);
1644 if ( studyInstanceUID != GDCM_UNFOUND )
1646 SetEntryString(studyInstanceUID, 0x0010, 0x0010);
1650 SetEntryString("anonymized", 0x0010, 0x0010);
1657 for (ListElements::iterator it = UserAnonymizeList.begin();
1658 it != UserAnonymizeList.end();
1661 d = GetDocEntry( (*it).Group, (*it).Elem);
1666 if ( dynamic_cast<SeqEntry *>(d) )
1668 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1672 if ( dynamic_cast<DataEntry *>(d) )
1674 gdcmWarningMacro( "To 'Anonymize' a DataEntry, better use AnonymizeNoLoad (FIXME) ");
1678 SetEntryString ((*it).Value, (*it).Group, (*it).Elem);
1682 // In order to make definitively impossible any further identification
1683 // remove or replace all the stuff that contains a Date
1685 //0008 0012 DA ID Instance Creation Date
1686 //0008 0020 DA ID Study Date
1687 //0008 0021 DA ID Series Date
1688 //0008 0022 DA ID Acquisition Date
1689 //0008 0023 DA ID Content Date
1690 //0008 0024 DA ID Overlay Date
1691 //0008 0025 DA ID Curve Date
1692 //0008 002a DT ID Acquisition Datetime
1693 //0018 9074 DT ACQ Frame Acquisition Datetime
1694 //0018 9151 DT ACQ Frame Reference Datetime
1695 //0018 a002 DT ACQ Contribution Date Time
1696 //0020 3403 SH REL Modified Image Date (RET)
1697 //0032 0032 DA SDY Study Verified Date
1698 //0032 0034 DA SDY Study Read Date
1699 //0032 1000 DA SDY Scheduled Study Start Date
1700 //0032 1010 DA SDY Scheduled Study Stop Date
1701 //0032 1040 DA SDY Study Arrival Date
1702 //0032 1050 DA SDY Study Completion Date
1703 //0038 001a DA VIS Scheduled Admission Date
1704 //0038 001c DA VIS Scheduled Discharge Date
1705 //0038 0020 DA VIS Admitting Date
1706 //0038 0030 DA VIS Discharge Date
1707 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1708 //0040 0004 DA PRC Scheduled Procedure Step End Date
1709 //0040 0244 DA PRC Performed Procedure Step Start Date
1710 //0040 0250 DA PRC Performed Procedure Step End Date
1711 //0040 2004 DA PRC Issue Date of Imaging Service Request
1712 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1713 //0040 4011 DT PRC Expected Completion Date and Time
1714 //0040 a030 DT PRC Verification Date Time
1715 //0040 a032 DT PRC Observation Date Time
1716 //0040 a120 DT PRC DateTime
1717 //0040 a121 DA PRC Date
1718 //0040 a13a DT PRC Referenced Datetime
1719 //0070 0082 DA ??? Presentation Creation Date
1720 //0100 0420 DT ??? SOP Autorization Date and Time
1721 //0400 0105 DT ??? Digital Signature DateTime
1722 //2100 0040 DA PJ Creation Date
1723 //3006 0008 DA SSET Structure Set Date
1724 //3008 0024 DA ??? Treatment Control Point Date
1725 //3008 0054 DA ??? First Treatment Date
1726 //3008 0056 DA ??? Most Recent Treatment Date
1727 //3008 0162 DA ??? Safe Position Exit Date
1728 //3008 0166 DA ??? Safe Position Return Date
1729 //3008 0250 DA ??? Treatment Date
1730 //300a 0006 DA RT RT Plan Date
1731 //300a 022c DA RT Air Kerma Rate Reference Date
1732 //300e 0004 DA RT Review Date
1738 * \brief Performs some consistency checking on various 'File related'
1739 * (as opposed to 'DicomDir related') entries
1740 * then writes in a file all the (Dicom Elements) included the Pixels
1741 * @param fileName file name to write to
1742 * @param writetype type of the file to be written
1743 * (ACR, ExplicitVR, ImplicitVR)
1745 bool File::Write(std::string fileName, FileType writetype)
1747 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1748 std::ios::out | std::ios::binary);
1751 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1755 // Entry : 0002|0000 = group length -> recalculated
1756 DataEntry *e0000 = GetDataEntry(0x0002,0x0000);
1759 std::ostringstream sLen;
1760 sLen << ComputeGroup0002Length( );
1761 e0000->SetString(sLen.str());
1764 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1767 // no (GrPixel, NumPixel) element
1768 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1769 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1770 InsertEntryString(s_lgPix,GrPixel, 0x0000);
1773 Document::WriteContent(fp, writetype);
1781 //-----------------------------------------------------------------------------
1785 //-----------------------------------------------------------------------------
1788 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1789 * Compute the RLE extra information and store it in \ref RLEInfo
1790 * for later pixel retrieval usage.
1792 void File::ComputeRLEInfo()
1794 std::string ts = GetTransferSyntax();
1795 if ( !Global::GetTS()->IsRLELossless(ts) )
1800 // Encoded pixel data: for the time being we are only concerned with
1801 // Jpeg or RLE Pixel data encodings.
1802 // As stated in PS 3.5-2003, section 8.2 p44:
1803 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1804 // value representation OB is used".
1805 // Hence we expect an OB value representation. Concerning OB VR,
1806 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1807 // "For the Value Representations OB and OW, the encoding shall meet the
1808 // following specifications depending on the Data element tag:"
1810 // - the first item in the sequence of items before the encoded pixel
1811 // data stream shall be basic offset table item. The basic offset table
1812 // item value, however, is not required to be present"
1813 ReadEncapsulatedBasicOffsetTable();
1815 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1816 // Loop on the individual frame[s] and store the information
1817 // on the RLE fragments in a RLEFramesInfo.
1818 // Note: - when only a single frame is present, this is a
1820 // - when more than one frame are present, then we are in
1821 // the case of a multi-frame image.
1825 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1827 // Since we have read the basic offset table, let's check the value were correct
1828 // or else produce a warning:
1829 if ( BasicOffsetTableItemValue )
1831 // If a BasicOffsetTableItemValue was read
1832 uint32_t individualLength = BasicOffsetTableItemValue[i];
1833 assert( individualLength == sum ); // REMOVE that if this is a problem
1834 if( individualLength != sum )
1836 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1838 sum += frameLength + 8;
1841 // Parse the RLE Header and store the corresponding RLE Segment
1842 // Offset Table information on fragments of this current Frame.
1843 // Note that the fragment pixels themselves are not loaded
1844 // (but just skipped).
1845 long frameOffset = Fp->tellg();
1847 uint32_t nbRleSegments = ReadInt32();
1848 if ( nbRleSegments > 16 )
1850 // There should be at most 15 segments (refer to RLEFrame class)
1851 gdcmWarningMacro( "Too many segments.");
1854 uint32_t rleSegmentOffsetTable[16];
1855 for( int k = 1; k <= 15; k++ )
1857 rleSegmentOffsetTable[k] = ReadInt32();
1860 // Deduce from both RLE Header and frameLength
1861 // the fragment length, and again store this info
1862 // in a RLEFramesInfo.
1863 long rleSegmentLength[15];
1864 // skipping (not reading) RLE Segments
1865 if ( nbRleSegments > 1)
1867 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1869 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1870 - rleSegmentOffsetTable[k];
1871 SkipBytes(rleSegmentLength[k]);
1875 rleSegmentLength[nbRleSegments] = frameLength
1876 - rleSegmentOffsetTable[nbRleSegments];
1877 SkipBytes(rleSegmentLength[nbRleSegments]);
1879 // Store the collected info
1880 RLEFrame *newFrame = new RLEFrame;
1881 newFrame->SetNumberOfFragments(nbRleSegments);
1882 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1884 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1885 newFrame->SetLength(uk,rleSegmentLength[uk]);
1887 RLEInfo->AddFrame(newFrame);
1890 // Make sure that we encounter a 'Sequence Delimiter Item'
1891 // at the end of the item :
1892 if ( !ReadTag(0xfffe, 0xe0dd) )
1894 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1899 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1900 * Compute the jpeg extra information (fragment[s] offset[s] and
1901 * length) and store it[them] in \ref JPEGInfo for later pixel
1904 void File::ComputeJPEGFragmentInfo()
1906 // If you need to, look for comments of ComputeRLEInfo().
1907 std::string ts = GetTransferSyntax();
1908 if ( ! Global::GetTS()->IsJPEG(ts) )
1913 ReadEncapsulatedBasicOffsetTable();
1915 // Loop on the fragments[s] and store the parsed information in a
1917 long fragmentLength;
1920 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1922 // Since we have read the basic offset table, let's check the value were correct
1923 // or else produce a warning:
1924 // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1925 // When the Item Value is present, the Basic Offset Table Item Value shall contain
1926 // concatenated 32-bit unsigned integer values that are byte offsets to the first
1927 // byte of the Item Tag of the first fragment for each frame in the Sequence of
1928 // Items. These offsets are measured from the first byte of the first Item Tag
1929 // following the Basic Offset Table item (See Table A.4-2).
1931 if ( BasicOffsetTableItemValue )
1933 // If a BasicOffsetTableItemValue was read
1934 uint32_t individualLength = BasicOffsetTableItemValue[i];
1935 //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1936 if( individualLength != sum )
1938 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1939 individualLength << " != " << sum );
1941 sum += fragmentLength + 8;
1945 long fragmentOffset = Fp->tellg();
1946 // Store the collected info
1947 JPEGFragment *newFragment = new JPEGFragment;
1948 newFragment->SetOffset(fragmentOffset);
1949 newFragment->SetLength(fragmentLength);
1950 JPEGInfo->AddFragment(newFragment);
1952 SkipBytes(fragmentLength);
1955 // Make sure that we encounter a 'Sequence Delimiter Item'
1956 // at the end of the item :
1957 if ( !ReadTag(0xfffe, 0xe0dd) )
1959 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1964 * \brief Assuming the internal file pointer \ref Document::Fp
1965 * is placed at the beginning of a tag check whether this
1966 * tag is (TestGroup, TestElem).
1967 * \warning On success the internal file pointer \ref Document::Fp
1968 * is modified to point after the tag.
1969 * On failure (i.e. when the tag wasn't the expected tag
1970 * (TestGroup, TestElem) the internal file pointer
1971 * \ref Document::Fp is restored to it's original position.
1972 * @param testGroup The expected group of the tag.
1973 * @param testElem The expected Element of the tag.
1974 * @return True on success, false otherwise.
1976 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1978 long positionOnEntry = Fp->tellg();
1979 long currentPosition = Fp->tellg(); // On debugging purposes
1981 // Read the Item Tag group and element, and make
1982 // sure they are what we expected:
1983 uint16_t itemTagGroup;
1984 uint16_t itemTagElem;
1987 itemTagGroup = ReadInt16();
1988 itemTagElem = ReadInt16();
1990 catch ( FormatError /*e*/ )
1992 //std::cerr << e << std::endl;
1995 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1997 gdcmWarningMacro( "Wrong Item Tag found:"
1998 << " We should have found tag ("
1999 << std::hex << testGroup << "," << testElem << ")" << std::endl
2000 << " but instead we encountered tag ("
2001 << std::hex << itemTagGroup << "," << itemTagElem << ")"
2002 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
2004 Fp->seekg(positionOnEntry, std::ios::beg);
2012 * \brief Assuming the internal file pointer \ref Document::Fp
2013 * is placed at the beginning of a tag (TestGroup, TestElement),
2014 * read the length associated to the Tag.
2015 * \warning On success the internal file pointer \ref Document::Fp
2016 * is modified to point after the tag and it's length.
2017 * On failure (i.e. when the tag wasn't the expected tag
2018 * (TestGroup, TestElement) the internal file pointer
2019 * \ref Document::Fp is restored to it's original position.
2020 * @param testGroup The expected Group of the tag.
2021 * @param testElem The expected Element of the tag.
2022 * @return On success returns the length associated to the tag. On failure
2025 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
2028 if ( !ReadTag(testGroup, testElem) )
2033 //// Then read the associated Item Length
2034 long currentPosition = Fp->tellg();
2035 uint32_t itemLength = ReadInt32();
2037 gdcmWarningMacro( "Basic Item Length is: "
2038 << itemLength << std::endl
2039 << " at address: " << std::hex << (unsigned int)currentPosition);
2045 * \brief When parsing the Pixel Data of an encapsulated file, read
2046 * the basic offset table (when present, and BTW dump it).
2048 void File::ReadEncapsulatedBasicOffsetTable()
2050 //// Read the Basic Offset Table Item Tag length...
2051 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
2053 // When present, read the basic offset table itself.
2054 // Notes: - since the presence of this basic offset table is optional
2055 // we can't rely on it for the implementation, and we will simply
2056 // trash it's content (when present).
2057 // - still, when present, we could add some further checks on the
2058 // lengths, but we won't bother with such fuses for the time being.
2059 if ( itemLength != 0 )
2061 char *charBasicOffsetTableItemValue = new char[itemLength];
2062 Fp->read(charBasicOffsetTableItemValue, itemLength);
2063 unsigned int nbEntries = itemLength/4;
2064 assert( nbEntries*4 == itemLength); // Make sure this is a multiple
2065 BasicOffsetTableItemValue = new uint32_t[nbEntries];
2067 for (unsigned int i=0; i < nbEntries; i++ )
2069 BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
2070 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
2071 uint32_t val = BasicOffsetTableItemValue[i];
2072 BasicOffsetTableItemValue[i]
2073 = ( (val<<24) | ((val<<8) & 0x00ff0000) |
2074 ((val>>8) & 0x0000ff00) | (val>>24) );
2076 gdcmWarningMacro( "Read one length for: " <<
2077 std::hex << BasicOffsetTableItemValue[i] );
2080 delete[] charBasicOffsetTableItemValue;
2084 // These are the deprecated method that one day should be removed (after the next release)
2086 #ifndef GDCM_LEGACY_REMOVE
2088 * \brief Constructor (DEPRECATED : temporaryly kept not to break the API)
2089 * @param filename name of the file whose header we want to analyze
2090 * @deprecated do not use any longer
2092 File::File( std::string const &filename )
2095 RLEInfo = new RLEFramesInfo;
2096 JPEGInfo = new JPEGFragmentsInfo;
2098 SetFileName( filename );
2099 Load( ); // gdcm::Document is first Loaded, then the 'File part'
2103 * \brief Loader. (DEPRECATED : temporaryly kept not to break the API)
2104 * @param fileName file to be open for parsing
2105 * @return false if file cannot be open or no swap info was found,
2106 * or no tag was found.
2107 * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
2109 bool File::Load( std::string const &fileName )
2111 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
2113 SetFileName( fileName );
2114 if ( ! this->Document::Load( ) )
2117 return DoTheLoadingJob( );
2121 //-----------------------------------------------------------------------------
2124 //-----------------------------------------------------------------------------
2125 } // end namespace gdcm