]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
Bug fix in Load method.
[gdcm.git] / src / gdcmFile.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/06/10 14:05:37 $
7   Version:   $Revision: 1.242 $
8                                                                                 
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.
12                                                                                 
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.
16                                                                                 
17 =========================================================================*/
18
19 //
20 // --------------  Remember ! ----------------------------------
21 //
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
28 //
29 // ---------------------------------------------------------------
30 //
31 #include "gdcmFile.h"
32 #include "gdcmGlobal.h"
33 #include "gdcmUtil.h"
34 #include "gdcmDebug.h"
35 #include "gdcmTS.h"
36 #include "gdcmValEntry.h"
37 #include "gdcmBinEntry.h"
38 #include "gdcmSeqEntry.h"
39 #include "gdcmRLEFramesInfo.h"
40 #include "gdcmJPEGFragmentsInfo.h"
41
42 #include <stdio.h> //sscanf
43 #include <vector>
44
45 namespace gdcm 
46 {
47 //-----------------------------------------------------------------------------
48 // Constructor / Destructor
49
50 /**
51  * \brief Constructor used when we want to generate dicom files from scratch
52  */
53 File::File():
54    Document()
55 {
56    RLEInfo  = new RLEFramesInfo;
57    JPEGInfo = new JPEGFragmentsInfo;
58    GrPixel  = 0x7fe0;  // to avoid further troubles
59    NumPixel = 0x0010;
60 }
61
62 /**
63  * \brief  Constructor 
64  * @param  filename name of the file whose header we want to analyze
65  */
66 File::File( std::string const &filename )
67      :Document(filename)
68 {    
69    RLEInfo  = new RLEFramesInfo;
70    JPEGInfo = new JPEGFragmentsInfo;
71
72    Load( filename );
73 }
74
75 /**
76  * \brief   Canonical destructor.
77  */
78 File::~File ()
79 {
80    if( RLEInfo )
81       delete RLEInfo;
82    if( JPEGInfo )
83       delete JPEGInfo;
84 }
85
86 //-----------------------------------------------------------------------------
87 // Public
88
89 /**
90  * \brief   Loader  
91  * @param   fileName file to be open for parsing
92  * @return false if file cannot be open or no swap info was found,
93  *         or no tag was found.
94  */
95 bool File::Load( std::string const &fileName ) 
96 {
97    this->Document::Load( fileName );
98
99    // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
100    // We may encounter the 'RETired' (0x0028, 0x0200) tag
101    // (Image Location") . This entry contains the number of
102    // the group that contains the pixel data (hence the "Pixel Data"
103    // is found by indirection through the "Image Location").
104    // Inside the group pointed by "Image Location" the searched element
105    // is conventionally the element 0x0010 (when the norm is respected).
106    // When the "Image Location" is missing we default to group 0x7fe0.
107    // Note: this IS the right place for the code
108  
109    // Image Location
110    const std::string &imgLocation = GetEntryValue(0x0028, 0x0200);
111    if ( imgLocation == GDCM_UNFOUND )
112    {
113       // default value
114       GrPixel = 0x7fe0;
115    }
116    else
117    {
118       GrPixel = (uint16_t) atoi( imgLocation.c_str() );
119    }   
120
121    // sometimes Image Location value doesn't follow
122    // the supposed processor endianness.
123    // see gdcmData/cr172241.dcm
124    if ( GrPixel == 0xe07f )
125    {
126       GrPixel = 0x7fe0;
127    }
128
129    if ( GrPixel != 0x7fe0 )
130    {
131       // This is a kludge for old dirty Philips imager.
132       NumPixel = 0x1010;
133    }
134    else
135    {
136       NumPixel = 0x0010;
137    }
138
139    // Now, we know GrPixel and NumPixel.
140    // Let's create a VirtualDictEntry to allow a further VR modification
141    // and force VR to match with BitsAllocated.
142    DocEntry *entry = GetDocEntry(GrPixel, NumPixel); 
143    if ( entry != 0 )
144    {
145       // Compute the RLE or JPEG info
146       OpenFile();
147       const std::string &ts = GetTransferSyntax();
148       Fp->seekg( entry->GetOffset(), std::ios::beg );
149       if ( Global::GetTS()->IsRLELossless(ts) ) 
150          ComputeRLEInfo();
151       else if ( Global::GetTS()->IsJPEG(ts) )
152          ComputeJPEGFragmentInfo();
153       CloseFile();
154
155       // Create a new BinEntry to change the DictEntry
156       // The changed DictEntry will have 
157       // - a correct PixelVR OB or OW)
158       // - the name to "Pixel Data"
159       BinEntry *oldEntry = dynamic_cast<BinEntry *>(entry);
160       if(oldEntry)
161       {
162          std::string PixelVR;
163          // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
164          // more than 8 (i.e 12, 16) is a 'O Words'
165          if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 ) 
166             PixelVR = "OB";
167          else
168             PixelVR = "OW";
169
170          // Change only made if usefull
171          if( PixelVR != oldEntry->GetVR() )
172          {
173             DictEntry* newDict = NewVirtualDictEntry(GrPixel,NumPixel,
174                                                      PixelVR,"1","Pixel Data");
175
176             BinEntry *newEntry = new BinEntry(newDict);
177             newEntry->Copy(entry);
178             newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
179             oldEntry->SetSelfArea(false);
180
181             RemoveEntry(oldEntry);
182             AddEntry(newEntry);
183          }
184       }
185    }
186    return true;
187 }
188 /**
189  * \brief  This predicate, based on hopefully reasonable heuristics,
190  *         decides whether or not the current File was properly parsed
191  *         and contains the mandatory information for being considered as
192  *         a well formed and usable Dicom/Acr File.
193  * @return true when File is the one of a reasonable Dicom/Acr file,
194  *         false otherwise. 
195  */
196 bool File::IsReadable()
197 {
198    if( !Document::IsReadable() )
199    {
200       return false;
201    }
202
203    const std::string &res = GetEntryValue(0x0028, 0x0005);
204    if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
205    {
206       gdcmWarningMacro("Wrong Image Dimensions" << res);
207       return false; // Image Dimensions
208    }
209    if ( !GetDocEntry(0x0028, 0x0100) )
210    {
211       gdcmWarningMacro("Bits Allocated (0028|0100) not found"); 
212       return false; // "Bits Allocated"
213    }
214    if ( !GetDocEntry(0x0028, 0x0101) )
215    {
216       gdcmWarningMacro("Bits Stored (0028|0101) not found");
217       return false; // "Bits Stored"
218    }
219    if ( !GetDocEntry(0x0028, 0x0102) )
220    {
221       gdcmWarningMacro("Hight Bit (0028|0102) not found"); 
222       return false; // "High Bit"
223    }
224    if ( !GetDocEntry(0x0028, 0x0103) )
225    {
226       gdcmWarningMacro("Pixel Representation (0028|0103) not found");
227       return false; // "Pixel Representation" i.e. 'Sign'
228    }
229    if ( !GetDocEntry(GrPixel, NumPixel) )
230    {
231       gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
232                         GrPixel << "|" << NumPixel << "not found");
233       return false; // Pixel Dicom Element not found :-(
234    }
235    return true;
236 }
237
238 /**
239  * \brief gets the info from 0020,0013 : Image Number else 0.
240  * @return image number
241  */
242 int File::GetImageNumber()
243 {
244    //0020 0013 : Image Number
245    std::string strImNumber = GetEntryValue(0x0020,0x0013);
246    if ( strImNumber != GDCM_UNFOUND )
247    {
248       return atoi( strImNumber.c_str() );
249    }
250    return 0;   //Hopeless
251 }
252
253 /**
254  * \brief gets the info from 0008,0060 : Modality
255  * @return Modality Type
256  */
257 ModalityType File::GetModality()
258 {
259    // 0008 0060 : Modality
260    std::string strModality = GetEntryValue(0x0008,0x0060);
261    if ( strModality != GDCM_UNFOUND )
262    {
263            if ( strModality.find("AU") < strModality.length()) return AU;
264       else if ( strModality.find("AS") < strModality.length()) return AS;
265       else if ( strModality.find("BI") < strModality.length()) return BI;
266       else if ( strModality.find("CF") < strModality.length()) return CF;
267       else if ( strModality.find("CP") < strModality.length()) return CP;
268       else if ( strModality.find("CR") < strModality.length()) return CR;
269       else if ( strModality.find("CT") < strModality.length()) return CT;
270       else if ( strModality.find("CS") < strModality.length()) return CS;
271       else if ( strModality.find("DD") < strModality.length()) return DD;
272       else if ( strModality.find("DF") < strModality.length()) return DF;
273       else if ( strModality.find("DG") < strModality.length()) return DG;
274       else if ( strModality.find("DM") < strModality.length()) return DM;
275       else if ( strModality.find("DS") < strModality.length()) return DS;
276       else if ( strModality.find("DX") < strModality.length()) return DX;
277       else if ( strModality.find("ECG") < strModality.length()) return ECG;
278       else if ( strModality.find("EPS") < strModality.length()) return EPS;
279       else if ( strModality.find("FA") < strModality.length()) return FA;
280       else if ( strModality.find("FS") < strModality.length()) return FS;
281       else if ( strModality.find("HC") < strModality.length()) return HC;
282       else if ( strModality.find("HD") < strModality.length()) return HD;
283       else if ( strModality.find("LP") < strModality.length()) return LP;
284       else if ( strModality.find("LS") < strModality.length()) return LS;
285       else if ( strModality.find("MA") < strModality.length()) return MA;
286       else if ( strModality.find("MR") < strModality.length()) return MR;
287       else if ( strModality.find("NM") < strModality.length()) return NM;
288       else if ( strModality.find("OT") < strModality.length()) return OT;
289       else if ( strModality.find("PT") < strModality.length()) return PT;
290       else if ( strModality.find("RF") < strModality.length()) return RF;
291       else if ( strModality.find("RG") < strModality.length()) return RG;
292       else if ( strModality.find("RTDOSE")   
293                                        < strModality.length()) return RTDOSE;
294       else if ( strModality.find("RTIMAGE")  
295                                        < strModality.length()) return RTIMAGE;
296       else if ( strModality.find("RTPLAN")
297                                        < strModality.length()) return RTPLAN;
298       else if ( strModality.find("RTSTRUCT") 
299                                        < strModality.length()) return RTSTRUCT;
300       else if ( strModality.find("SM") < strModality.length()) return SM;
301       else if ( strModality.find("ST") < strModality.length()) return ST;
302       else if ( strModality.find("TG") < strModality.length()) return TG;
303       else if ( strModality.find("US") < strModality.length()) return US;
304       else if ( strModality.find("VF") < strModality.length()) return VF;
305       else if ( strModality.find("XA") < strModality.length()) return XA;
306       else if ( strModality.find("XC") < strModality.length()) return XC;
307
308       else
309       {
310          /// \todo throw error return value ???
311          /// specified <> unknown in our database
312          return Unknow;
313       }
314    }
315
316    return Unknow;
317 }
318
319 /**
320  * \brief   Retrieve the number of columns of image.
321  * @return  The encountered size when found, 0 by default.
322  *          0 means the file is NOT USABLE. The caller will have to check
323  */
324 int File::GetXSize()
325 {
326    const std::string &strSize = GetEntryValue(0x0028,0x0011);
327    if ( strSize == GDCM_UNFOUND )
328    {
329       return 0;
330    }
331
332    return atoi( strSize.c_str() );
333 }
334
335 /**
336  * \brief   Retrieve the number of lines of image.
337  * \warning The defaulted value is 1 as opposed to File::GetXSize()
338  * @return  The encountered size when found, 1 by default 
339  *          (The ACR-NEMA file contains a Signal, not an Image).
340  */
341 int File::GetYSize()
342 {
343    const std::string &strSize = GetEntryValue(0x0028,0x0010);
344    if ( strSize != GDCM_UNFOUND )
345    {
346       return atoi( strSize.c_str() );
347    }
348    if ( IsDicomV3() )
349    {
350       return 0;
351    }
352
353    // The Rows (0028,0010) entry was optional for ACR/NEMA. It might
354    // hence be a signal (1D image). So we default to 1:
355    return 1;
356 }
357
358 /**
359  * \brief   Retrieve the number of planes of volume or the number
360  *          of frames of a multiframe.
361  * \warning When present we consider the "Number of Frames" as the third
362  *          dimension. When Missing we consider the third dimension as
363  *          being the ACR-NEMA "Planes" tag content.
364  * @return  The encountered size when found, 1 by default (single image).
365  */
366 int File::GetZSize()
367 {
368    // Both  DicomV3 and ACR/Nema consider the "Number of Frames"
369    // as the third dimension.
370    const std::string &strSize = GetEntryValue(0x0028,0x0008);
371    if ( strSize != GDCM_UNFOUND )
372    {
373       return atoi( strSize.c_str() );
374    }
375
376    // We then consider the "Planes" entry as the third dimension 
377    const std::string &strSize2 = GetEntryValue(0x0028,0x0012);
378    if ( strSize2 != GDCM_UNFOUND )
379    {
380       return atoi( strSize2.c_str() );
381    }
382
383    return 1;
384 }
385
386 /**
387   * \brief gets the info from 0028,0030 : Pixel Spacing
388   *                         (first in  0018,1164 : ImagerPixelSpacing) 
389   *             else 1.0
390   * @return X dimension of a pixel
391   */
392 float File::GetXSpacing()
393 {
394    float xspacing = 1.0;
395    float yspacing = 1.0;
396    int nbValues;
397
398    // To follow David Clunie's advice, we first check ImagerPixelSpacing
399    // (never saw any image with that field :-(
400
401    const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
402    if( strImagerPixelSpacing != GDCM_UNFOUND )
403    {
404       if( ( nbValues = sscanf( strImagerPixelSpacing.c_str(), 
405             "%f\\%f", &yspacing, &xspacing)) != 2 )
406       {
407          // if no values, xspacing is set to 1.0
408          if( nbValues == 0 )
409             xspacing = 1.0;
410          // if single value is found, xspacing is defaulted to yspacing
411          if( nbValues == 1 )
412             xspacing = yspacing;
413
414          if ( xspacing == 0.0 )
415             xspacing = 1.0;
416
417          return xspacing;
418       }  
419    }
420
421
422    const std::string &strSpacing = GetEntryValue(0x0028,0x0030);
423
424    if( strSpacing == GDCM_UNFOUND )
425    {
426       gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
427       return 1.;
428    }
429
430    if( ( nbValues = sscanf( strSpacing.c_str(), 
431          "%f \\%f ", &yspacing, &xspacing)) != 2 )
432    {
433       // if no values, xspacing is set to 1.0
434       if( nbValues == 0 )
435          xspacing = 1.0;
436       // if single value is found, xspacing is defaulted to yspacing
437       if( nbValues == 1 )
438          xspacing = yspacing;
439
440       if ( xspacing == 0.0 )
441          xspacing = 1.0;
442
443       return xspacing;
444
445    }
446
447    // to avoid troubles with David Clunie's-like images
448    if ( xspacing == 0. && yspacing == 0.)
449       return 1.;
450
451    if ( xspacing == 0.)
452    {
453       gdcmWarningMacro("gdcmData/CT-MONO2-8-abdo.dcm-like problem");
454       // seems to be a bug in the header ...
455       nbValues = sscanf( strSpacing.c_str(), "%f \\0\\%f ", &yspacing, &xspacing);
456       gdcmAssertMacro( nbValues == 2 );
457    }
458
459    return xspacing;
460 }
461
462 /**
463   * \brief gets the info from 0028,0030 : Pixel Spacing
464   *                         (first in  0018,1164 : ImagerPixelSpacing)   
465   *             else 1.0
466   * @return Y dimension of a pixel
467   */
468 float File::GetYSpacing()
469 {
470    float yspacing = 1.;
471    int nbValues;
472    // To follow David Clunie's advice, we first check ImagerPixelSpacing
473    // (never saw any image with that field :-(
474
475    const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
476    if( strImagerPixelSpacing != GDCM_UNFOUND )
477    {
478       nbValues = sscanf( strImagerPixelSpacing.c_str(), "%f", &yspacing);
479    
480    // if sscanf cannot read any float value, it won't affect yspacing
481       if( nbValues == 0 )
482             yspacing = 1.0;
483
484       if ( yspacing == 0.0 )
485             yspacing = 1.0;
486
487       return yspacing;  
488    }
489
490    std::string strSpacing = GetEntryValue(0x0028,0x0030);  
491    if ( strSpacing == GDCM_UNFOUND )
492    {
493       gdcmWarningMacro("Unfound Pixel Spacing (0028,0030)");
494       return 1.;
495     }
496
497    // if sscanf cannot read any float value, it won't affect yspacing
498    nbValues = sscanf( strSpacing.c_str(), "%f", &yspacing);
499
500    // if no values, yspacing is set to 1.0
501    if( nbValues == 0 )
502       yspacing = 1.0;
503
504    if ( yspacing == 0.0 )
505       yspacing = 1.0;
506
507    return yspacing;
508
509
510 /**
511  * \brief gets the info from 0018,0088 : Space Between Slices
512  *                 else from 0018,0050 : Slice Thickness
513  *                 else 1.0
514  * @return Z dimension of a voxel-to be
515  */
516 float File::GetZSpacing()
517 {
518    // Spacing Between Slices : distance between the middle of 2 slices
519    // Slices may be :
520    //   jointives     (Spacing between Slices = Slice Thickness)
521    //   overlapping   (Spacing between Slices < Slice Thickness)
522    //   disjointes    (Spacing between Slices > Slice Thickness)
523    // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
524    //   It only concerns the MRI guys, not people wanting to visualize volmues
525    //   If Spacing Between Slices is Missing, 
526    //   we suppose slices joint together
527    
528    const std::string &strSpacingBSlices = GetEntryValue(0x0018,0x0088);
529
530    if ( strSpacingBSlices == GDCM_UNFOUND )
531    {
532       gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
533       const std::string &strSliceThickness = GetEntryValue(0x0018,0x0050);       
534       if ( strSliceThickness == GDCM_UNFOUND )
535       {
536          gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
537          return 1.;
538       }
539       else
540       {
541          // if no 'Spacing Between Slices' is found, 
542          // we assume slices join together
543          // (no overlapping, no interslice gap)
544          // if they don't, we're fucked up
545          return (float)atof( strSliceThickness.c_str() );
546       }
547    }
548    //else
549    return (float)atof( strSpacingBSlices.c_str() );
550 }
551
552 /**
553  * \brief gets the info from 0020,0032 : Image Position Patient
554  *                 else from 0020,0030 : Image Position (RET)
555  *                 else 0.
556  * @return up-left image corner X position
557  */
558 float File::GetXOrigin()
559 {
560    float xImPos, yImPos, zImPos;  
561    std::string strImPos = GetEntryValue(0x0020,0x0032);
562
563    if ( strImPos == GDCM_UNFOUND )
564    {
565       gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
566       strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
567       if ( strImPos == GDCM_UNFOUND )
568       {
569          gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
570          return 0.;
571       }
572    }
573
574    if( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
575    {
576       return 0.;
577    }
578
579    return xImPos;
580 }
581
582 /**
583  * \brief gets the info from 0020,0032 : Image Position Patient
584  *                 else from 0020,0030 : Image Position (RET)
585  *                 else 0.
586  * @return up-left image corner Y position
587  */
588 float File::GetYOrigin()
589 {
590    float xImPos, yImPos, zImPos;
591    std::string strImPos = GetEntryValue(0x0020,0x0032);
592
593    if ( strImPos == GDCM_UNFOUND)
594    {
595       gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
596       strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
597       if ( strImPos == GDCM_UNFOUND )
598       {
599          gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
600          return 0.;
601       }  
602    }
603
604    if( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
605    {
606       return 0.;
607    }
608
609    return yImPos;
610 }
611
612 /**
613  * \brief gets the info from 0020,0032 : Image Position Patient
614  *                 else from 0020,0030 : Image Position (RET)
615  *                 else from 0020,1041 : Slice Location
616  *                 else from 0020,0050 : Location
617  *                 else 0.
618  * @return up-left image corner Z position
619  */
620 float File::GetZOrigin()
621 {
622    float xImPos, yImPos, zImPos; 
623    std::string strImPos = GetEntryValue(0x0020,0x0032);
624
625    if ( strImPos != GDCM_UNFOUND )
626    {
627       if( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3)
628       {
629          gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
630          return 0.;  // bug in the element 0x0020,0x0032
631       }
632       else
633       {
634          return zImPos;
635       }
636    }
637
638    strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
639    if ( strImPos != GDCM_UNFOUND )
640    {
641       if( sscanf( strImPos.c_str(), 
642           "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos ) != 3 )
643       {
644          gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
645          return 0.;  // bug in the element 0x0020,0x0032
646       }
647       else
648       {
649          return zImPos;
650       }
651    }
652
653    std::string strSliceLocation = GetEntryValue(0x0020,0x1041); // for *very* old ACR-NEMA images
654    if ( strSliceLocation != GDCM_UNFOUND )
655    {
656       if( sscanf( strSliceLocation.c_str(), "%f ", &zImPos) != 1)
657       {
658          gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
659          return 0.;  // bug in the element 0x0020,0x1041
660       }
661       else
662       {
663          return zImPos;
664       }
665    }
666    gdcmWarningMacro( "Unfound Slice Location (0020,1041)");
667
668    std::string strLocation = GetEntryValue(0x0020,0x0050);
669    if ( strLocation != GDCM_UNFOUND )
670    {
671       if( sscanf( strLocation.c_str(), "%f ", &zImPos) != 1)
672       {
673          gdcmWarningMacro( "Wrong Location (0020,0050)");
674          return 0.;  // bug in the element 0x0020,0x0050
675       }
676       else
677       {
678          return zImPos;
679       }
680    }
681    gdcmWarningMacro( "Unfound Location (0020,0050)");  
682
683    return 0.; // Hopeless
684 }
685
686 /**
687   * \brief gets the info from 0020,0037 : Image Orientation Patient
688   * (needed to organize DICOM files based on their x,y,z position)
689   * @param iop adress of the (6)float aray to receive values
690   * @return cosines of image orientation patient
691   */
692 void File::GetImageOrientationPatient( float iop[6] )
693 {
694    std::string strImOriPat;
695    //iop is supposed to be float[6]
696    iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
697
698    // 0020 0037 DS REL Image Orientation (Patient)
699    if ( (strImOriPat = GetEntryValue(0x0020,0x0037)) != GDCM_UNFOUND )
700    {
701       if( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ", 
702           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
703       {
704          gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037). Less than 6 values were found." );
705       }
706    }
707    //For ACR-NEMA
708    // 0020 0035 DS REL Image Orientation (RET)
709    else if ( (strImOriPat = GetEntryValue(0x0020,0x0035)) != GDCM_UNFOUND )
710    {
711       if( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ", 
712           &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
713       {
714          gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). Less than 6 values were found." );
715       }
716    }
717 }
718
719 /**
720  * \brief   Retrieve the number of Bits Stored (actually used)
721  *          (as opposed to number of Bits Allocated)
722  * @return  The encountered number of Bits Stored, 0 by default.
723  *          0 means the file is NOT USABLE. The caller has to check it !
724  */
725 int File::GetBitsStored()
726 {
727    std::string strSize = GetEntryValue( 0x0028, 0x0101 );
728    if ( strSize == GDCM_UNFOUND )
729    {
730       gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
731       return 0;  // It's supposed to be mandatory
732                  // the caller will have to check
733    }
734    return atoi( strSize.c_str() );
735 }
736
737 /**
738  * \brief   Retrieve the number of Bits Allocated
739  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
740  * @return  The encountered number of Bits Allocated, 0 by default.
741  *          0 means the file is NOT USABLE. The caller has to check it !
742  */
743 int File::GetBitsAllocated()
744 {
745    std::string strSize = GetEntryValue(0x0028,0x0100);
746    if ( strSize == GDCM_UNFOUND  )
747    {
748       gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
749       return 0; // It's supposed to be mandatory
750                 // the caller will have to check
751    }
752    return atoi( strSize.c_str() );
753 }
754
755 /**
756  * \brief   Retrieve the high bit position.
757  * \warning The method defaults to 0 when information is Missing.
758  *          The responsability of checking this value is left to the caller.
759  * @return  The high bit positin when present. 0 when Missing.
760  */
761 int File::GetHighBitPosition()
762 {
763    std::string strSize = GetEntryValue( 0x0028, 0x0102 );
764    if ( strSize == GDCM_UNFOUND )
765    {
766       gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
767       return 0;
768    }
769    return atoi( strSize.c_str() );
770 }
771
772 /**
773  * \brief   Retrieve the number of Samples Per Pixel
774  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
775  * @return  The encountered number of Samples Per Pixel, 1 by default.
776  *          (Gray level Pixels)
777  */
778 int File::GetSamplesPerPixel()
779 {
780    const std::string &strSize = GetEntryValue(0x0028,0x0002);
781    if ( strSize == GDCM_UNFOUND )
782    {
783       gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
784       return 1; // Well, it's supposed to be mandatory ...
785                 // but sometimes it's missing : *we* assume Gray pixels
786    }
787    return atoi( strSize.c_str() );
788 }
789
790 /**
791  * \brief   Retrieve the Planar Configuration for RGB images
792  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
793  * @return  The encountered Planar Configuration, 0 by default.
794  */
795 int File::GetPlanarConfiguration()
796 {
797    std::string strSize = GetEntryValue(0x0028,0x0006);
798    if ( strSize == GDCM_UNFOUND )
799    {
800       gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
801       return 0;
802    }
803    return atoi( strSize.c_str() );
804 }
805
806 /**
807  * \brief   Return the size (in bytes) of a single pixel of data.
808  * @return  The size in bytes of a single pixel of data; 0 by default
809  *          0 means the file is NOT USABLE; the caller will have to check
810  */
811 int File::GetPixelSize()
812 {
813    // 0028 0100 US IMG Bits Allocated
814    // (in order no to be messed up by old RGB images)
815    //   if (File::GetEntryValue(0x0028,0x0100) == "24")
816    //      return 3;
817
818    std::string pixelType = GetPixelType();
819    if ( pixelType ==  "8U" || pixelType == "8S" )
820    {
821       return 1;
822    }
823    if ( pixelType == "16U" || pixelType == "16S")
824    {
825       return 2;
826    }
827    if ( pixelType == "32U" || pixelType == "32S")
828    {
829       return 4;
830    }
831    if ( pixelType == "FD" )
832    {
833       return 8;
834    }
835    gdcmWarningMacro( "Unknown pixel type");
836    return 0;
837 }
838
839 /**
840  * \brief   Build the Pixel Type of the image.
841  *          Possible values are:
842  *          - 8U  unsigned  8 bit,
843  *          - 8S    signed  8 bit,
844  *          - 16U unsigned 16 bit,
845  *          - 16S   signed 16 bit,
846  *          - 32U unsigned 32 bit,
847  *          - 32S   signed 32 bit,
848  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
849  * \warning 12 bit images appear as 16 bit.
850  *          24 bit images appear as 8 bit + photochromatic interp ="RGB "
851  * @return  0S if nothing found. NOT USABLE file. The caller has to check
852  */
853 std::string File::GetPixelType()
854 {
855    std::string bitsAlloc = GetEntryValue(0x0028, 0x0100); // Bits Allocated
856    if ( bitsAlloc == GDCM_UNFOUND )
857    {
858       gdcmWarningMacro( "Missing  Bits Allocated (0028,0100)");
859       bitsAlloc = "16"; // default and arbitrary value, not to polute the output
860    }
861
862    if ( bitsAlloc == "64" )
863    {
864       return "FD";
865    }
866    else if ( bitsAlloc == "12" )
867    {
868       // It will be unpacked
869       bitsAlloc = "16";
870    }
871    else if ( bitsAlloc == "24" )
872    {
873       // (in order no to be messed up
874       bitsAlloc = "8";  // by old RGB images)
875    }
876
877    std::string sign = GetEntryValue(0x0028, 0x0103);//"Pixel Representation"
878
879    if (sign == GDCM_UNFOUND )
880    {
881       gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
882       sign = "U"; // default and arbitrary value, not to polute the output
883    }
884    else if ( sign == "0" )
885    {
886       sign = "U";
887    }
888    else
889    {
890       sign = "S";
891    }
892    return bitsAlloc + sign;
893 }
894
895 /**
896  * \brief   Check whether the pixels are signed (1) or UNsigned (0) data.
897  * \warning The method defaults to false (UNsigned) when tag 0028|0103
898  *          is missing.
899  *          The responsability of checking this value is left to the caller.
900  * @return  True when signed, false when UNsigned
901  */
902 bool File::IsSignedPixelData()
903 {
904    std::string strSign = GetEntryValue( 0x0028, 0x0103 );
905    if ( strSign == GDCM_UNFOUND )
906    {
907       gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
908       return false;
909    }
910    int sign = atoi( strSign.c_str() );
911    if ( sign == 0 ) 
912    {
913       return false;
914    }
915    return true;
916 }
917
918 /**
919  * \brief   Check whether this a monochrome picture (gray levels) or not,
920  *          using "Photometric Interpretation" tag (0x0028,0x0004).
921  * @return  true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
922  */
923 bool File::IsMonochrome()
924 {
925    const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
926    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
927       || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
928    {
929       return true;
930    }
931    if ( PhotometricInterp == GDCM_UNFOUND )
932    {
933       gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
934    }
935    return false;
936 }
937
938 /**
939  * \brief   Check whether this a MONOCHROME1 picture (high values = dark)
940  *            or not using "Photometric Interpretation" tag (0x0028,0x0004).
941  * @return  true when "MONOCHROME1" . False otherwise.
942  */
943 bool File::IsMonochrome1()
944 {
945    const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
946    if (  Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
947    {
948       return true;
949    }
950    if ( PhotometricInterp == GDCM_UNFOUND )
951    {
952       gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
953    }
954    return false;
955 }
956
957 /**
958  * \brief   Check whether this a "PALETTE COLOR" picture or not by accessing
959  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
960  * @return  true when "PALETTE COLOR". False otherwise.
961  */
962 bool File::IsPaletteColor()
963 {
964    std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
965    if (   PhotometricInterp == "PALETTE COLOR " )
966    {
967       return true;
968    }
969    if ( PhotometricInterp == GDCM_UNFOUND )
970    {
971       gdcmWarningMacro( "Not found : Palette color (0028,0004)");
972    }
973    return false;
974 }
975
976 /**
977  * \brief   Check whether this a "YBR_FULL" color picture or not by accessing
978  *          the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
979  * @return  true when "YBR_FULL". False otherwise.
980  */
981 bool File::IsYBRFull()
982 {
983    std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
984    if (   PhotometricInterp == "YBR_FULL" )
985    {
986       return true;
987    }
988    if ( PhotometricInterp == GDCM_UNFOUND )
989    {
990       gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
991    }
992    return false;
993 }
994
995 /**
996   * \brief tells us if LUT are used
997   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
998   *          are NOT considered as LUT, since nobody knows
999   *          how to deal with them
1000   *          Please warn me if you know sbdy that *does* know ... jprx
1001   * @return true if LUT Descriptors and LUT Tables were found 
1002   */
1003 bool File::HasLUT()
1004 {
1005    // Check the presence of the LUT Descriptors, and LUT Tables    
1006    // LutDescriptorRed    
1007    if ( !GetDocEntry(0x0028,0x1101) )
1008    {
1009       return false;
1010    }
1011    // LutDescriptorGreen 
1012    if ( !GetDocEntry(0x0028,0x1102) )
1013    {
1014       return false;
1015    }
1016    // LutDescriptorBlue 
1017    if ( !GetDocEntry(0x0028,0x1103) )
1018    {
1019       return false;
1020    }
1021    // Red Palette Color Lookup Table Data
1022    if ( !GetDocEntry(0x0028,0x1201) )
1023    {
1024       return false;
1025    }
1026    // Green Palette Color Lookup Table Data       
1027    if ( !GetDocEntry(0x0028,0x1202) )
1028    {
1029       return false;
1030    }
1031    // Blue Palette Color Lookup Table Data      
1032    if ( !GetDocEntry(0x0028,0x1203) )
1033    {
1034       return false;
1035    }
1036
1037    // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1038    //         NOT taken into account, but we don't know how to use it ...   
1039    return true;
1040 }
1041
1042 /**
1043   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1044   *             else 0
1045   * @return Lookup Table number of Bits , 0 by default
1046   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1047   * @ return bit number of each LUT item 
1048   */
1049 int File::GetLUTNbits()
1050 {
1051    std::vector<std::string> tokens;
1052    int lutNbits;
1053
1054    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1055    //                                = Lookup Table Desc-Blue
1056    // Consistency already checked in GetLUTLength
1057    std::string lutDescription = GetEntryValue(0x0028,0x1101);
1058    if ( lutDescription == GDCM_UNFOUND )
1059    {
1060       return 0;
1061    }
1062
1063    tokens.clear(); // clean any previous value
1064    Util::Tokenize ( lutDescription, tokens, "\\" );
1065    //LutLength=atoi(tokens[0].c_str());
1066    //LutDepth=atoi(tokens[1].c_str());
1067
1068    lutNbits = atoi( tokens[2].c_str() );
1069    tokens.clear();
1070
1071    return lutNbits;
1072 }
1073
1074 /**
1075  *\brief gets the info from 0028,1052 : Rescale Intercept
1076  * @return Rescale Intercept
1077  */
1078 float File::GetRescaleIntercept()
1079 {
1080    float resInter = 0.;
1081    /// 0028 1052 DS IMG Rescale Intercept
1082    const std::string &strRescInter = GetEntryValue(0x0028,0x1052);
1083    if ( strRescInter != GDCM_UNFOUND )
1084    {
1085       if( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1086       {
1087          // bug in the element 0x0028,0x1052
1088          gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1089       }
1090    }
1091
1092    return resInter;
1093 }
1094
1095 /**
1096  *\brief   gets the info from 0028,1053 : Rescale Slope
1097  * @return Rescale Slope
1098  */
1099 float File::GetRescaleSlope()
1100 {
1101    float resSlope = 1.;
1102    //0028 1053 DS IMG Rescale Slope
1103    std::string strRescSlope = GetEntryValue(0x0028,0x1053);
1104    if ( strRescSlope != GDCM_UNFOUND )
1105    {
1106       if( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1)
1107       {
1108          // bug in the element 0x0028,0x1053
1109          gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1110       }
1111    }
1112
1113    return resSlope;
1114 }
1115
1116 /**
1117  * \brief This function is intended to user who doesn't want 
1118  *   to have to manage a LUT and expects to get an RBG Pixel image
1119  *   (or a monochrome one ...) 
1120  * \warning to be used with GetImagePixels()
1121  * @return 1 if Gray level, 3 if Color (RGB, YBR or PALETTE COLOR)
1122  */
1123 int File::GetNumberOfScalarComponents()
1124 {
1125    if ( GetSamplesPerPixel() == 3 )
1126    {
1127       return 3;
1128    }
1129       
1130    // 0028 0100 US IMG Bits Allocated
1131    // (in order no to be messed up by old RGB images)
1132    if ( GetEntryValue(0x0028,0x0100) == "24" )
1133    {
1134       return 3;
1135    }
1136        
1137    std::string strPhotometricInterpretation = GetEntryValue(0x0028,0x0004);
1138
1139    if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1140    {
1141       if ( HasLUT() )// PALETTE COLOR is NOT enough
1142       {
1143          return 3;
1144       }
1145       else
1146       {
1147          return 1;
1148       }
1149    }
1150
1151    // beware of trailing space at end of string      
1152    // DICOM tags are never of odd length
1153    if ( strPhotometricInterpretation == GDCM_UNFOUND   || 
1154         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1155         Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1156    {
1157       return 1;
1158    }
1159    else
1160    {
1161       // we assume that *all* kinds of YBR are dealt with
1162       return 3;
1163    }
1164 }
1165
1166 /**
1167  * \brief This function is intended to user that DOESN'T want 
1168  *  to get RGB pixels image when it's stored as a PALETTE COLOR image
1169  *   - the (vtk) user is supposed to know how deal with LUTs - 
1170  * \warning to be used with GetImagePixelsRaw()
1171  * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1172  */
1173 int File::GetNumberOfScalarComponentsRaw()
1174 {
1175    // 0028 0100 US IMG Bits Allocated
1176    // (in order no to be messed up by old RGB images)
1177    if ( File::GetEntryValue(0x0028,0x0100) == "24" )
1178    {
1179       return 3;
1180    }
1181
1182    // we assume that *all* kinds of YBR are dealt with
1183    return GetSamplesPerPixel();
1184 }
1185
1186 /**
1187  * \brief   Recover the offset (from the beginning of the file) 
1188  *          of *image* pixels (not *icone image* pixels, if any !)
1189  * @return Pixel Offset
1190  */
1191 size_t File::GetPixelOffset()
1192 {
1193    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1194    if ( pxlElement )
1195    {
1196       return pxlElement->GetOffset();
1197    }
1198    else
1199    {
1200       gdcmDebugMacro( "Big trouble : Pixel Element ("
1201                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1202       return 0;
1203    }
1204 }
1205
1206 /**
1207  * \brief   Recover the pixel area length (in Bytes)
1208  * @return Pixel Element Length, as stored in the header
1209  *         (NOT the memory space necessary to hold the Pixels 
1210  *          -in case of embeded compressed image-)
1211  *         0 : NOT USABLE file. The caller has to check.
1212  */
1213 size_t File::GetPixelAreaLength()
1214 {
1215    DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1216    if ( pxlElement )
1217    {
1218       return pxlElement->GetLength();
1219    }
1220    else
1221    {
1222       gdcmDebugMacro( "Big trouble : Pixel Element ("
1223                       << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1224       return 0;
1225    }
1226 }
1227
1228 /**
1229  * \brief Adds the characteristics of a new element we want to anonymize
1230  *
1231  */
1232 void File::AddAnonymizeElement (uint16_t group, uint16_t elem, 
1233                                 std::string const &value) 
1234
1235
1236    Element el;
1237    el.Group = group;
1238    el.Elem  = elem;
1239    el.Value = value;
1240    AnonymizeList.push_back(el); 
1241 }
1242
1243 /**
1244  * \brief Overwrites in the file the values of the DicomElements
1245  *       held in the list 
1246  */
1247 void File::AnonymizeNoLoad()
1248 {
1249    std::fstream *fp = new std::fstream(Filename.c_str(), 
1250                               std::ios::in | std::ios::out | std::ios::binary); 
1251    gdcm::DocEntry *d;
1252    uint32_t offset;
1253    uint32_t lgth;
1254    uint32_t valLgth = 0;
1255    std::string *spaces;
1256    for (ListElements::iterator it = AnonymizeList.begin();  
1257                                it != AnonymizeList.end();
1258                              ++it)
1259    { 
1260       d = GetDocEntry( (*it).Group, (*it).Elem);
1261
1262       if ( d == NULL)
1263          continue;
1264
1265       if ( dynamic_cast<BinEntry *>(d)
1266         || dynamic_cast<SeqEntry *>(d) )
1267          continue;
1268
1269       offset = d->GetOffset();
1270       lgth =   d->GetLength();
1271       if (valLgth < lgth)
1272       {
1273          spaces = new std::string( lgth-valLgth, ' ');
1274          (*it).Value = (*it).Value + *spaces;
1275          delete spaces;
1276       }
1277       fp->seekp( offset, std::ios::beg );
1278       fp->write( (*it).Value.c_str(), lgth );
1279      
1280    }
1281    fp->close();
1282    delete fp;
1283 }
1284
1285 /**
1286  * \brief anonymize a File (removes Patient's personal info passed with
1287  *        AddAnonymizeElement()
1288  */
1289 bool File::AnonymizeFile()
1290 {
1291    // If Anonymisation list is empty, let's perform some basic anonymization
1292    if ( AnonymizeList.begin() == AnonymizeList.end() )
1293    {
1294       // If exist, replace by spaces
1295       SetValEntry ("  ",0x0010, 0x2154); // Telephone   
1296       SetValEntry ("  ",0x0010, 0x1040); // Adress
1297       SetValEntry ("  ",0x0010, 0x0020); // Patient ID
1298
1299       DocEntry* patientNameHE = GetDocEntry (0x0010, 0x0010);
1300   
1301       if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1302       {
1303          std::string studyInstanceUID =  GetEntryValue (0x0020, 0x000d);
1304          if ( studyInstanceUID != GDCM_UNFOUND )
1305          {
1306             SetValEntry(studyInstanceUID, 0x0010, 0x0010);
1307          }
1308          else
1309          {
1310             SetValEntry("anonymised", 0x0010, 0x0010);
1311          }
1312       }
1313    }
1314    else
1315    {
1316       gdcm::DocEntry *d;
1317       for (ListElements::iterator it = AnonymizeList.begin();  
1318                                   it != AnonymizeList.end();
1319                                 ++it)
1320       {  
1321          d = GetDocEntry( (*it).Group, (*it).Elem);
1322
1323          if ( d == NULL)
1324             continue;
1325
1326          if ( dynamic_cast<BinEntry *>(d)
1327            || dynamic_cast<SeqEntry *>(d) )
1328             continue;
1329
1330          SetValEntry ((*it).Value, (*it).Group, (*it).Elem);
1331       }
1332 }
1333
1334   // In order to make definitively impossible any further identification
1335   // remove or replace all the stuff that contains a Date
1336
1337 //0008 0012 DA ID Instance Creation Date
1338 //0008 0020 DA ID Study Date
1339 //0008 0021 DA ID Series Date
1340 //0008 0022 DA ID Acquisition Date
1341 //0008 0023 DA ID Content Date
1342 //0008 0024 DA ID Overlay Date
1343 //0008 0025 DA ID Curve Date
1344 //0008 002a DT ID Acquisition Datetime
1345 //0018 9074 DT ACQ Frame Acquisition Datetime
1346 //0018 9151 DT ACQ Frame Reference Datetime
1347 //0018 a002 DT ACQ Contribution Date Time
1348 //0020 3403 SH REL Modified Image Date (RET)
1349 //0032 0032 DA SDY Study Verified Date
1350 //0032 0034 DA SDY Study Read Date
1351 //0032 1000 DA SDY Scheduled Study Start Date
1352 //0032 1010 DA SDY Scheduled Study Stop Date
1353 //0032 1040 DA SDY Study Arrival Date
1354 //0032 1050 DA SDY Study Completion Date
1355 //0038 001a DA VIS Scheduled Admission Date
1356 //0038 001c DA VIS Scheduled Discharge Date
1357 //0038 0020 DA VIS Admitting Date
1358 //0038 0030 DA VIS Discharge Date
1359 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1360 //0040 0004 DA PRC Scheduled Procedure Step End Date
1361 //0040 0244 DA PRC Performed Procedure Step Start Date
1362 //0040 0250 DA PRC Performed Procedure Step End Date
1363 //0040 2004 DA PRC Issue Date of Imaging Service Request
1364 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1365 //0040 4011 DT PRC Expected Completion Date and Time
1366 //0040 a030 DT PRC Verification Date Time
1367 //0040 a032 DT PRC Observation Date Time
1368 //0040 a120 DT PRC DateTime
1369 //0040 a121 DA PRC Date
1370 //0040 a13a DT PRC Referenced Datetime
1371 //0070 0082 DA ??? Presentation Creation Date
1372 //0100 0420 DT ??? SOP Autorization Date and Time
1373 //0400 0105 DT ??? Digital Signature DateTime
1374 //2100 0040 DA PJ Creation Date
1375 //3006 0008 DA SSET Structure Set Date
1376 //3008 0024 DA ??? Treatment Control Point Date
1377 //3008 0054 DA ??? First Treatment Date
1378 //3008 0056 DA ??? Most Recent Treatment Date
1379 //3008 0162 DA ??? Safe Position Exit Date
1380 //3008 0166 DA ??? Safe Position Return Date
1381 //3008 0250 DA ??? Treatment Date
1382 //300a 0006 DA RT RT Plan Date
1383 //300a 022c DA RT Air Kerma Rate Reference Date
1384 //300e 0004 DA RT Review Date
1385
1386    return true;
1387 }
1388
1389 /**
1390  * \brief Performs some consistency checking on various 'File related' 
1391  *       (as opposed to 'DicomDir related') entries 
1392  *       then writes in a file all the (Dicom Elements) included the Pixels 
1393  * @param fileName file name to write to
1394  * @param writetype Type of the File to be written 
1395  *          (ACR, ExplicitVR, ImplicitVR)
1396  */
1397 bool File::Write(std::string fileName, FileType writetype)
1398 {
1399    std::ofstream *fp = new std::ofstream(fileName.c_str(), 
1400                                          std::ios::out | std::ios::binary);
1401    if (*fp == NULL)
1402    {
1403       gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1404       return false;
1405    }
1406
1407    // Entry : 0002|0000 = group length -> recalculated
1408    ValEntry*e0000 = GetValEntry(0x0002,0x0000);
1409    if( e0000 )
1410    {
1411       std::ostringstream sLen;
1412       sLen << ComputeGroup0002Length(writetype);
1413       e0000->SetValue(sLen.str());
1414    }
1415
1416    int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1417    if (i_lgPix != -2)
1418    {
1419       // no (GrPixel, NumPixel) element
1420       std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1421       s_lgPix = Util::DicomString( s_lgPix.c_str() );
1422       InsertValEntry(s_lgPix,GrPixel, 0x0000);
1423    }
1424
1425    Document::WriteContent(fp, writetype);
1426
1427    fp->close();
1428    delete fp;
1429
1430    return true;
1431 }
1432
1433 //-----------------------------------------------------------------------------
1434 // Protected
1435
1436
1437 //-----------------------------------------------------------------------------
1438 // Private
1439 /**
1440  * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1441  *        Compute the RLE extra information and store it in \ref RLEInfo
1442  *        for later pixel retrieval usage.
1443  */
1444 void File::ComputeRLEInfo()
1445 {
1446    std::string ts = GetTransferSyntax();
1447    if ( !Global::GetTS()->IsRLELossless(ts) ) 
1448    {
1449       return;
1450    }
1451
1452    // Encoded pixel data: for the time being we are only concerned with
1453    // Jpeg or RLE Pixel data encodings.
1454    // As stated in PS 3.5-2003, section 8.2 p44:
1455    // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1456    //  value representation OB is used".
1457    // Hence we expect an OB value representation. Concerning OB VR,
1458    // the section PS 3.5-2003, section A.4.c p 58-59, states:
1459    // "For the Value Representations OB and OW, the encoding shall meet the
1460    //   following specifications depending on the Data element tag:"
1461    //   [...snip...]
1462    //    - the first item in the sequence of items before the encoded pixel
1463    //      data stream shall be basic offset table item. The basic offset table
1464    //      item value, however, is not required to be present"
1465    ReadAndSkipEncapsulatedBasicOffsetTable();
1466
1467    // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1468    // Loop on the individual frame[s] and store the information
1469    // on the RLE fragments in a RLEFramesInfo.
1470    // Note: - when only a single frame is present, this is a
1471    //         classical image.
1472    //       - when more than one frame are present, then we are in 
1473    //         the case of a multi-frame image.
1474    long frameLength;
1475    while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1476    { 
1477       // Parse the RLE Header and store the corresponding RLE Segment
1478       // Offset Table information on fragments of this current Frame.
1479       // Note that the fragment pixels themselves are not loaded
1480       // (but just skipped).
1481       long frameOffset = Fp->tellg();
1482
1483       uint32_t nbRleSegments = ReadInt32();
1484       if ( nbRleSegments > 16 )
1485       {
1486          // There should be at most 15 segments (refer to RLEFrame class)
1487          gdcmWarningMacro( "Too many segments.");
1488       }
1489  
1490       uint32_t rleSegmentOffsetTable[16];
1491       for( int k = 1; k <= 15; k++ )
1492       {
1493          rleSegmentOffsetTable[k] = ReadInt32();
1494       }
1495
1496       // Deduce from both the RLE Header and the frameLength the
1497       // fragment length, and again store this info in a
1498       // RLEFramesInfo.
1499       long rleSegmentLength[15];
1500       // skipping (not reading) RLE Segments
1501       if ( nbRleSegments > 1)
1502       {
1503          for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1504          {
1505              rleSegmentLength[k] =  rleSegmentOffsetTable[k+1]
1506                                   - rleSegmentOffsetTable[k];
1507              SkipBytes(rleSegmentLength[k]);
1508           }
1509        }
1510
1511        rleSegmentLength[nbRleSegments] = frameLength 
1512                                       - rleSegmentOffsetTable[nbRleSegments];
1513        SkipBytes(rleSegmentLength[nbRleSegments]);
1514
1515        // Store the collected info
1516        RLEFrame *newFrame = new RLEFrame;
1517        newFrame->SetNumberOfFragments(nbRleSegments);
1518        for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1519        {
1520           newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1521           newFrame->SetLength(uk,rleSegmentLength[uk]);
1522        }
1523        RLEInfo->AddFrame(newFrame);
1524    }
1525
1526    // Make sure that at the end of the item we encounter a 'Sequence
1527    // Delimiter Item':
1528    if ( !ReadTag(0xfffe, 0xe0dd) )
1529    {
1530       gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1531    }
1532 }
1533
1534 /**
1535  * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1536  *        Compute the jpeg extra information (fragment[s] offset[s] and
1537  *        length) and store it[them] in \ref JPEGInfo for later pixel
1538  *        retrieval usage.
1539  */
1540 void File::ComputeJPEGFragmentInfo()
1541 {
1542    // If you need to, look for comments of ComputeRLEInfo().
1543    std::string ts = GetTransferSyntax();
1544    if ( ! Global::GetTS()->IsJPEG(ts) )
1545    {
1546       return;
1547    }
1548
1549    ReadAndSkipEncapsulatedBasicOffsetTable();
1550
1551    // Loop on the fragments[s] and store the parsed information in a
1552    // JPEGInfo.
1553    long fragmentLength;
1554    while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1555    { 
1556       long fragmentOffset = Fp->tellg();
1557
1558        // Store the collected info
1559        JPEGFragment *newFragment = new JPEGFragment;
1560        newFragment->SetOffset(fragmentOffset);
1561        newFragment->SetLength(fragmentLength);
1562        JPEGInfo->AddFragment(newFragment);
1563
1564        SkipBytes(fragmentLength);
1565    }
1566
1567    // Make sure that at the end of the item we encounter a 'Sequence
1568    // Delimiter Item':
1569    if ( !ReadTag(0xfffe, 0xe0dd) )
1570    {
1571       gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1572    }
1573 }
1574
1575 /**
1576  * \brief   Assuming the internal file pointer \ref Document::Fp 
1577  *          is placed at the beginning of a tag check whether this
1578  *          tag is (TestGroup, TestElement).
1579  * \warning On success the internal file pointer \ref Document::Fp
1580  *          is modified to point after the tag.
1581  *          On failure (i.e. when the tag wasn't the expected tag
1582  *          (TestGroup, TestElement) the internal file pointer
1583  *          \ref Document::Fp is restored to it's original position.
1584  * @param   testGroup   The expected group of the tag.
1585  * @param   testElement The expected Element of the tag.
1586  * @return  True on success, false otherwise.
1587  */
1588 bool File::ReadTag(uint16_t testGroup, uint16_t testElement)
1589 {
1590    long positionOnEntry = Fp->tellg();
1591    long currentPosition = Fp->tellg();          // On debugging purposes
1592
1593    // Read the Item Tag group and element, and make
1594    // sure they are what we expected:
1595    uint16_t itemTagGroup;
1596    uint16_t itemTagElement;
1597    try
1598    {
1599       itemTagGroup   = ReadInt16();
1600       itemTagElement = ReadInt16();
1601    }
1602    catch ( FormatError e )
1603    {
1604       //std::cerr << e << std::endl;
1605       return false;
1606    }
1607    if ( itemTagGroup != testGroup || itemTagElement != testElement )
1608    {
1609       gdcmWarningMacro( "Wrong Item Tag found:"
1610        << "   We should have found tag ("
1611        << std::hex << testGroup << "," << testElement << ")" << std::endl
1612        << "   but instead we encountered tag ("
1613        << std::hex << itemTagGroup << "," << itemTagElement << ")"
1614        << "  at address: " << "  0x(" << (unsigned int)currentPosition  << ")" 
1615        ) ;
1616       Fp->seekg(positionOnEntry, std::ios::beg);
1617
1618       return false;
1619    }
1620    return true;
1621 }
1622
1623 /**
1624  * \brief   Assuming the internal file pointer \ref Document::Fp 
1625  *          is placed at the beginning of a tag (TestGroup, TestElement),
1626  *          read the length associated to the Tag.
1627  * \warning On success the internal file pointer \ref Document::Fp
1628  *          is modified to point after the tag and it's length.
1629  *          On failure (i.e. when the tag wasn't the expected tag
1630  *          (TestGroup, TestElement) the internal file pointer
1631  *          \ref Document::Fp is restored to it's original position.
1632  * @param   testGroup   The expected group of the tag.
1633  * @param   testElement The expected Element of the tag.
1634  * @return  On success returns the length associated to the tag. On failure
1635  *          returns 0.
1636  */
1637 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElement)
1638 {
1639
1640    if ( !ReadTag(testGroup, testElement) )
1641    {
1642       return 0;
1643    }
1644                                                                                 
1645    //// Then read the associated Item Length
1646    long currentPosition = Fp->tellg();
1647    uint32_t itemLength  = ReadInt32();
1648    {
1649       gdcmWarningMacro( "Basic Item Length is: "
1650         << itemLength << std::endl
1651         << "  at address: " << std::hex << (unsigned int)currentPosition);
1652    }
1653    return itemLength;
1654 }
1655
1656 /**
1657  * \brief When parsing the Pixel Data of an encapsulated file, read
1658  *        the basic offset table (when present, and BTW dump it).
1659  */
1660 void File::ReadAndSkipEncapsulatedBasicOffsetTable()
1661 {
1662    //// Read the Basic Offset Table Item Tag length...
1663    uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1664
1665    // When present, read the basic offset table itself.
1666    // Notes: - since the presence of this basic offset table is optional
1667    //          we can't rely on it for the implementation, and we will simply
1668    //          trash it's content (when present).
1669    //        - still, when present, we could add some further checks on the
1670    //          lengths, but we won't bother with such fuses for the time being.
1671    if ( itemLength != 0 )
1672    {
1673       char *basicOffsetTableItemValue = new char[itemLength + 1];
1674       Fp->read(basicOffsetTableItemValue, itemLength);
1675
1676 #ifdef GDCM_DEBUG
1677       for (unsigned int i=0; i < itemLength; i += 4 )
1678       {
1679          uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
1680                                               uint32_t);
1681          gdcmWarningMacro( "Read one length: " << 
1682                           std::hex << individualLength );
1683       }
1684 #endif //GDCM_DEBUG
1685
1686       delete[] basicOffsetTableItemValue;
1687    }
1688 }
1689
1690 //-----------------------------------------------------------------------------
1691 // Print
1692
1693 //-----------------------------------------------------------------------------
1694 } // end namespace gdcm