1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2006/06/15 14:25:26 $
7 Version: $Revision: 1.322 $
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
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
68 // we can also find (non standard!)
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;
121 FourthDimensionLocation = TagKey(0,0);
126 * \brief Canonical destructor.
134 delete[] BasicOffsetTableItemValue;
137 //-----------------------------------------------------------------------------
141 * @return false if file cannot be open or no swap info was found,
142 * or no tag was found.
146 if ( ! this->Document::Load( ) )
149 return DoTheLoadingJob( );
153 * \brief Does the Loading Job (internal use only)
154 * @return false if file cannot be open or no swap info was found,
155 * or no tag was found.
157 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"
221 //==> Just change the VR !
224 DataEntry *oldEntry = dynamic_cast<DataEntry *>(entry);
228 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
229 // more than 8 (i.e 12, 16) is a 'O Words'
230 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
235 // Change only made if usefull
236 if ( PixelVR != oldEntry->GetVR() )
238 //DictEntry* newDict = DictEntry::New(GrPixel,NumPixel,
239 // PixelVR,"1","Pixel Data");
240 //DataEntry *newEntry = DataEntry::New(newDict);
242 //newEntry->Copy(entry);
243 //newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
244 //oldEntry->SetSelfArea(false);
246 //RemoveEntry(oldEntry);
247 //AddEntry(newEntry);
248 //newEntry->Delete();
254 // 8 bits allocated is a 'OB(ytes)' , as well as 24 (old ACR-NEMA RGB)
255 // more than 8 (i.e 12, 16) is a 'OW(ords)'
256 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
260 // Change only made if usefull
261 if ( PixelVR != entry->GetVR() )
263 entry->SetVR(PixelVR);
270 * \brief This predicate, based on hopefully reasonable heuristics,
271 * decides whether or not the current File was properly parsed
272 * and contains the mandatory information for being considered as
273 * a well formed and usable Dicom/Acr File.
274 * @return true when File is the one of a reasonable Dicom/Acr file,
277 bool File::IsReadable()
279 if ( !Document::IsReadable() )
284 const std::string &res = GetEntryString(0x0028, 0x0005);
285 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
287 gdcmWarningMacro("Wrong Image Dimensions" << res);
288 return false; // Image Dimensions
290 bool b0028_0100 = true;
291 if ( !GetDocEntry(0x0028, 0x0100) )
293 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
294 //return false; // "Bits Allocated"
297 bool b0028_0101 = true;
298 if ( !GetDocEntry(0x0028, 0x0101) )
300 gdcmWarningMacro("Bits Stored (0028|0101) not found");
301 //return false; // "Bits Stored"
304 bool b0028_0102 = true;
305 if ( !GetDocEntry(0x0028, 0x0102) )
307 gdcmWarningMacro("Hight Bit (0028|0102) not found");
308 //return false; // "High Bit"
311 bool b0028_0103 = true;
312 if ( !GetDocEntry(0x0028, 0x0103) )
314 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
315 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
319 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
321 gdcmWarningMacro("Too much mandatory Tags missing !");
325 if ( !GetDocEntry(GrPixel, NumPixel) )
327 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
328 GrPixel << "|" << NumPixel << "not found");
329 return false; // Pixel Dicom Element not found :-(
335 * \brief gets the info from 0020,0013 : Image Number else 0.
336 * @return image number
338 int File::GetImageNumber()
340 //0020 0013 : Image Number
341 std::string strImNumber = GetEntryString(0x0020,0x0013);
342 if ( strImNumber != GDCM_UNFOUND )
344 return atoi( strImNumber.c_str() );
350 * \brief gets the info from 0008,0060 : Modality
351 * @return Modality Type
353 ModalityType File::GetModality()
355 // 0008 0060 : Modality
356 std::string strModality = GetEntryString(0x0008,0x0060);
357 if ( strModality != GDCM_UNFOUND )
359 if ( strModality.find("AU") < strModality.length()) return AU;
360 else if ( strModality.find("AS") < strModality.length()) return AS;
361 else if ( strModality.find("BI") < strModality.length()) return BI;
362 else if ( strModality.find("CF") < strModality.length()) return CF;
363 else if ( strModality.find("CP") < strModality.length()) return CP;
364 else if ( strModality.find("CR") < strModality.length()) return CR;
365 else if ( strModality.find("CT") < strModality.length()) return CT;
366 else if ( strModality.find("CS") < strModality.length()) return CS;
367 else if ( strModality.find("DD") < strModality.length()) return DD;
368 else if ( strModality.find("DF") < strModality.length()) return DF;
369 else if ( strModality.find("DG") < strModality.length()) return DG;
370 else if ( strModality.find("DM") < strModality.length()) return DM;
371 else if ( strModality.find("DS") < strModality.length()) return DS;
372 else if ( strModality.find("DX") < strModality.length()) return DX;
373 else if ( strModality.find("ECG") < strModality.length()) return ECG;
374 else if ( strModality.find("EPS") < strModality.length()) return EPS;
375 else if ( strModality.find("FA") < strModality.length()) return FA;
376 else if ( strModality.find("FS") < strModality.length()) return FS;
377 else if ( strModality.find("HC") < strModality.length()) return HC;
378 else if ( strModality.find("HD") < strModality.length()) return HD;
379 else if ( strModality.find("LP") < strModality.length()) return LP;
380 else if ( strModality.find("LS") < strModality.length()) return LS;
381 else if ( strModality.find("MA") < strModality.length()) return MA;
382 else if ( strModality.find("MR") < strModality.length()) return MR;
383 else if ( strModality.find("NM") < strModality.length()) return NM;
384 else if ( strModality.find("OT") < strModality.length()) return OT;
385 else if ( strModality.find("PT") < strModality.length()) return PT;
386 else if ( strModality.find("RF") < strModality.length()) return RF;
387 else if ( strModality.find("RG") < strModality.length()) return RG;
388 else if ( strModality.find("RTDOSE")
389 < strModality.length()) return RTDOSE;
390 else if ( strModality.find("RTIMAGE")
391 < strModality.length()) return RTIMAGE;
392 else if ( strModality.find("RTPLAN")
393 < strModality.length()) return RTPLAN;
394 else if ( strModality.find("RTSTRUCT")
395 < strModality.length()) return RTSTRUCT;
396 else if ( strModality.find("SM") < strModality.length()) return SM;
397 else if ( strModality.find("ST") < strModality.length()) return ST;
398 else if ( strModality.find("TG") < strModality.length()) return TG;
399 else if ( strModality.find("US") < strModality.length()) return US;
400 else if ( strModality.find("VF") < strModality.length()) return VF;
401 else if ( strModality.find("XA") < strModality.length()) return XA;
402 else if ( strModality.find("XC") < strModality.length()) return XC;
406 /// \todo throw error return value ???
407 /// specified <> unknown in our database
415 * \brief Retrieve the number of columns of image.
416 * @return The encountered size when found, 0 by default.
417 * 0 means the file is NOT USABLE. The caller will have to check
421 DataEntry *entry = GetDataEntry(0x0028,0x0011);
423 return (int)entry->GetValue(0);
428 * \brief Retrieve the number of lines of image.
429 * \warning The defaulted value is 1 as opposed to File::GetXSize()
430 * @return The encountered size when found, 1 by default
431 * (The ACR-NEMA file contains a Signal, not an Image).
435 DataEntry *entry = GetDataEntry(0x0028,0x0010);
437 return (int)entry->GetValue(0);
444 // The Rows (0028,0010) entry was optional for ACR/NEMA.
445 // (at least some images didn't have it.)
446 // It might hence be a signal (1D image). So we default to 1:
451 * \brief Retrieve the number of planes of volume or the number
452 * of frames of a multiframe.
453 * \warning When present we consider the "Number of Frames" as the third
454 * dimension. When missing we consider the third dimension as
455 * being the ACR-NEMA "Planes" tag content.
456 * @return The encountered size when found, 1 by default (single image).
460 // Both DicomV3 and ACR/Nema consider the "Number of Frames"
461 // as the third dimension.
462 DataEntry *entry = GetDataEntry(0x0028,0x0008);
464 return (int)entry->GetValue(0);
466 // We then consider the "Planes" entry as the third dimension
467 entry = GetDataEntry(0x0028,0x0012);
469 return (int)entry->GetValue(0);
474 * \brief Retrieve the -unnormalized- number of 'times' of '4D image'.
475 * User has to tell gdcm the location of this '4th Dimension component'
476 * using SetFourthDimensionLocation() method before.
477 * \warning The defaulted value is 1.
478 * @return The encountered size when found, 1 by default
479 * (The file doesn't contain a '4D image'.).
483 if (FourthDimensionLocation == TagKey(0,0) )// 4D location is not set : not a 4D object
486 DataEntry *entry = GetDataEntry(FourthDimensionLocation.GetGroup(),
487 FourthDimensionLocation.GetElement() );
490 gdcmWarningMacro( " FourthDimensionLocation not found at : " <<
491 std::hex << FourthDimensionLocation.GetGroup()
492 << "|" << FourthDimensionLocation.GetElement());
497 return (int)entry->GetValue(0);
502 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
503 * then 0028,0030 : Pixel Spacing
505 * @return X dimension of a pixel
507 float File::GetXSpacing()
509 float xspacing = 1.0;
514 From:David Clunie - view profile
515 Date:Wed, May 24 2006 1:12 pm
516 Email:David Clunie <dclu...@dclunie.com>
517 Groups:comp.protocols.dicom
519 The short answer is that:
521 - (0018,1164) describes a spacing equivalent to that which
522 would be measured off a film in projection radiography
524 - (0018,7022) does not describe the image pixels themselves,
525 since detector elements may have been binned to produce
528 - (0018,7020) may be different from (0018,7022) since there
529 may be non-sensitive material separating individual
530 detectors (i.e. the size is smaller than the spacing
533 Only (0018,1164) is relevant when measuring things; the
534 detector-specific attributes are there to describe the
539 PS. For ultrasound you need to use Region Calibration.
543 It *SHOULD* first find the IOD and then deduce which tags to read
544 Eg: Cross section this is in Pixel Spacing (0028,0030)
545 CR is in Imager Pixel Spacing (0018,1164)
546 US is in Pixel Aspect Ratio (0028,0034)
548 (3002,0011) Image Plane Pixel Spacing
549 (3002,0012) RT Image Position
551 (3004,000c) for deducing Z spacing
554 std::string SOPClassUID = GetEntryString(0x0008,0x0016);
556 /// \todo check the various SOP Class
557 /// to get the Pixel Spacing at the proper location
559 ///\todo find images to check if it *actually* works
561 if (Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.6")
562 // Ultrasound Image Storage (Retired)
563 || Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.6.1")
564 // Ultrasound Image Storage
565 || Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.3")
566 // Ultrasound Multi-Frame Storage (Retired)
567 || Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.3.1") )
568 // Ultrasound Multi-FrameImage Storage
570 // - check if SOPClassUID contains 2 parts (e.g. "4\3")
571 // - guess how to deduce the spacing (FOV ?, ??)
573 entry = GetDataEntry(0x0028,0x0034);
574 nbValue = entry->GetValueCount();
576 gdcmWarningMacro("PixelAspectRatio (0x0028,0x0034) "
577 << "has a wrong number of values :" << nbValue);
579 xspacing = 1.0; // We get Pixel Aspect Ratio, not Spacing ...
587 if (Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.1") )
588 // Computed Radiography Image Storage
590 // CR is in Imager Pixel Spacing (0018,1164)//
593 // go on with old method ...
594 // ---------------------
595 // To follow David Clunie's advice, we first check ImagerPixelSpacing
597 entry = GetDataEntry(0x0018,0x1164);
600 nbValue = entry->GetValueCount();
601 // Can't use IsValueCountValid because of the complex heuristic.
603 gdcmWarningMacro("ImagerPixelSpacing (0x0018,0x1164) "
604 << "has a wrong number of values :" << nbValue);
607 xspacing = (float)entry->GetValue(2);
608 else if( nbValue >= 2 )
609 xspacing = (float)entry->GetValue(1);
611 xspacing = (float)entry->GetValue(0);
613 if ( xspacing == 0.0 )
619 gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
622 entry = GetDataEntry(0x0028,0x0030);
625 nbValue = entry->GetValueCount();
627 gdcmWarningMacro("PixelSpacing (0x0018,0x0030) "
628 << "has a wrong number of values :" << nbValue);
631 xspacing = (float)entry->GetValue(2);
632 else if( nbValue >= 2 )
633 xspacing = (float)entry->GetValue(1);
635 xspacing = (float)entry->GetValue(0);
637 if ( xspacing == 0.0 )
643 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
649 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
650 * then from 0028,0030 : Pixel Spacing
652 * @return Y dimension of a pixel
654 float File::GetYSpacing()
661 std::string SOPClassUID = GetEntryString(0x0008,0x0016);
663 /// \todo check the various SOP Class
664 /// to get the Pixel Spacing at the proper location
666 ///\todo find images to check if it *actually* works
668 if (Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.6")
669 // Ultrasound Image Storage (Retired)
670 || Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.6.1")
671 // Ultrasound Image Storage
672 || Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.3")
673 // Ultrasound Multi-Frame Storage (Retired)
674 || Util::DicomStringEqual( SOPClassUID,"1.2.840.10008.5.1.4.1.1.3.1") )
675 // Ultrasound Multi-FrameImage Storage
677 // - check if SOPClassUID contains 2 parts (e.g. "4\3")
678 // - no way to deduce the spacing/
680 entry = GetDataEntry(0x0028,0x0034);
681 nbValue = entry->GetValueCount();
683 gdcmWarningMacro("PixelAspectRatio (0x0028,0x0034) "
684 << "has a wrong number of values :" << nbValue);
686 yspacing = (float)entry->GetValue(0)/(float)entry->GetValue(1);
687 std::cout << "ys " << yspacing << std::endl;
696 // go on with old method ...
697 // ---------------------
698 // To follow David Clunie's advice, we first check ImagerPixelSpacing
700 // To follow David Clunie's advice, we first check ImagerPixelSpacing
702 entry = GetDataEntry(0x0018,0x1164);
705 yspacing = (float)entry->GetValue(0);
707 if ( yspacing == 0.0 )
713 gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
716 entry = GetDataEntry(0x0028,0x0030);
719 yspacing = (float)entry->GetValue(0);
721 if ( yspacing == 0.0 )
727 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
734 * \brief gets the info from 0018,0088 : Space Between Slices
735 * else from 0018,0050 : Slice Thickness
738 * When an element is missing, we suppose slices join together
739 * (no overlapping, no interslice gap) but we have no way to check it !
740 * For *Dicom* images, ZSpacing *should be* calculated using
741 * XOrigin, YOrigin, ZOrigin (of the top left image corner)
742 * of 2 consecutive images, and the Orientation
743 * Computing ZSpacing on a single image is not really meaningfull !
744 * @return Z dimension of a voxel-to be
746 float File::GetZSpacing()
749 float zspacing = 1.0f;
751 // Spacing Between Slices : distance between the middle of 2 slices
753 // jointives (Spacing between Slices = Slice Thickness)
754 // overlapping (Spacing between Slices < Slice Thickness)
755 // disjointes (Spacing between Slices > Slice Thickness)
756 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
757 // It only concerns the MRI guys, not people wanting to visualize volumes
758 // If Spacing Between Slices is missing,
759 // we suppose slices joint together
760 DataEntry *entry = GetDataEntry(0x0018,0x0088);
763 zspacing = (float)entry->GetValue(0);
765 if ( zspacing == 0.0 )
770 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
772 // if no 'Spacing Between Slices' is found,
773 // we assume slices join together
774 // (no overlapping, no interslice gap)
775 entry = GetDataEntry(0x0018,0x0050);
778 zspacing = (float)entry->GetValue(0);
780 if ( zspacing == 0.0 )
785 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
787 // if no 'Spacing Between Slices' is found,
788 // we assume slices join together
789 // (no overlapping, no interslice gap)
790 entry = GetDataEntry(0x3004,0x000c);
793 float z1 = (float)entry->GetValue(0);
794 float z2 = (float)entry->GetValue(1);
795 zspacing = z2 - z1; // can be negative...
797 if ( zspacing == 0.0 )
806 * \brief gets the info from 0020,0032 : Image Position Patient
807 * else from 0020,0030 : Image Position (RET)
809 * @return up-left image corner X position
811 float File::GetXOrigin()
813 DataEntry *entry = GetDataEntry(0x0020,0x0032);
816 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
817 entry = GetDataEntry(0x0020,0x0030);
820 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
825 if( entry->GetValueCount() == 3 )
827 if (!entry->IsValueCountValid() )
829 gdcmErrorMacro( "Invalid Value Count" );
831 return (float)entry->GetValue(0);
837 * \brief gets the info from 0020,0032 : Image Position Patient
838 * else from 0020,0030 : Image Position (RET)
840 * @return up-left image corner Y position
842 float File::GetYOrigin()
844 DataEntry *entry = GetDataEntry(0x0020,0x0032);
847 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
848 entry = GetDataEntry(0x0020,0x0030);
851 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
856 if( entry->GetValueCount() == 3 )
858 if (!entry->IsValueCountValid() )
860 gdcmErrorMacro( "Invalid Value Count" );
862 return (float)entry->GetValue(1);
868 * \brief gets the info from 0020,0032 : Image Position Patient
869 * else from 0020,0030 : Image Position (RET)
870 * else from 0020,1041 : Slice Location
871 * else from 0020,0050 : Location
873 * @return up-left image corner Z position
875 float File::GetZOrigin()
877 DataEntry *entry = GetDataEntry(0x0020,0x0032);
880 if( entry->GetValueCount() == 3 )
882 if (!entry->IsValueCountValid() )
884 gdcmErrorMacro( "Invalid Value Count" );
886 return (float)entry->GetValue(2);
888 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
892 entry = GetDataEntry(0x0020,0x0030);
895 if( entry->GetValueCount() == 3 )
897 if (!entry->IsValueCountValid() )
899 gdcmErrorMacro( "Invalid Value Count" );
901 return (float)entry->GetValue(2);
903 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
907 // for *very* old ACR-NEMA images
908 entry = GetDataEntry(0x0020,0x1041);
911 if( entry->GetValueCount() == 1 )
913 if (!entry->IsValueCountValid() )
915 gdcmErrorMacro( "Invalid Value Count" );
917 return (float)entry->GetValue(0); // VM=1 !
919 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
923 entry = GetDataEntry(0x0020,0x0050);
926 if( entry->GetValueCount() == 1 )
928 if (!entry->IsValueCountValid() )
930 gdcmErrorMacro( "Invalid Value Count" );
932 return (float)entry->GetValue(0);
934 gdcmWarningMacro( "Wrong Location (0020,0050)");
937 return 0.; // Hopeless
941 * \brief gets the info from 0020,0037 : Image Orientation Patient
942 * or from 0020 0035 : Image Orientation (RET)
944 * (needed to organize DICOM files based on their x,y,z position)
946 * @param iop adress of the (6)float array to receive values.
947 * (defaulted as 1.,0.,0.,0.,1.,0. if nothing -or inconsistent stuff-
949 * @return true when one of the tag -with consistent values- is found
950 * false when nothing or inconsistent stuff - is found
952 bool File::GetImageOrientationPatient( float iop[6] )
954 std::string strImOriPat;
955 //iop is supposed to be float[6]
956 iop[0] = iop[4] = 1.;
957 iop[1] = iop[2] = iop[3] = iop[5] = 0.;
959 // 0020 0037 DS REL Image Orientation (Patient)
960 if ( (strImOriPat = GetEntryString(0x0020,0x0037)) != GDCM_UNFOUND )
962 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
963 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
965 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
966 << " Less than 6 values were found." );
972 // 0020 0035 DS REL Image Orientation (RET)
973 else if ( (strImOriPat = GetEntryString(0x0020,0x0035)) != GDCM_UNFOUND )
975 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
976 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
978 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
979 << "Less than 6 values were found." );
988 * \brief Retrieve the number of Bits Stored (actually used)
989 * (as opposed to number of Bits Allocated)
990 * @return The encountered number of Bits Stored, 0 by default.
991 * 0 means the file is NOT USABLE. The caller has to check it !
993 int File::GetBitsStored()
995 DataEntry *entry = GetDataEntry(0x0028,0x0101);
998 gdcmWarningMacro("BitsStored (0028,0101) is supposed to be mandatory");
1001 return (int)entry->GetValue(0);
1005 * \brief Retrieve the number of Bits Allocated
1006 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
1007 * @return The encountered Number of Bits Allocated, 0 by default.
1008 * 0 means the file is NOT USABLE. The caller has to check it !
1010 int File::GetBitsAllocated()
1012 DataEntry *entry = GetDataEntry(0x0028,0x0100);
1015 gdcmWarningMacro("BitsAllocated (0028,0100) is supposed to be mandatory");
1018 return (int)entry->GetValue(0);
1022 * \brief Retrieve the high bit position.
1023 * \warning The method defaults to 0 when information is missing.
1024 * The responsability of checking this value is left to the caller.
1025 * @return The high bit position when present. 0 when missing.
1027 int File::GetHighBitPosition()
1029 DataEntry *entry = GetDataEntry(0x0028,0x0102);
1032 gdcmWarningMacro("HighBitPosition (0028,0102) is supposed to be mandatory");
1035 return (int)entry->GetValue(0);
1039 * \brief Retrieve the number of Samples Per Pixel
1040 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
1041 * @return The encountered number of Samples Per Pixel, 1 by default.
1042 * (we assume Gray level Pixels)
1044 int File::GetSamplesPerPixel()
1046 DataEntry *entry = GetDataEntry(0x0028,0x0002);
1049 gdcmWarningMacro("SamplesPerPixel (0028,0002) is supposed to be mandatory");
1050 return 1; // Well, it's supposed to be mandatory ...
1051 // but sometimes it's missing : *we* assume Gray pixels
1053 return (int)entry->GetValue(0);
1057 * \brief Retrieve the Planar Configuration for RGB images
1058 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1059 * @return The encountered Planar Configuration, 0 by default.
1061 int File::GetPlanarConfiguration()
1063 DataEntry *entry = GetDataEntry(0x0028,0x0006);
1068 return (int)entry->GetValue(0);
1072 * \brief Return the size (in bytes) of a single pixel of data.
1073 * @return The size in bytes of a single pixel of data; 0 by default
1074 * 0 means the file is NOT USABLE; the caller will have to check
1076 int File::GetPixelSize()
1078 // 0028 0100 US IMG Bits Allocated
1079 // (in order no to be messed up by old ACR-NEMA RGB images)
1080 assert( !(GetEntryString(0x0028,0x0100) == "24") );
1082 std::string pixelType = GetPixelType();
1083 if ( pixelType == "8U" || pixelType == "8S" )
1087 if ( pixelType == "16U" || pixelType == "16S")
1091 if ( pixelType == "32U" || pixelType == "32S")
1095 if ( pixelType == "FD" )
1099 gdcmWarningMacro( "Unknown pixel type: " << pixelType);
1104 * \brief Build the Pixel Type of the image.
1105 * Possible values are:
1106 * - 8U unsigned 8 bit,
1107 * - 8S signed 8 bit,
1108 * - 16U unsigned 16 bit,
1109 * - 16S signed 16 bit,
1110 * - 32U unsigned 32 bit,
1111 * - 32S signed 32 bit,
1112 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
1113 * \warning 12 bit images appear as 16 bit.
1114 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
1115 * + Planar Configuration = 0
1116 * @return 0S if nothing found. NOT USABLE file. The caller has to check
1118 std::string File::GetPixelType()
1120 std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
1121 if ( bitsAlloc == GDCM_UNFOUND )
1123 gdcmWarningMacro( "Bits Allocated (0028,0100) supposed to be mandatory");
1124 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
1127 if ( bitsAlloc == "64" )
1131 else if ( bitsAlloc == "12" )
1133 // It will be unpacked
1136 else if ( bitsAlloc == "24" )
1138 // (in order no to be messed up by old RGB images)
1143 if( IsSignedPixelData() )
1151 return bitsAlloc + sign;
1155 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
1156 * \warning The method defaults to false (UNsigned) when tag 0028|0103
1158 * The responsability of checking this value is left to the caller
1159 * (NO transformation is performed on the pixels to make then >0)
1160 * @return True when signed, false when UNsigned
1162 bool File::IsSignedPixelData()
1164 DataEntry *entry = GetDataEntry(0x0028, 0x0103);//"Pixel Representation"
1167 gdcmWarningMacro( "Pixel Representation (0028,0103) supposed to be "
1171 return entry->GetValue(0) != 0;
1175 * \brief Check whether this a monochrome picture (gray levels) or not,
1176 * using "Photometric Interpretation" tag (0x0028,0x0004).
1177 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1179 bool File::IsMonochrome()
1181 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1182 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1183 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1187 if ( PhotometricInterp == GDCM_UNFOUND )
1189 gdcmWarningMacro( "Photometric Interpretation (0028,0004) supposed to be "
1196 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1197 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1198 * @return true when "MONOCHROME1" . False otherwise.
1200 bool File::IsMonochrome1()
1202 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1203 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1207 if ( PhotometricInterp == GDCM_UNFOUND )
1209 gdcmWarningMacro( "Photometric Interpretation (0028,0004) : supposed to"
1210 << " be mandatory! ");
1216 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1217 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1218 * @return true when "PALETTE COLOR". False otherwise.
1220 bool File::IsPaletteColor()
1222 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1223 if ( PhotometricInterp == "PALETTE COLOR " )
1227 if ( PhotometricInterp == GDCM_UNFOUND )
1229 gdcmDebugMacro( "Not found : Palette color (0028,0004)");
1235 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1236 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1237 * @return true when "YBR_FULL". False otherwise.
1239 bool File::IsYBRFull()
1241 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1242 if ( PhotometricInterp == "YBR_FULL" )
1246 if ( PhotometricInterp == GDCM_UNFOUND )
1248 gdcmDebugMacro( "Not found : YBR Full (0028,0004)");
1254 * \brief tells us if LUT are used
1255 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1256 * are NOT considered as LUT, since nobody knows
1257 * how to deal with them
1258 * Please warn me if you know sbdy that *does* know ... jprx
1259 * @return true if LUT Descriptors and LUT Tables were found
1263 // Check the presence of the LUT Descriptors, and LUT Tables
1265 if ( !GetDocEntry(0x0028,0x1101) )
1269 // LutDescriptorGreen
1270 if ( !GetDocEntry(0x0028,0x1102) )
1274 // LutDescriptorBlue
1275 if ( !GetDocEntry(0x0028,0x1103) )
1279 // Red Palette Color Lookup Table Data
1280 if ( !GetDocEntry(0x0028,0x1201) )
1284 // Green Palette Color Lookup Table Data
1285 if ( !GetDocEntry(0x0028,0x1202) )
1289 // Blue Palette Color Lookup Table Data
1290 if ( !GetDocEntry(0x0028,0x1203) )
1295 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1296 // NOT taken into account, but we don't know how to use it ...
1301 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1303 * @return Lookup Table number of Bits , 0 by default
1304 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1305 * @ return bit number of each LUT item
1307 int File::GetLUTNbits()
1309 std::vector<std::string> tokens;
1312 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1313 // = Lookup Table Desc-Blue
1314 // Consistency already checked in GetLUTLength
1315 std::string lutDescription = GetEntryString(0x0028,0x1101);
1316 if ( lutDescription == GDCM_UNFOUND )
1321 tokens.clear(); // clean any previous value
1322 Util::Tokenize ( lutDescription, tokens, "\\" );
1323 //LutLength=atoi(tokens[0].c_str());
1324 //LutDepth=atoi(tokens[1].c_str());
1326 lutNbits = atoi( tokens[2].c_str() );
1333 *\brief gets the info from 0028,1052 : Rescale Intercept
1334 * @return Rescale Intercept. defaulted to 0.0 is not found or empty
1336 float File::GetRescaleIntercept()
1338 // 0028 1052 DS IMG Rescale Intercept
1339 DataEntry *entry = GetDataEntry(0x0028, 0x1052);
1342 gdcmWarningMacro( "Missing Rescale Intercept (0028,1052)");
1345 return (float)entry->GetValue(0);
1350 *\brief gets the info from 0028,1053 : Rescale Slope
1351 * @return Rescale Slope. defaulted to 1.0 is not found or empty
1353 float File::GetRescaleSlope()
1355 // 0028 1053 DS IMG Rescale Slope
1356 DataEntry *entry = GetDataEntry(0x0028, 0x1053);
1359 gdcmDebugMacro( "Missing Rescale Slope (0028,1053)");
1362 return (float)entry->GetValue(0);
1366 * \brief This function is intended to user who doesn't want
1367 * to have to manage a LUT and expects to get an RBG Pixel image
1368 * (or a monochrome one, if no LUT found ...)
1369 * \warning to be used with GetImagePixels()
1370 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1372 int File::GetNumberOfScalarComponents()
1374 if ( GetSamplesPerPixel() == 3 )
1379 // 0028 0100 US IMG Bits Allocated
1380 // (in order no to be messed up by old RGB images)
1381 if ( GetEntryString(0x0028,0x0100) == "24" )
1386 std::string strPhotometricInterpretation = GetEntryString(0x0028,0x0004);
1388 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1390 if ( HasLUT() )// PALETTE COLOR is NOT enough
1400 // beware of trailing space at end of string
1401 // DICOM tags are never of odd length
1402 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1403 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1404 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1410 // we assume that *all* kinds of YBR are dealt with
1416 * \brief This function is intended to user that DOESN'T want
1417 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1418 * - the (vtk) user is supposed to know how deal with LUTs -
1419 * \warning to be used with GetImagePixelsRaw()
1420 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1422 int File::GetNumberOfScalarComponentsRaw()
1424 // 0028 0100 US IMG Bits Allocated
1425 // (in order no to be messed up by old RGB images)
1426 if ( File::GetEntryString(0x0028,0x0100) == "24" )
1431 // we assume that *all* kinds of YBR are dealt with
1432 return GetSamplesPerPixel();
1436 * \brief Recover the offset (from the beginning of the file)
1437 * of *image* pixels (not *icone image* pixels, if any !)
1438 * @return Pixel Offset
1440 size_t File::GetPixelOffset()
1442 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1445 return pxlElement->GetOffset();
1449 gdcmWarningMacro( "Big trouble : Pixel Element ("
1450 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1456 * \brief Recover the pixel area length (in Bytes)
1457 * @return Pixel Element Length, as stored in the header
1458 * (NOT the memory space necessary to hold the Pixels
1459 * -in case of embeded compressed image-)
1460 * 0 : NOT USABLE file. The caller has to check.
1462 size_t File::GetPixelAreaLength()
1464 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1467 return pxlElement->GetLength();
1471 gdcmWarningMacro( "Big trouble : Pixel Element ("
1472 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1478 * \brief Adds the characteristics of a new element we want to anonymize
1479 * @param group Group number of the target tag.
1480 * @param elem Element number of the target tag.
1481 * @param value new value (string) to substitute with
1483 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1484 std::string const &value)
1490 UserAnonymizeList.push_back(el);
1494 * \brief Overwrites in the file the values of the DicomElements
1497 void File::AnonymizeNoLoad()
1499 std::fstream *fp = new std::fstream(Filename.c_str(),
1500 std::ios::in | std::ios::out | std::ios::binary);
1504 uint32_t valLgth = 0;
1505 std::string *spaces;
1506 for (ListElements::iterator it = UserAnonymizeList.begin();
1507 it != UserAnonymizeList.end();
1511 //std::cout << "File::AnonymizeNoLoad -------" << std::hex <<(*it).Group <<"|"<<
1513 // << "[" << (*it).Value << "] "<< std::dec << std::endl;
1514 d = GetDocEntry( (*it).Group, (*it).Elem);
1519 if ( dynamic_cast<SeqEntry *>(d) )
1521 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1525 valLgth = (*it).Value.size();
1529 offset = d->GetOffset();
1530 lgth = d->GetLength();
1532 //std::cout << "lgth " << lgth << " valLgth " << valLgth << std::endl;
1535 spaces = new std::string( lgth-valLgth, ' ');
1536 (*it).Value = (*it).Value + *spaces;
1537 //std::cout << "[" << (*it).Value << "] " << lgth << std::endl;
1540 fp->seekp( offset, std::ios::beg );
1541 fp->write( (*it).Value.c_str(), lgth );
1549 * \brief anonymize a File (remove Patient's personal info passed with
1550 * AddAnonymizeElement()
1551 * \note You cannot Anonymize a DataEntry (to be fixed)
1553 bool File::AnonymizeFile()
1555 // If Anonymisation list is empty, let's perform some basic anonymization
1556 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1558 // If exist, replace by spaces
1559 SetEntryString(" ",0x0010, 0x2154); // Telephone
1560 SetEntryString(" ",0x0010, 0x1040); // Adress
1561 SetEntryString(" ",0x0010, 0x0020); // Patient ID
1563 DocEntry *patientNameHE = GetDocEntry (0x0010, 0x0010);
1565 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1567 std::string studyInstanceUID = GetEntryString (0x0020, 0x000d);
1568 if ( studyInstanceUID != GDCM_UNFOUND )
1570 SetEntryString(studyInstanceUID, 0x0010, 0x0010);
1574 SetEntryString("anonymized", 0x0010, 0x0010);
1581 for (ListElements::iterator it = UserAnonymizeList.begin();
1582 it != UserAnonymizeList.end();
1585 d = GetDocEntry( (*it).Group, (*it).Elem);
1590 if ( dynamic_cast<SeqEntry *>(d) )
1592 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1596 if ( dynamic_cast<DataEntry *>(d) )
1598 gdcmWarningMacro( "To 'Anonymize' a DataEntry, better use AnonymizeNoLoad (FIXME) ");
1602 SetEntryString ((*it).Value, (*it).Group, (*it).Elem);
1606 // In order to make definitively impossible any further identification
1607 // remove or replace all the stuff that contains a Date
1609 //0008 0012 DA ID Instance Creation Date
1610 //0008 0020 DA ID Study Date
1611 //0008 0021 DA ID Series Date
1612 //0008 0022 DA ID Acquisition Date
1613 //0008 0023 DA ID Content Date
1614 //0008 0024 DA ID Overlay Date
1615 //0008 0025 DA ID Curve Date
1616 //0008 002a DT ID Acquisition Datetime
1617 //0018 9074 DT ACQ Frame Acquisition Datetime
1618 //0018 9151 DT ACQ Frame Reference Datetime
1619 //0018 a002 DT ACQ Contribution Date Time
1620 //0020 3403 SH REL Modified Image Date (RET)
1621 //0032 0032 DA SDY Study Verified Date
1622 //0032 0034 DA SDY Study Read Date
1623 //0032 1000 DA SDY Scheduled Study Start Date
1624 //0032 1010 DA SDY Scheduled Study Stop Date
1625 //0032 1040 DA SDY Study Arrival Date
1626 //0032 1050 DA SDY Study Completion Date
1627 //0038 001a DA VIS Scheduled Admission Date
1628 //0038 001c DA VIS Scheduled Discharge Date
1629 //0038 0020 DA VIS Admitting Date
1630 //0038 0030 DA VIS Discharge Date
1631 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1632 //0040 0004 DA PRC Scheduled Procedure Step End Date
1633 //0040 0244 DA PRC Performed Procedure Step Start Date
1634 //0040 0250 DA PRC Performed Procedure Step End Date
1635 //0040 2004 DA PRC Issue Date of Imaging Service Request
1636 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1637 //0040 4011 DT PRC Expected Completion Date and Time
1638 //0040 a030 DT PRC Verification Date Time
1639 //0040 a032 DT PRC Observation Date Time
1640 //0040 a120 DT PRC DateTime
1641 //0040 a121 DA PRC Date
1642 //0040 a13a DT PRC Referenced Datetime
1643 //0070 0082 DA ??? Presentation Creation Date
1644 //0100 0420 DT ??? SOP Autorization Date and Time
1645 //0400 0105 DT ??? Digital Signature DateTime
1646 //2100 0040 DA PJ Creation Date
1647 //3006 0008 DA SSET Structure Set Date
1648 //3008 0024 DA ??? Treatment Control Point Date
1649 //3008 0054 DA ??? First Treatment Date
1650 //3008 0056 DA ??? Most Recent Treatment Date
1651 //3008 0162 DA ??? Safe Position Exit Date
1652 //3008 0166 DA ??? Safe Position Return Date
1653 //3008 0250 DA ??? Treatment Date
1654 //300a 0006 DA RT RT Plan Date
1655 //300a 022c DA RT Air Kerma Rate Reference Date
1656 //300e 0004 DA RT Review Date
1662 * \brief Performs some consistency checking on various 'File related'
1663 * (as opposed to 'DicomDir related') entries
1664 * then writes in a file all the (Dicom Elements) included the Pixels
1665 * @param fileName file name to write to
1666 * @param writetype type of the file to be written
1667 * (ACR, ExplicitVR, ImplicitVR)
1669 bool File::Write(std::string fileName, FileType writetype)
1671 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1672 std::ios::out | std::ios::binary);
1675 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1679 // Entry : 0002|0000 = group length -> recalculated
1680 DataEntry *e0000 = GetDataEntry(0x0002,0x0000);
1683 std::ostringstream sLen;
1684 sLen << ComputeGroup0002Length( );
1685 e0000->SetString(sLen.str());
1688 /// \todo FIXME : Derma?.dcm does not have it...let's remove it ?!? JPRx
1689 if( writetype != JPEG )
1691 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1694 // no (GrPixel, NumPixel) element
1695 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1696 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1697 InsertEntryString(s_lgPix,GrPixel, 0x0000, "UL");
1700 Document::WriteContent(fp, writetype);
1708 //-----------------------------------------------------------------------------
1712 //-----------------------------------------------------------------------------
1715 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1716 * Compute the RLE extra information and store it in \ref RLEInfo
1717 * for later pixel retrieval usage.
1719 void File::ComputeRLEInfo()
1721 std::string ts = GetTransferSyntax();
1722 if ( !Global::GetTS()->IsRLELossless(ts) )
1727 // Encoded pixel data: for the time being we are only concerned with
1728 // Jpeg or RLE Pixel data encodings.
1729 // As stated in PS 3.5-2003, section 8.2 p44:
1730 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1731 // value representation OB is used".
1732 // Hence we expect an OB value representation. Concerning OB VR,
1733 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1734 // "For the Value Representations OB and OW, the encoding shall meet the
1735 // following specifications depending on the Data element tag:"
1737 // - the first item in the sequence of items before the encoded pixel
1738 // data stream shall be basic offset table item. The basic offset table
1739 // item value, however, is not required to be present"
1740 ReadEncapsulatedBasicOffsetTable();
1742 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1743 // Loop on the individual frame[s] and store the information
1744 // on the RLE fragments in a RLEFramesInfo.
1745 // Note: - when only a single frame is present, this is a
1747 // - when more than one frame are present, then we are in
1748 // the case of a multi-frame image.
1752 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1754 // Since we have read the basic offset table, let's check the value were correct
1755 // or else produce a warning:
1756 if ( BasicOffsetTableItemValue )
1758 // If a BasicOffsetTableItemValue was read
1759 uint32_t individualLength = BasicOffsetTableItemValue[i];
1760 assert( individualLength == sum ); // REMOVE that if this is a problem
1761 if( individualLength != sum )
1763 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1765 sum += frameLength + 8;
1768 // Parse the RLE Header and store the corresponding RLE Segment
1769 // Offset Table information on fragments of this current Frame.
1770 // Note that the fragment pixels themselves are not loaded
1771 // (but just skipped).
1772 long frameOffset = Fp->tellg(); // once per fragment
1774 uint32_t nbRleSegments = ReadInt32();
1775 if ( nbRleSegments > 16 )
1777 // There should be at most 15 segments (refer to RLEFrame class)
1778 gdcmWarningMacro( "Too many segments.");
1781 uint32_t rleSegmentOffsetTable[16];
1782 for( int k = 1; k <= 15; k++ )
1784 rleSegmentOffsetTable[k] = ReadInt32();
1787 // Deduce from both RLE Header and frameLength
1788 // the fragment length, and again store this info
1789 // in a RLEFramesInfo.
1790 long rleSegmentLength[15];
1791 // skipping (not reading) RLE Segments
1792 if ( nbRleSegments > 1)
1794 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1796 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1797 - rleSegmentOffsetTable[k];
1798 SkipBytes(rleSegmentLength[k]);
1802 rleSegmentLength[nbRleSegments] = frameLength
1803 - rleSegmentOffsetTable[nbRleSegments];
1804 SkipBytes(rleSegmentLength[nbRleSegments]);
1806 // Store the collected info
1807 RLEFrame *newFrame = new RLEFrame;
1808 newFrame->SetNumberOfFragments(nbRleSegments);
1809 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1811 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1812 newFrame->SetLength(uk,rleSegmentLength[uk]);
1814 RLEInfo->AddFrame(newFrame);
1817 // Make sure that we encounter a 'Sequence Delimiter Item'
1818 // at the end of the item :
1819 if ( !ReadTag(0xfffe, 0xe0dd) ) // once per RLE File
1821 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1826 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1827 * Compute the jpeg extra information (fragment[s] offset[s] and
1828 * length) and store it[them] in \ref JPEGInfo for later pixel
1831 void File::ComputeJPEGFragmentInfo()
1833 // If you need to, look for comments of ComputeRLEInfo().
1834 std::string ts = GetTransferSyntax();
1835 if ( ! Global::GetTS()->IsJPEG(ts) )
1840 ReadEncapsulatedBasicOffsetTable();
1842 // Loop on the fragments[s] and store the parsed information in a
1844 long fragmentLength;
1847 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1849 // Since we have read the basic offset table, let's check the value were correct
1850 // or else produce a warning:
1851 // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1852 // When the Item Value is present, the Basic Offset Table Item Value shall contain
1853 // concatenated 32-bit unsigned integer values that are byte offsets to the first
1854 // byte of the Item Tag of the first fragment for each frame in the Sequence of
1855 // Items. These offsets are measured from the first byte of the first Item Tag
1856 // following the Basic Offset Table item (See Table A.4-2).
1858 if ( BasicOffsetTableItemValue )
1860 // If a BasicOffsetTableItemValue was read
1861 uint32_t individualLength = BasicOffsetTableItemValue[i];
1862 //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1863 if( individualLength != sum )
1865 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1866 individualLength << " != " << sum );
1868 sum += fragmentLength + 8;
1872 long fragmentOffset = Fp->tellg(); // Once per fragment
1873 // Store the collected info
1874 JPEGFragment *newFragment = new JPEGFragment;
1875 newFragment->SetOffset(fragmentOffset);
1876 newFragment->SetLength(fragmentLength);
1877 JPEGInfo->AddFragment(newFragment);
1879 SkipBytes(fragmentLength);
1882 // Make sure that we encounter a 'Sequence Delimiter Item'
1883 // at the end of the item :
1884 if ( !ReadTag(0xfffe, 0xe0dd) )
1886 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1891 * \brief Assuming the internal file pointer \ref Document::Fp
1892 * is placed at the beginning of a tag, check whether this
1893 * tag is (TestGroup, TestElem).
1894 * \warning On success the internal file pointer \ref Document::Fp
1895 * is modified to point after the tag.
1896 * On failure (i.e. when the tag wasn't the expected tag
1897 * (TestGroup, TestElem) the internal file pointer
1898 * \ref Document::Fp is restored to it's original position.
1899 * @param testGroup The expected group of the tag.
1900 * @param testElem The expected Element of the tag.
1901 * @return True on success, false otherwise.
1903 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1905 long positionOnEntry = Fp->tellg(); // Only when reading fragments
1906 //long currentPosition = positionOnEntry; // On debugging purposes
1908 // Read the Item Tag group and element, and make
1909 // sure they are what we expected:
1910 uint16_t itemTagGroup;
1911 uint16_t itemTagElem;
1914 itemTagGroup = ReadInt16();
1915 itemTagElem = ReadInt16();
1917 catch ( FormatError )
1919 gdcmErrorMacro( "Can not read tag for "
1920 << " We should have found tag ("
1921 << DictEntry::TranslateToKey(testGroup,testElem) << ")"
1926 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1928 // in order not to pollute output we don't warn on 'delimitors'
1929 if (itemTagGroup != 0xfffe || testGroup != 0xfffe )
1930 gdcmWarningMacro( "Wrong Item Tag found:"
1931 << " We should have found tag ("
1932 << DictEntry::TranslateToKey(testGroup,testElem) << ")" << std::endl
1933 << " but instead we encountered tag ("
1934 << DictEntry::TranslateToKey(itemTagGroup,itemTagElem) << ")"
1935 << " at address: " << " 0x(" << std::hex
1936 << (unsigned int)positionOnEntry << std::dec << ")"
1938 Fp->seekg(positionOnEntry, std::ios::beg);
1946 * \brief Assuming the internal file pointer \ref Document::Fp
1947 * is placed at the beginning of a tag (TestGroup, TestElement),
1948 * read the length associated to the Tag.
1949 * \warning On success the internal file pointer \ref Document::Fp
1950 * is modified to point after the tag and it's length.
1951 * On failure (i.e. when the tag wasn't the expected tag
1952 * (TestGroup, TestElement) the internal file pointer
1953 * \ref Document::Fp is restored to it's original position.
1954 * @param testGroup The expected Group of the tag.
1955 * @param testElem The expected Element of the tag.
1956 * @return On success returns the length associated to the tag. On failure
1959 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1962 if ( !ReadTag(testGroup, testElem) )
1964 // Avoid polutting output
1965 if ( testGroup != 0xfffe )
1966 gdcmErrorMacro( "ReadTag did not succeed for ("
1967 << DictEntry::TranslateToKey(testGroup,testElem)
1972 //// Then read the associated Item Length
1974 // long currentPosition = Fp->tellg(); // save time // JPRx
1975 uint32_t itemLength = ReadInt32();
1976 gdcmDebugMacro( "Basic Item Length is: " << itemLength
1977 // << " at address: " << std::hex << (unsigned int)currentPosition
1983 * \brief When parsing the Pixel Data of an encapsulated file, read
1984 * the basic offset table (when present, and BTW dump it).
1986 void File::ReadEncapsulatedBasicOffsetTable()
1988 //// Read the Basic Offset Table Item Tag length...
1989 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1991 // When present, read the basic offset table itself.
1992 // Notes: - since the presence of this basic offset table is optional
1993 // we can't rely on it for the implementation, and we will simply
1994 // trash it's content (when present).
1995 // - still, when present, we could add some further checks on the
1996 // lengths, but we won't bother with such fuses for the time being.
1997 if ( itemLength != 0 )
1999 char *charBasicOffsetTableItemValue = new char[itemLength];
2000 Fp->read(charBasicOffsetTableItemValue, itemLength);
2001 unsigned int nbEntries = itemLength/4;
2002 assert( nbEntries*4 == itemLength); // Make sure this is a multiple
2003 BasicOffsetTableItemValue = new uint32_t[nbEntries];
2005 for (unsigned int i=0; i < nbEntries; i++ )
2007 BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
2008 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
2009 uint32_t val = BasicOffsetTableItemValue[i];
2010 BasicOffsetTableItemValue[i]
2011 = ( (val<<24) | ((val<<8) & 0x00ff0000) |
2012 ( (val>>8) & 0x0000ff00) | (val>>24) );
2014 gdcmDebugMacro( "Read one length for: " <<
2015 std::hex << BasicOffsetTableItemValue[i] );
2018 delete[] charBasicOffsetTableItemValue;
2022 // These are the deprecated method that one day should be removed (after the next release)
2024 //#ifndef GDCM_LEGACY_REMOVE
2026 * \ brief Loader. (DEPRECATED : temporaryly kept not to break the API)
2027 * @ param fileName file to be open for parsing
2028 * @ return false if file cannot be open or no swap info was found,
2029 * or no tag was found.
2030 * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
2033 bool File::Load( std::string const &fileName )
2035 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
2037 SetFileName( fileName );
2038 if ( ! this->Document::Load( ) )
2041 return DoTheLoadingJob( );
2045 //-----------------------------------------------------------------------------
2048 //-----------------------------------------------------------------------------
2049 } // end namespace gdcm