1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/10/17 14:26:44 $
7 Version: $Revision: 1.275 $
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 "gdcmValEntry.h"
96 #include "gdcmBinEntry.h"
97 #include "gdcmSeqEntry.h"
98 #include "gdcmRLEFramesInfo.h"
99 #include "gdcmJPEGFragmentsInfo.h"
102 #include <stdio.h> //sscanf
103 #include <stdlib.h> // for atoi
108 //-----------------------------------------------------------------------------
109 // Constructor / Destructor
112 * \brief Constructor used when we want to generate dicom files from scratch
117 RLEInfo = new RLEFramesInfo;
118 JPEGInfo = new JPEGFragmentsInfo;
119 GrPixel = 0x7fe0; // to avoid further troubles
121 BasicOffsetTableItemValue = 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( )
160 // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
161 // We may encounter the 'RETired' (0x0028, 0x0200) tag
162 // (Image Location") . This entry contains the number of
163 // the group that contains the pixel data (hence the "Pixel Data"
164 // is found by indirection through the "Image Location").
165 // Inside the group pointed by "Image Location" the searched element
166 // is conventionally the element 0x0010 (when the norm is respected).
167 // When the "Image Location" is missing we default to group 0x7fe0.
168 // Note: this IS the right place for the code
171 const std::string &imgLocation = GetEntryValue(0x0028, 0x0200);
172 if ( imgLocation == GDCM_UNFOUND )
179 GrPixel = (uint16_t) atoi( imgLocation.c_str() );
182 // sometimes Image Location value doesn't follow
183 // the supposed processor endianness.
184 // see gdcmData/cr172241.dcm
185 if ( GrPixel == 0xe07f )
190 if ( GrPixel != 0x7fe0 )
192 // This is a kludge for old dirty Philips imager.
200 // Now, we know GrPixel and NumPixel.
201 // Let's create a VirtualDictEntry to allow a further VR modification
202 // and force VR to match with BitsAllocated.
203 DocEntry *entry = GetDocEntry(GrPixel, NumPixel);
206 // Compute the RLE or JPEG info
208 const std::string &ts = GetTransferSyntax();
209 Fp->seekg( entry->GetOffset(), std::ios::beg );
210 if ( Global::GetTS()->IsRLELossless(ts) )
212 else if ( Global::GetTS()->IsJPEG(ts) )
213 ComputeJPEGFragmentInfo();
216 // Create a new BinEntry to change the DictEntry
217 // The changed DictEntry will have
218 // - a correct PixelVR OB or OW)
219 // - the name to "Pixel Data"
220 BinEntry *oldEntry = dynamic_cast<BinEntry *>(entry);
224 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
225 // more than 8 (i.e 12, 16) is a 'O Words'
226 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
231 // Change only made if usefull
232 if ( PixelVR != oldEntry->GetVR() )
234 DictEntry* newDict = NewVirtualDictEntry(GrPixel,NumPixel,
235 PixelVR,"1","Pixel Data");
237 BinEntry *newEntry = new BinEntry(newDict);
238 newEntry->Copy(entry);
239 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
240 oldEntry->SetSelfArea(false);
242 RemoveEntry(oldEntry);
250 * \brief This predicate, based on hopefully reasonable heuristics,
251 * decides whether or not the current File was properly parsed
252 * and contains the mandatory information for being considered as
253 * a well formed and usable Dicom/Acr File.
254 * @return true when File is the one of a reasonable Dicom/Acr file,
257 bool File::IsReadable()
259 if ( !Document::IsReadable() )
264 const std::string &res = GetEntryValue(0x0028, 0x0005);
265 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
267 gdcmWarningMacro("Wrong Image Dimensions" << res);
268 return false; // Image Dimensions
270 bool b0028_0100 = true;
271 if ( !GetDocEntry(0x0028, 0x0100) )
273 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
274 //return false; // "Bits Allocated"
277 bool b0028_0101 = true;
278 if ( !GetDocEntry(0x0028, 0x0101) )
280 gdcmWarningMacro("Bits Stored (0028|0101) not found");
281 //return false; // "Bits Stored"
284 bool b0028_0102 = true;
285 if ( !GetDocEntry(0x0028, 0x0102) )
287 gdcmWarningMacro("Hight Bit (0028|0102) not found");
288 //return false; // "High Bit"
291 bool b0028_0103 = true;
292 if ( !GetDocEntry(0x0028, 0x0103) )
294 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
295 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
299 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
301 gdcmWarningMacro("Too much mandatory Tags missing !");
305 if ( !GetDocEntry(GrPixel, NumPixel) )
307 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
308 GrPixel << "|" << NumPixel << "not found");
309 return false; // Pixel Dicom Element not found :-(
315 * \brief gets the info from 0020,0013 : Image Number else 0.
316 * @return image number
318 int File::GetImageNumber()
320 //0020 0013 : Image Number
321 std::string strImNumber = GetEntryValue(0x0020,0x0013);
322 if ( strImNumber != GDCM_UNFOUND )
324 return atoi( strImNumber.c_str() );
330 * \brief gets the info from 0008,0060 : Modality
331 * @return Modality Type
333 ModalityType File::GetModality()
335 // 0008 0060 : Modality
336 std::string strModality = GetEntryValue(0x0008,0x0060);
337 if ( strModality != GDCM_UNFOUND )
339 if ( strModality.find("AU") < strModality.length()) return AU;
340 else if ( strModality.find("AS") < strModality.length()) return AS;
341 else if ( strModality.find("BI") < strModality.length()) return BI;
342 else if ( strModality.find("CF") < strModality.length()) return CF;
343 else if ( strModality.find("CP") < strModality.length()) return CP;
344 else if ( strModality.find("CR") < strModality.length()) return CR;
345 else if ( strModality.find("CT") < strModality.length()) return CT;
346 else if ( strModality.find("CS") < strModality.length()) return CS;
347 else if ( strModality.find("DD") < strModality.length()) return DD;
348 else if ( strModality.find("DF") < strModality.length()) return DF;
349 else if ( strModality.find("DG") < strModality.length()) return DG;
350 else if ( strModality.find("DM") < strModality.length()) return DM;
351 else if ( strModality.find("DS") < strModality.length()) return DS;
352 else if ( strModality.find("DX") < strModality.length()) return DX;
353 else if ( strModality.find("ECG") < strModality.length()) return ECG;
354 else if ( strModality.find("EPS") < strModality.length()) return EPS;
355 else if ( strModality.find("FA") < strModality.length()) return FA;
356 else if ( strModality.find("FS") < strModality.length()) return FS;
357 else if ( strModality.find("HC") < strModality.length()) return HC;
358 else if ( strModality.find("HD") < strModality.length()) return HD;
359 else if ( strModality.find("LP") < strModality.length()) return LP;
360 else if ( strModality.find("LS") < strModality.length()) return LS;
361 else if ( strModality.find("MA") < strModality.length()) return MA;
362 else if ( strModality.find("MR") < strModality.length()) return MR;
363 else if ( strModality.find("NM") < strModality.length()) return NM;
364 else if ( strModality.find("OT") < strModality.length()) return OT;
365 else if ( strModality.find("PT") < strModality.length()) return PT;
366 else if ( strModality.find("RF") < strModality.length()) return RF;
367 else if ( strModality.find("RG") < strModality.length()) return RG;
368 else if ( strModality.find("RTDOSE")
369 < strModality.length()) return RTDOSE;
370 else if ( strModality.find("RTIMAGE")
371 < strModality.length()) return RTIMAGE;
372 else if ( strModality.find("RTPLAN")
373 < strModality.length()) return RTPLAN;
374 else if ( strModality.find("RTSTRUCT")
375 < strModality.length()) return RTSTRUCT;
376 else if ( strModality.find("SM") < strModality.length()) return SM;
377 else if ( strModality.find("ST") < strModality.length()) return ST;
378 else if ( strModality.find("TG") < strModality.length()) return TG;
379 else if ( strModality.find("US") < strModality.length()) return US;
380 else if ( strModality.find("VF") < strModality.length()) return VF;
381 else if ( strModality.find("XA") < strModality.length()) return XA;
382 else if ( strModality.find("XC") < strModality.length()) return XC;
386 /// \todo throw error return value ???
387 /// specified <> unknown in our database
395 * \brief Retrieve the number of columns of image.
396 * @return The encountered size when found, 0 by default.
397 * 0 means the file is NOT USABLE. The caller will have to check
401 const std::string &strSize = GetEntryValue(0x0028,0x0011);
402 if ( strSize == GDCM_UNFOUND )
406 return atoi( strSize.c_str() );
410 * \brief Retrieve the number of lines of image.
411 * \warning The defaulted value is 1 as opposed to File::GetXSize()
412 * @return The encountered size when found, 1 by default
413 * (The ACR-NEMA file contains a Signal, not an Image).
417 const std::string &strSize = GetEntryValue(0x0028,0x0010);
418 if ( strSize != GDCM_UNFOUND )
420 return atoi( strSize.c_str() );
427 // The Rows (0028,0010) entry was optional for ACR/NEMA.
428 // (at least some images didn't have it.)
429 // It might hence be a signal (1D image). So we default to 1:
434 * \brief Retrieve the number of planes of volume or the number
435 * of frames of a multiframe.
436 * \warning When present we consider the "Number of Frames" as the third
437 * dimension. When missing we consider the third dimension as
438 * being the ACR-NEMA "Planes" tag content.
439 * @return The encountered size when found, 1 by default (single image).
443 // Both DicomV3 and ACR/Nema consider the "Number of Frames"
444 // as the third dimension.
445 const std::string &strSize = GetEntryValue(0x0028,0x0008);
446 if ( strSize != GDCM_UNFOUND )
448 return atoi( strSize.c_str() );
451 // We then consider the "Planes" entry as the third dimension
452 const std::string &strSize2 = GetEntryValue(0x0028,0x0012);
453 if ( strSize2 != GDCM_UNFOUND )
455 return atoi( strSize2.c_str() );
461 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
462 * then 0028,0030 : Pixel Spacing
464 * @return X dimension of a pixel
466 float File::GetXSpacing()
468 float xspacing = 1.0;
469 float yspacing = 1.0;
472 // To follow David Clunie's advice, we first check ImagerPixelSpacing
474 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
475 if ( strImagerPixelSpacing != GDCM_UNFOUND )
477 if ( ( nbValues = sscanf( strImagerPixelSpacing.c_str(),
478 "%f\\%f", &yspacing, &xspacing)) != 2 )
480 // if no values, xspacing is set to 1.0
483 // if single value is found, xspacing is defaulted to yspacing
487 if ( xspacing == 0.0 )
493 const std::string &strSpacing = GetEntryValue(0x0028,0x0030);
495 if ( strSpacing == GDCM_UNFOUND )
497 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
501 if ( ( nbValues = sscanf( strSpacing.c_str(),
502 "%f \\%f ", &yspacing, &xspacing)) != 2 )
504 // if no values, xspacing is set to 1.0
507 // if single value is found, xspacing is defaulted to yspacing
511 if ( xspacing == 0.0 )
516 // to avoid troubles with David Clunie's-like images (at least one)
517 if ( xspacing == 0.0 && yspacing == 0.0)
520 if ( xspacing == 0.0)
522 gdcmWarningMacro("gdcmData/CT-MONO2-8-abdo.dcm-like problem");
523 // seems to be a bug in the header ...
524 nbValues = sscanf( strSpacing.c_str(), "%f \\0\\%f ", &yspacing, &xspacing);
525 gdcmAssertMacro( nbValues == 2 );
532 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
533 * then from 0028,0030 : Pixel Spacing
535 * @return Y dimension of a pixel
537 float File::GetYSpacing()
539 float yspacing = 1.0;
541 // To follow David Clunie's advice, we first check ImagerPixelSpacing
543 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
544 if ( strImagerPixelSpacing != GDCM_UNFOUND )
546 nbValues = sscanf( strImagerPixelSpacing.c_str(), "%f", &yspacing);
548 // if sscanf cannot read any float value, it won't affect yspacing
552 if ( yspacing == 0.0 )
558 std::string strSpacing = GetEntryValue(0x0028,0x0030);
559 if ( strSpacing == GDCM_UNFOUND )
561 gdcmWarningMacro("Unfound Pixel Spacing (0028,0030)");
565 // if sscanf cannot read any float value, it won't affect yspacing
566 nbValues = sscanf( strSpacing.c_str(), "%f", &yspacing);
568 // if no values, yspacing is set to 1.0
572 if ( yspacing == 0.0 )
579 * \brief gets the info from 0018,0088 : Space Between Slices
580 * else from 0018,0050 : Slice Thickness
582 * @return Z dimension of a voxel-to be
584 float File::GetZSpacing()
586 // Spacing Between Slices : distance between the middle of 2 slices
588 // jointives (Spacing between Slices = Slice Thickness)
589 // overlapping (Spacing between Slices < Slice Thickness)
590 // disjointes (Spacing between Slices > Slice Thickness)
591 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
592 // It only concerns the MRI guys, not people wanting to visualize volumes
593 // If Spacing Between Slices is missing,
594 // we suppose slices joint together
601 // For *Dicom* images, ZSpacing should be calculated using
602 // XOrigin, YOrigin, ZOrigin (of the top left image corner)
603 // of 2 consecutive images, and the Orientation
605 // Computing ZSpacing on a single image is not really meaningfull !
607 const std::string &strSpacingBSlices = GetEntryValue(0x0018,0x0088);
609 if ( strSpacingBSlices == GDCM_UNFOUND )
611 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
612 const std::string &strSliceThickness = GetEntryValue(0x0018,0x0050);
613 if ( strSliceThickness == GDCM_UNFOUND )
615 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
620 // if no 'Spacing Between Slices' is found,
621 // we assume slices join together
622 // (no overlapping, no interslice gap)
623 // if they don't, we're fucked up
624 return (float)atof( strSliceThickness.c_str() );
629 float zsp = (float)atof( strSpacingBSlices.c_str());
630 if (zsp == 0.0) // last change not to break further computations ...
636 * \brief gets the info from 0020,0032 : Image Position Patient
637 * else from 0020,0030 : Image Position (RET)
639 * @return up-left image corner X position
641 float File::GetXOrigin()
643 float xImPos, yImPos, zImPos;
644 std::string strImPos = GetEntryValue(0x0020,0x0032);
646 if ( strImPos == GDCM_UNFOUND )
648 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
649 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
650 if ( strImPos == GDCM_UNFOUND )
652 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
657 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
666 * \brief gets the info from 0020,0032 : Image Position Patient
667 * else from 0020,0030 : Image Position (RET)
669 * @return up-left image corner Y position
671 float File::GetYOrigin()
673 float xImPos, yImPos, zImPos;
674 std::string strImPos = GetEntryValue(0x0020,0x0032);
676 if ( strImPos == GDCM_UNFOUND)
678 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
679 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
680 if ( strImPos == GDCM_UNFOUND )
682 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
687 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
696 * \brief gets the info from 0020,0032 : Image Position Patient
697 * else from 0020,0030 : Image Position (RET)
698 * else from 0020,1041 : Slice Location
699 * else from 0020,0050 : Location
701 * @return up-left image corner Z position
703 float File::GetZOrigin()
705 float xImPos, yImPos, zImPos;
706 std::string strImPos = GetEntryValue(0x0020,0x0032);
708 if ( strImPos != GDCM_UNFOUND )
710 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3)
712 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
713 return 0.; // bug in the element 0x0020,0x0032
721 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
722 if ( strImPos != GDCM_UNFOUND )
724 if ( sscanf( strImPos.c_str(),
725 "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos ) != 3 )
727 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
728 return 0.; // bug in the element 0x0020,0x0032
736 // for *very* old ACR-NEMA images
737 std::string strSliceLocation = GetEntryValue(0x0020,0x1041);
738 if ( strSliceLocation != GDCM_UNFOUND )
740 if ( sscanf( strSliceLocation.c_str(), "%f ", &zImPos) != 1)
742 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
743 return 0.; // bug in the element 0x0020,0x1041
750 gdcmWarningMacro( "Unfound Slice Location (0020,1041)");
752 std::string strLocation = GetEntryValue(0x0020,0x0050);
753 if ( strLocation != GDCM_UNFOUND )
755 if ( sscanf( strLocation.c_str(), "%f ", &zImPos) != 1 )
757 gdcmWarningMacro( "Wrong Location (0020,0050)");
758 return 0.; // bug in the element 0x0020,0x0050
765 gdcmWarningMacro( "Unfound Location (0020,0050)");
767 return 0.; // Hopeless
771 * \brief gets the info from 0020,0037 : Image Orientation Patient
772 * or from 0020 0035 : Image Orientation (RET)
773 * (needed to organize DICOM files based on their x,y,z position)
774 * @param iop adress of the (6)float array to receive values
775 * @return true when one of the tag is found
776 * false when nothing is found
778 bool File::GetImageOrientationPatient( float iop[6] )
780 std::string strImOriPat;
781 //iop is supposed to be float[6]
782 iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
784 // 0020 0037 DS REL Image Orientation (Patient)
785 if ( (strImOriPat = GetEntryValue(0x0020,0x0037)) != GDCM_UNFOUND )
787 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
788 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
790 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
791 << " Less than 6 values were found." );
796 // 0020 0035 DS REL Image Orientation (RET)
797 else if ( (strImOriPat = GetEntryValue(0x0020,0x0035)) != GDCM_UNFOUND )
799 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
800 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
802 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
803 << "Less than 6 values were found." );
813 * \brief Retrieve the number of Bits Stored (actually used)
814 * (as opposed to number of Bits Allocated)
815 * @return The encountered number of Bits Stored, 0 by default.
816 * 0 means the file is NOT USABLE. The caller has to check it !
818 int File::GetBitsStored()
820 std::string strSize = GetEntryValue( 0x0028, 0x0101 );
821 if ( strSize == GDCM_UNFOUND )
823 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
824 return 0; // It's supposed to be mandatory
825 // the caller will have to check
827 return atoi( strSize.c_str() );
831 * \brief Retrieve the number of Bits Allocated
832 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
833 * @return The encountered Number of Bits Allocated, 0 by default.
834 * 0 means the file is NOT USABLE. The caller has to check it !
836 int File::GetBitsAllocated()
838 std::string strSize = GetEntryValue(0x0028,0x0100);
839 if ( strSize == GDCM_UNFOUND )
841 gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
842 return 0; // It's supposed to be mandatory
843 // the caller will have to check
845 return atoi( strSize.c_str() );
849 * \brief Retrieve the high bit position.
850 * \warning The method defaults to 0 when information is missing.
851 * The responsability of checking this value is left to the caller.
852 * @return The high bit position when present. 0 when missing.
854 int File::GetHighBitPosition()
856 std::string strSize = GetEntryValue( 0x0028, 0x0102 );
857 if ( strSize == GDCM_UNFOUND )
859 gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
862 return atoi( strSize.c_str() );
866 * \brief Retrieve the number of Samples Per Pixel
867 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
868 * @return The encountered number of Samples Per Pixel, 1 by default.
869 * (we assume Gray level Pixels)
871 int File::GetSamplesPerPixel()
873 const std::string &strSize = GetEntryValue(0x0028,0x0002);
874 if ( strSize == GDCM_UNFOUND )
876 gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
877 return 1; // Well, it's supposed to be mandatory ...
878 // but sometimes it's missing : *we* assume Gray pixels
880 return atoi( strSize.c_str() );
884 * \brief Retrieve the Planar Configuration for RGB images
885 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
886 * @return The encountered Planar Configuration, 0 by default.
888 int File::GetPlanarConfiguration()
890 std::string strSize = GetEntryValue(0x0028,0x0006);
891 if ( strSize == GDCM_UNFOUND )
893 gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
896 return atoi( strSize.c_str() );
900 * \brief Return the size (in bytes) of a single pixel of data.
901 * @return The size in bytes of a single pixel of data; 0 by default
902 * 0 means the file is NOT USABLE; the caller will have to check
904 int File::GetPixelSize()
906 // 0028 0100 US IMG Bits Allocated
907 // (in order no to be messed up by old ACR-NEMA RGB images)
908 // if (File::GetEntryValue(0x0028,0x0100) == "24")
910 assert( !(GetEntryValue(0x0028,0x0100) == "24") );
912 std::string pixelType = GetPixelType();
913 if ( pixelType == "8U" || pixelType == "8S" )
917 if ( pixelType == "16U" || pixelType == "16S")
921 if ( pixelType == "32U" || pixelType == "32S")
925 if ( pixelType == "FD" )
929 gdcmWarningMacro( "Unknown pixel type");
934 * \brief Build the Pixel Type of the image.
935 * Possible values are:
936 * - 8U unsigned 8 bit,
938 * - 16U unsigned 16 bit,
939 * - 16S signed 16 bit,
940 * - 32U unsigned 32 bit,
941 * - 32S signed 32 bit,
942 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
943 * \warning 12 bit images appear as 16 bit.
944 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
945 * + Planar Configuration = 0
946 * @return 0S if nothing found. NOT USABLE file. The caller has to check
948 std::string File::GetPixelType()
950 std::string bitsAlloc = GetEntryValue(0x0028, 0x0100); // Bits Allocated
951 if ( bitsAlloc == GDCM_UNFOUND )
953 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
954 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
957 if ( bitsAlloc == "64" )
961 else if ( bitsAlloc == "12" )
963 // It will be unpacked
966 else if ( bitsAlloc == "24" )
968 // (in order no to be messed up by old RGB images)
972 std::string sign = GetEntryValue(0x0028, 0x0103);//"Pixel Representation"
974 if (sign == GDCM_UNFOUND )
976 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
977 sign = "U"; // default and arbitrary value, not to polute the output
979 else if ( sign == "0" )
987 return bitsAlloc + sign;
991 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
992 * \warning The method defaults to false (UNsigned) when tag 0028|0103
994 * The responsability of checking this value is left to the caller
995 * (NO transformation is performed on the pixels to make then >0)
996 * @return True when signed, false when UNsigned
998 bool File::IsSignedPixelData()
1000 std::string strSign = GetEntryValue( 0x0028, 0x0103 );
1001 if ( strSign == GDCM_UNFOUND )
1003 gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
1006 int sign = atoi( strSign.c_str() );
1015 * \brief Check whether this a monochrome picture (gray levels) or not,
1016 * using "Photometric Interpretation" tag (0x0028,0x0004).
1017 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1019 bool File::IsMonochrome()
1021 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1022 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1023 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1027 if ( PhotometricInterp == GDCM_UNFOUND )
1029 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1035 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1036 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1037 * @return true when "MONOCHROME1" . False otherwise.
1039 bool File::IsMonochrome1()
1041 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1042 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1046 if ( PhotometricInterp == GDCM_UNFOUND )
1048 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1054 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1055 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1056 * @return true when "PALETTE COLOR". False otherwise.
1058 bool File::IsPaletteColor()
1060 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1061 if ( PhotometricInterp == "PALETTE COLOR " )
1065 if ( PhotometricInterp == GDCM_UNFOUND )
1067 gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1073 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1074 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1075 * @return true when "YBR_FULL". False otherwise.
1077 bool File::IsYBRFull()
1079 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1080 if ( PhotometricInterp == "YBR_FULL" )
1084 if ( PhotometricInterp == GDCM_UNFOUND )
1086 gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1092 * \brief tells us if LUT are used
1093 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1094 * are NOT considered as LUT, since nobody knows
1095 * how to deal with them
1096 * Please warn me if you know sbdy that *does* know ... jprx
1097 * @return true if LUT Descriptors and LUT Tables were found
1101 // Check the presence of the LUT Descriptors, and LUT Tables
1103 if ( !GetDocEntry(0x0028,0x1101) )
1107 // LutDescriptorGreen
1108 if ( !GetDocEntry(0x0028,0x1102) )
1112 // LutDescriptorBlue
1113 if ( !GetDocEntry(0x0028,0x1103) )
1117 // Red Palette Color Lookup Table Data
1118 if ( !GetDocEntry(0x0028,0x1201) )
1122 // Green Palette Color Lookup Table Data
1123 if ( !GetDocEntry(0x0028,0x1202) )
1127 // Blue Palette Color Lookup Table Data
1128 if ( !GetDocEntry(0x0028,0x1203) )
1133 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1134 // NOT taken into account, but we don't know how to use it ...
1139 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1141 * @return Lookup Table number of Bits , 0 by default
1142 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1143 * @ return bit number of each LUT item
1145 int File::GetLUTNbits()
1147 std::vector<std::string> tokens;
1150 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1151 // = Lookup Table Desc-Blue
1152 // Consistency already checked in GetLUTLength
1153 std::string lutDescription = GetEntryValue(0x0028,0x1101);
1154 if ( lutDescription == GDCM_UNFOUND )
1159 tokens.clear(); // clean any previous value
1160 Util::Tokenize ( lutDescription, tokens, "\\" );
1161 //LutLength=atoi(tokens[0].c_str());
1162 //LutDepth=atoi(tokens[1].c_str());
1164 lutNbits = atoi( tokens[2].c_str() );
1171 *\brief gets the info from 0028,1052 : Rescale Intercept
1172 * @return Rescale Intercept
1174 float File::GetRescaleIntercept()
1176 float resInter = 0.;
1177 /// 0028 1052 DS IMG Rescale Intercept
1178 const std::string &strRescInter = GetEntryValue(0x0028,0x1052);
1179 if ( strRescInter != GDCM_UNFOUND )
1181 if ( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1183 // bug in the element 0x0028,0x1052
1184 gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1192 *\brief gets the info from 0028,1053 : Rescale Slope
1193 * @return Rescale Slope
1195 float File::GetRescaleSlope()
1197 float resSlope = 1.;
1198 //0028 1053 DS IMG Rescale Slope
1199 std::string strRescSlope = GetEntryValue(0x0028,0x1053);
1200 if ( strRescSlope != GDCM_UNFOUND )
1202 if ( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1 )
1204 // bug in the element 0x0028,0x1053
1205 gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1213 * \brief This function is intended to user who doesn't want
1214 * to have to manage a LUT and expects to get an RBG Pixel image
1215 * (or a monochrome one ...)
1216 * \warning to be used with GetImagePixels()
1217 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1219 int File::GetNumberOfScalarComponents()
1221 if ( GetSamplesPerPixel() == 3 )
1226 // 0028 0100 US IMG Bits Allocated
1227 // (in order no to be messed up by old RGB images)
1228 if ( GetEntryValue(0x0028,0x0100) == "24" )
1233 std::string strPhotometricInterpretation = GetEntryValue(0x0028,0x0004);
1235 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1237 if ( HasLUT() )// PALETTE COLOR is NOT enough
1247 // beware of trailing space at end of string
1248 // DICOM tags are never of odd length
1249 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1250 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1251 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1257 // we assume that *all* kinds of YBR are dealt with
1263 * \brief This function is intended to user that DOESN'T want
1264 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1265 * - the (vtk) user is supposed to know how deal with LUTs -
1266 * \warning to be used with GetImagePixelsRaw()
1267 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1269 int File::GetNumberOfScalarComponentsRaw()
1271 // 0028 0100 US IMG Bits Allocated
1272 // (in order no to be messed up by old RGB images)
1273 if ( File::GetEntryValue(0x0028,0x0100) == "24" )
1278 // we assume that *all* kinds of YBR are dealt with
1279 return GetSamplesPerPixel();
1283 * \brief Recover the offset (from the beginning of the file)
1284 * of *image* pixels (not *icone image* pixels, if any !)
1285 * @return Pixel Offset
1287 size_t File::GetPixelOffset()
1289 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1292 return pxlElement->GetOffset();
1296 gdcmDebugMacro( "Big trouble : Pixel Element ("
1297 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1303 * \brief Recover the pixel area length (in Bytes)
1304 * @return Pixel Element Length, as stored in the header
1305 * (NOT the memory space necessary to hold the Pixels
1306 * -in case of embeded compressed image-)
1307 * 0 : NOT USABLE file. The caller has to check.
1309 size_t File::GetPixelAreaLength()
1311 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1314 return pxlElement->GetLength();
1318 gdcmDebugMacro( "Big trouble : Pixel Element ("
1319 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1325 * \brief Adds the characteristics of a new element we want to anonymize
1326 * @param group Group number of the target tag.
1327 * @param elem Element number of the target tag.
1328 * @param value new value (string) to substitute with
1330 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1331 std::string const &value)
1337 UserAnonymizeList.push_back(el);
1341 * \brief Overwrites in the file the values of the DicomElements
1344 void File::AnonymizeNoLoad()
1346 std::fstream *fp = new std::fstream(Filename.c_str(),
1347 std::ios::in | std::ios::out | std::ios::binary);
1351 uint32_t valLgth = 0;
1352 std::string *spaces;
1353 for (ListElements::iterator it = UserAnonymizeList.begin();
1354 it != UserAnonymizeList.end();
1357 d = GetDocEntry( (*it).Group, (*it).Elem);
1362 if ( dynamic_cast<SeqEntry *>(d) )
1364 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1368 offset = d->GetOffset();
1369 lgth = d->GetLength();
1372 spaces = new std::string( lgth-valLgth, ' ');
1373 (*it).Value = (*it).Value + *spaces;
1376 fp->seekp( offset, std::ios::beg );
1377 fp->write( (*it).Value.c_str(), lgth );
1385 * \brief anonymize a File (remove Patient's personal info passed with
1386 * AddAnonymizeElement()
1387 * \note You cannot Anonymize a BinEntry (to be fixed)
1389 bool File::AnonymizeFile()
1391 // If Anonymisation list is empty, let's perform some basic anonymization
1392 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1394 // If exist, replace by spaces
1395 SetValEntry (" ",0x0010, 0x2154); // Telephone
1396 SetValEntry (" ",0x0010, 0x1040); // Adress
1397 SetValEntry (" ",0x0010, 0x0020); // Patient ID
1399 DocEntry* patientNameHE = GetDocEntry (0x0010, 0x0010);
1401 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1403 std::string studyInstanceUID = GetEntryValue (0x0020, 0x000d);
1404 if ( studyInstanceUID != GDCM_UNFOUND )
1406 SetValEntry(studyInstanceUID, 0x0010, 0x0010);
1410 SetValEntry("anonymized", 0x0010, 0x0010);
1417 for (ListElements::iterator it = UserAnonymizeList.begin();
1418 it != UserAnonymizeList.end();
1421 d = GetDocEntry( (*it).Group, (*it).Elem);
1426 if ( dynamic_cast<SeqEntry *>(d) )
1428 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1432 if ( dynamic_cast<BinEntry *>(d) )
1434 gdcmWarningMacro( "To 'Anonymize' a BinEntry, better use AnonymizeNoLoad (FIXME) ");
1438 SetValEntry ((*it).Value, (*it).Group, (*it).Elem);
1442 // In order to make definitively impossible any further identification
1443 // remove or replace all the stuff that contains a Date
1445 //0008 0012 DA ID Instance Creation Date
1446 //0008 0020 DA ID Study Date
1447 //0008 0021 DA ID Series Date
1448 //0008 0022 DA ID Acquisition Date
1449 //0008 0023 DA ID Content Date
1450 //0008 0024 DA ID Overlay Date
1451 //0008 0025 DA ID Curve Date
1452 //0008 002a DT ID Acquisition Datetime
1453 //0018 9074 DT ACQ Frame Acquisition Datetime
1454 //0018 9151 DT ACQ Frame Reference Datetime
1455 //0018 a002 DT ACQ Contribution Date Time
1456 //0020 3403 SH REL Modified Image Date (RET)
1457 //0032 0032 DA SDY Study Verified Date
1458 //0032 0034 DA SDY Study Read Date
1459 //0032 1000 DA SDY Scheduled Study Start Date
1460 //0032 1010 DA SDY Scheduled Study Stop Date
1461 //0032 1040 DA SDY Study Arrival Date
1462 //0032 1050 DA SDY Study Completion Date
1463 //0038 001a DA VIS Scheduled Admission Date
1464 //0038 001c DA VIS Scheduled Discharge Date
1465 //0038 0020 DA VIS Admitting Date
1466 //0038 0030 DA VIS Discharge Date
1467 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1468 //0040 0004 DA PRC Scheduled Procedure Step End Date
1469 //0040 0244 DA PRC Performed Procedure Step Start Date
1470 //0040 0250 DA PRC Performed Procedure Step End Date
1471 //0040 2004 DA PRC Issue Date of Imaging Service Request
1472 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1473 //0040 4011 DT PRC Expected Completion Date and Time
1474 //0040 a030 DT PRC Verification Date Time
1475 //0040 a032 DT PRC Observation Date Time
1476 //0040 a120 DT PRC DateTime
1477 //0040 a121 DA PRC Date
1478 //0040 a13a DT PRC Referenced Datetime
1479 //0070 0082 DA ??? Presentation Creation Date
1480 //0100 0420 DT ??? SOP Autorization Date and Time
1481 //0400 0105 DT ??? Digital Signature DateTime
1482 //2100 0040 DA PJ Creation Date
1483 //3006 0008 DA SSET Structure Set Date
1484 //3008 0024 DA ??? Treatment Control Point Date
1485 //3008 0054 DA ??? First Treatment Date
1486 //3008 0056 DA ??? Most Recent Treatment Date
1487 //3008 0162 DA ??? Safe Position Exit Date
1488 //3008 0166 DA ??? Safe Position Return Date
1489 //3008 0250 DA ??? Treatment Date
1490 //300a 0006 DA RT RT Plan Date
1491 //300a 022c DA RT Air Kerma Rate Reference Date
1492 //300e 0004 DA RT Review Date
1498 * \brief Performs some consistency checking on various 'File related'
1499 * (as opposed to 'DicomDir related') entries
1500 * then writes in a file all the (Dicom Elements) included the Pixels
1501 * @param fileName file name to write to
1502 * @param writetype type of the file to be written
1503 * (ACR, ExplicitVR, ImplicitVR)
1505 bool File::Write(std::string fileName, FileType writetype)
1507 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1508 std::ios::out | std::ios::binary);
1511 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1515 // Entry : 0002|0000 = group length -> recalculated
1516 ValEntry*e0000 = GetValEntry(0x0002,0x0000);
1519 std::ostringstream sLen;
1520 sLen << ComputeGroup0002Length( );
1521 e0000->SetValue(sLen.str());
1524 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1527 // no (GrPixel, NumPixel) element
1528 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1529 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1530 InsertValEntry(s_lgPix,GrPixel, 0x0000);
1533 Document::WriteContent(fp, writetype);
1541 //-----------------------------------------------------------------------------
1545 //-----------------------------------------------------------------------------
1548 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1549 * Compute the RLE extra information and store it in \ref RLEInfo
1550 * for later pixel retrieval usage.
1552 void File::ComputeRLEInfo()
1554 std::string ts = GetTransferSyntax();
1555 if ( !Global::GetTS()->IsRLELossless(ts) )
1560 // Encoded pixel data: for the time being we are only concerned with
1561 // Jpeg or RLE Pixel data encodings.
1562 // As stated in PS 3.5-2003, section 8.2 p44:
1563 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1564 // value representation OB is used".
1565 // Hence we expect an OB value representation. Concerning OB VR,
1566 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1567 // "For the Value Representations OB and OW, the encoding shall meet the
1568 // following specifications depending on the Data element tag:"
1570 // - the first item in the sequence of items before the encoded pixel
1571 // data stream shall be basic offset table item. The basic offset table
1572 // item value, however, is not required to be present"
1573 ReadEncapsulatedBasicOffsetTable();
1575 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1576 // Loop on the individual frame[s] and store the information
1577 // on the RLE fragments in a RLEFramesInfo.
1578 // Note: - when only a single frame is present, this is a
1580 // - when more than one frame are present, then we are in
1581 // the case of a multi-frame image.
1585 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1587 // Since we have read the basic offset table, let's check the value were correct
1588 // or else produce a warning:
1589 if ( BasicOffsetTableItemValue )
1591 // If a BasicOffsetTableItemValue was read
1592 uint32_t individualLength = BasicOffsetTableItemValue[i];
1593 assert( individualLength == sum ); // REMOVE that if this is a problem
1594 if( individualLength != sum )
1596 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1598 sum += frameLength + 8;
1601 // Parse the RLE Header and store the corresponding RLE Segment
1602 // Offset Table information on fragments of this current Frame.
1603 // Note that the fragment pixels themselves are not loaded
1604 // (but just skipped).
1605 long frameOffset = Fp->tellg();
1607 uint32_t nbRleSegments = ReadInt32();
1608 if ( nbRleSegments > 16 )
1610 // There should be at most 15 segments (refer to RLEFrame class)
1611 gdcmWarningMacro( "Too many segments.");
1614 uint32_t rleSegmentOffsetTable[16];
1615 for( int k = 1; k <= 15; k++ )
1617 rleSegmentOffsetTable[k] = ReadInt32();
1620 // Deduce from both RLE Header and frameLength
1621 // the fragment length, and again store this info
1622 // in a RLEFramesInfo.
1623 long rleSegmentLength[15];
1624 // skipping (not reading) RLE Segments
1625 if ( nbRleSegments > 1)
1627 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1629 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1630 - rleSegmentOffsetTable[k];
1631 SkipBytes(rleSegmentLength[k]);
1635 rleSegmentLength[nbRleSegments] = frameLength
1636 - rleSegmentOffsetTable[nbRleSegments];
1637 SkipBytes(rleSegmentLength[nbRleSegments]);
1639 // Store the collected info
1640 RLEFrame *newFrame = new RLEFrame;
1641 newFrame->SetNumberOfFragments(nbRleSegments);
1642 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1644 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1645 newFrame->SetLength(uk,rleSegmentLength[uk]);
1647 RLEInfo->AddFrame(newFrame);
1650 // Make sure that we encounter a 'Sequence Delimiter Item'
1651 // at the end of the item :
1652 if ( !ReadTag(0xfffe, 0xe0dd) )
1654 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1659 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1660 * Compute the jpeg extra information (fragment[s] offset[s] and
1661 * length) and store it[them] in \ref JPEGInfo for later pixel
1664 void File::ComputeJPEGFragmentInfo()
1666 // If you need to, look for comments of ComputeRLEInfo().
1667 std::string ts = GetTransferSyntax();
1668 if ( ! Global::GetTS()->IsJPEG(ts) )
1673 ReadEncapsulatedBasicOffsetTable();
1675 // Loop on the fragments[s] and store the parsed information in a
1677 long fragmentLength;
1680 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1682 // Since we have read the basic offset table, let's check the value were correct
1683 // or else produce a warning:
1684 // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1685 // When the Item Value is present, the Basic Offset Table Item Value shall contain
1686 // concatenated 32-bit unsigned integer values that are byte offsets to the first
1687 // byte of the Item Tag of the first fragment for each frame in the Sequence of
1688 // Items. These offsets are measured from the first byte of the first Item Tag
1689 // following the Basic Offset Table item (See Table A.4-2).
1691 if ( BasicOffsetTableItemValue )
1693 // If a BasicOffsetTableItemValue was read
1694 uint32_t individualLength = BasicOffsetTableItemValue[i];
1695 //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1696 if( individualLength != sum )
1698 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1699 individualLength << " != " << sum );
1701 sum += fragmentLength + 8;
1705 long fragmentOffset = Fp->tellg();
1706 // Store the collected info
1707 JPEGFragment *newFragment = new JPEGFragment;
1708 newFragment->SetOffset(fragmentOffset);
1709 newFragment->SetLength(fragmentLength);
1710 JPEGInfo->AddFragment(newFragment);
1712 SkipBytes(fragmentLength);
1715 // Make sure that we encounter a 'Sequence Delimiter Item'
1716 // at the end of the item :
1717 if ( !ReadTag(0xfffe, 0xe0dd) )
1719 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1724 * \brief Assuming the internal file pointer \ref Document::Fp
1725 * is placed at the beginning of a tag check whether this
1726 * tag is (TestGroup, TestElem).
1727 * \warning On success the internal file pointer \ref Document::Fp
1728 * is modified to point after the tag.
1729 * On failure (i.e. when the tag wasn't the expected tag
1730 * (TestGroup, TestElem) the internal file pointer
1731 * \ref Document::Fp is restored to it's original position.
1732 * @param testGroup The expected group of the tag.
1733 * @param testElem The expected Element of the tag.
1734 * @return True on success, false otherwise.
1736 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1738 long positionOnEntry = Fp->tellg();
1739 long currentPosition = Fp->tellg(); // On debugging purposes
1741 // Read the Item Tag group and element, and make
1742 // sure they are what we expected:
1743 uint16_t itemTagGroup;
1744 uint16_t itemTagElem;
1747 itemTagGroup = ReadInt16();
1748 itemTagElem = ReadInt16();
1750 catch ( FormatError /*e*/ )
1752 //std::cerr << e << std::endl;
1755 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1757 gdcmWarningMacro( "Wrong Item Tag found:"
1758 << " We should have found tag ("
1759 << std::hex << testGroup << "," << testElem << ")" << std::endl
1760 << " but instead we encountered tag ("
1761 << std::hex << itemTagGroup << "," << itemTagElem << ")"
1762 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
1764 Fp->seekg(positionOnEntry, std::ios::beg);
1772 * \brief Assuming the internal file pointer \ref Document::Fp
1773 * is placed at the beginning of a tag (TestGroup, TestElement),
1774 * read the length associated to the Tag.
1775 * \warning On success the internal file pointer \ref Document::Fp
1776 * is modified to point after the tag and it's length.
1777 * On failure (i.e. when the tag wasn't the expected tag
1778 * (TestGroup, TestElement) the internal file pointer
1779 * \ref Document::Fp is restored to it's original position.
1780 * @param testGroup The expected Group of the tag.
1781 * @param testElem The expected Element of the tag.
1782 * @return On success returns the length associated to the tag. On failure
1785 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1788 if ( !ReadTag(testGroup, testElem) )
1793 //// Then read the associated Item Length
1794 long currentPosition = Fp->tellg();
1795 uint32_t itemLength = ReadInt32();
1797 gdcmWarningMacro( "Basic Item Length is: "
1798 << itemLength << std::endl
1799 << " at address: " << std::hex << (unsigned int)currentPosition);
1805 * \brief When parsing the Pixel Data of an encapsulated file, read
1806 * the basic offset table (when present, and BTW dump it).
1808 void File::ReadEncapsulatedBasicOffsetTable()
1810 //// Read the Basic Offset Table Item Tag length...
1811 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1813 // When present, read the basic offset table itself.
1814 // Notes: - since the presence of this basic offset table is optional
1815 // we can't rely on it for the implementation, and we will simply
1816 // trash it's content (when present).
1817 // - still, when present, we could add some further checks on the
1818 // lengths, but we won't bother with such fuses for the time being.
1819 if ( itemLength != 0 )
1821 char *charBasicOffsetTableItemValue = new char[itemLength];
1822 Fp->read(charBasicOffsetTableItemValue, itemLength);
1823 unsigned int nbEntries = itemLength/4;
1824 assert( nbEntries*4 == itemLength); // Make sure this is a multiple
1825 BasicOffsetTableItemValue = new uint32_t[nbEntries];
1827 for (unsigned int i=0; i < nbEntries; i++ )
1829 BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
1830 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1831 uint32_t val = BasicOffsetTableItemValue[i];
1832 BasicOffsetTableItemValue[i]
1833 = ( (val<<24) | ((val<<8) & 0x00ff0000) |
1834 ((val>>8) & 0x0000ff00) | (val>>24) );
1836 gdcmWarningMacro( "Read one length for: " <<
1837 std::hex << BasicOffsetTableItemValue[i] );
1840 delete[] charBasicOffsetTableItemValue;
1844 // These are the deprecated method that one day should be removed (after the next release)
1846 #ifndef GDCM_LEGACY_REMOVE
1848 * \brief Constructor (DEPRECATED : temporaryly kept not to break the API)
1849 * @param filename name of the file whose header we want to analyze
1850 * @deprecated do not use any longer
1852 File::File( std::string const &filename )
1855 RLEInfo = new RLEFramesInfo;
1856 JPEGInfo = new JPEGFragmentsInfo;
1858 SetFileName( filename );
1859 Load( ); // gdcm::Document is first Loaded, then the 'File part'
1863 * \brief Loader. (DEPRECATED : temporaryly kept not to break the API)
1864 * @param fileName file to be open for parsing
1865 * @return false if file cannot be open or no swap info was found,
1866 * or no tag was found.
1867 * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1869 bool File::Load( std::string const &fileName )
1871 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1873 SetFileName( fileName );
1874 if ( ! this->Document::Load( ) )
1877 return DoTheLoadingJob( );
1881 //-----------------------------------------------------------------------------
1884 //-----------------------------------------------------------------------------
1885 } // end namespace gdcm