]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
* src/gdcmParser.[cxx|h] and gdcmHeader.[cxx.h]: gdcmHeader::Write split
[gdcm.git] / src / gdcmHeader.cxx
1 // gdcmHeader.cxx
2 //-----------------------------------------------------------------------------
3 #include <stdio.h>
4 #include <cerrno>
5 #include <cctype>    // for isalpha
6 #include <vector>
7
8 #include "gdcmHeader.h"
9 #include "gdcmGlobal.h"
10 #include "gdcmUtil.h"
11 #include "gdcmDebug.h"
12 #include "gdcmTS.h"
13
14 //-----------------------------------------------------------------------------
15 // Constructor / Destructor
16 /**
17  * \brief  Constructor 
18  * @param  InFilename name of the file whose header we want to analyze
19  * @param  exception_on_error whether we want to throw an exception or not
20  * @param  enable_sequences = true to allow the header 
21  *         to be parsed *inside* the SeQuences, when they have an actual length 
22  * @param  ignore_shadow = true if user wants to skip shadow groups 
23  *         during parsing, to save memory space
24  */
25 gdcmHeader::gdcmHeader(const char *InFilename, 
26                        bool exception_on_error,
27                        bool enable_sequences, 
28                        bool ignore_shadow):
29    gdcmParser(InFilename,exception_on_error,enable_sequences,ignore_shadow)
30
31    
32    // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
33    // We may encounter the 'RETired' (0x0028, 0x0200) tag
34    // (Image Location") . This Element contains the number of
35    // the group that contains the pixel data (hence the "Pixel Data"
36    // is found by indirection through the "Image Location").
37    // Inside the group pointed by "Image Location" the searched element
38    // is conventionally the element 0x0010 (when the norm is respected).
39    // When the "Image Location" is absent we default to group 0x7fe0.
40    
41    // This IS the right place for the code
42  
43       std::string ImageLocation = GetEntryByNumber(0x0028, 0x0200);
44       if ( ImageLocation == GDCM_UNFOUND ) { // Image Location
45          GrPixel = 0x7fe0;                   // default value
46       } else {
47          GrPixel = (guint16) atoi( ImageLocation.c_str() );
48       }   
49       if (GrPixel == 0xe07f) // sometimes Image Location value doesn't follow 
50          GrPixel = 0x7fe0;   // the supposed processor endianity. 
51                              // see gdcmData/cr172241.dcm      
52       if (GrPixel != 0x7fe0) 
53          // This is a kludge for old dirty Philips imager.
54          NumPixel = 0x1010;
55       else
56          NumPixel = 0x0010;
57
58       TagKey key = gdcmDictEntry::TranslateToKey(GrPixel, NumPixel);
59       countGrPixel = GetEntry().count(key);
60 }
61
62 /**
63  * \brief Constructor  
64  * @param exception_on_error whether we want to throw an exception or not
65  */
66 gdcmHeader::gdcmHeader(bool exception_on_error) :
67    gdcmParser(exception_on_error)
68 {
69 }
70
71 /**
72  * \ingroup gdcmHeader
73  * \brief   Canonical destructor.
74  */
75 gdcmHeader::~gdcmHeader (void) {
76 }
77
78 //-----------------------------------------------------------------------------
79 // Print
80
81 // see gdcmParser.cxx
82 //-----------------------------------------------------------------------------
83 // Public
84
85 /**
86  * \ingroup gdcmHeader
87  * \brief  This predicate, based on hopefully reasonable heuristics,
88  *         decides whether or not the current gdcmParser was properly parsed
89  *         and contains the mandatory information for being considered as
90  *         a well formed and usable Dicom/Acr File.
91  * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
92  *         false otherwise. 
93  */
94 bool gdcmHeader::IsReadable(void) {
95    if(!gdcmParser::IsReadable()) {
96       return(false);
97    }
98    std::string res = GetEntryByNumber(0x0028, 0x0005);
99    if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 ) 
100       return false; // Image Dimensions
101    if ( !GetHeaderEntryByNumber(0x0028, 0x0100) )
102       return false; // "Bits Allocated"
103    if ( !GetHeaderEntryByNumber(0x0028, 0x0101) )
104       return false; // "Bits Stored"
105    if ( !GetHeaderEntryByNumber(0x0028, 0x0102) )
106       return false; // "High Bit"
107    if ( !GetHeaderEntryByNumber(0x0028, 0x0103) )
108       return false; // "Pixel Representation" i.e. 'Sign'
109    return true;
110 }
111
112 /**
113  * \ingroup gdcmHeader
114  * \brief   Determines if the Transfer Syntax was already encountered
115  *          and if it corresponds to a JPEGBaseLineProcess1 one.
116  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
117  */
118 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
119    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
120    if ( !Element )
121       return false;
122    LoadHeaderEntrySafe(Element);
123
124    std::string Transfer = Element->GetValue();
125    if ( Transfer == "1.2.840.10008.1.2.4.50" )
126       return true;
127    return false;
128 }
129
130 /**
131  * \ingroup gdcmHeader
132  * \brief   Determines if the Transfer Syntax was already encountered
133  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
134  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
135  */
136 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
137    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
138    if ( !Element )
139       return false;
140    LoadHeaderEntrySafe(Element);
141    return ( Element->GetValue() == "1.2.840.10008.1.2.4.51" );
142 }
143
144 /**
145  * \ingroup gdcmHeader
146  * \brief   Determines if the Transfer Syntax was already encountered
147  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
148  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
149  */
150 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
151    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
152    if ( !Element )
153       return false;
154    LoadHeaderEntrySafe(Element);
155
156    std::string Transfer = Element->GetValue();
157    if ( Transfer == "1.2.840.10008.1.2.4.52" )
158       return true;
159    return false;
160 }
161
162 /**
163  * \ingroup gdcmHeader
164  * \brief   Determines if the Transfer Syntax was already encountered
165  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
166  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all
167  *          other cases.
168  */
169 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
170    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
171    if ( !Element )
172       return false;
173    LoadHeaderEntrySafe(Element);
174
175    std::string Transfer = Element->GetValue();
176    if ( Transfer == "1.2.840.10008.1.2.4.53" )
177       return true;
178    return false;
179 }
180
181 /**
182  * \ingroup gdcmHeader
183  * \brief   Determines if the Transfer Syntax was already encountered
184  *          and if it corresponds to a RLE Lossless one.
185  * @return  True when RLE Lossless found. False in all
186  *          other cases.
187  */
188 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
189    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
190    if ( !Element )
191       return false;
192    LoadHeaderEntrySafe(Element);
193
194    std::string Transfer = Element->GetValue();
195    if ( Transfer == "1.2.840.10008.1.2.5" ) {
196       return true;
197     }
198    return false;
199 }
200
201 /**
202  * \ingroup gdcmHeader
203  * \brief  Determines if Transfer Syntax was already encountered
204  *          and if it corresponds to a JPEG Lossless one. 
205  * @return  True when RLE Lossless found. False in all
206  *          other cases. 
207  */
208 bool gdcmHeader::IsJPEGLossless(void) {
209    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
210     // faire qq chose d'intelligent a la place de ça
211    if ( !Element )
212       return false;
213    LoadHeaderEntrySafe(Element);
214
215    const char * Transfert = Element->GetValue().c_str();
216    if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
217    if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
218    if (Element->GetValue() == "1.2.840.10008.1.2.4.57")   return true;
219
220    return false;
221 }
222
223 /**
224  * \ingroup gdcmHeader
225  * \brief   Determines if the Transfer Syntax was already encountered
226  *          and if it corresponds to a JPEG2000 one
227  * @return  True when JPEG2000 (Lossly or LossLess) found. False in all
228  *          other cases.
229  */
230 bool gdcmHeader::IsJPEG2000(void) {
231    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
232    if ( !Element )
233       return false;
234    LoadHeaderEntrySafe(Element);
235
236    std::string Transfer = Element->GetValue();
237    if (    (Transfer == "1.2.840.10008.1.2.4.90") 
238         || (Transfer == "1.2.840.10008.1.2.4.91") )
239       return true;
240    return false;
241 }
242
243 /**
244  * \ingroup gdcmHeader
245  * \brief   Predicate for dicom version 3 file.
246  * @return  True when the file is a dicom version 3.
247  */
248 bool gdcmHeader::IsDicomV3(void) {
249    // Checking if Transfert Syntax exists is enough
250    // Anyway, it's to late check if the 'Preamble' was found ...
251    // And ... would it be a rich idea to check ?
252    // (some 'no Preamble' DICOM images exist !)
253    return (GetHeaderEntryByNumber(0x0002, 0x0010) != NULL);
254 }
255
256 /**
257  * \ingroup gdcmHeader
258  * \brief   Retrieve the number of columns of image.
259  * @return  The encountered size when found, 0 by default.
260  *          0 means the file is NOT USABLE. The caller will have to check
261  */
262 int gdcmHeader::GetXSize(void) {
263    std::string StrSize;
264    StrSize = GetEntryByNumber(0x0028,0x0011);
265    if (StrSize == GDCM_UNFOUND)
266       return 0;
267    return atoi(StrSize.c_str());
268 }
269
270 /**
271  * \ingroup gdcmHeader
272  * \brief   Retrieve the number of lines of image.
273  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
274  * @return  The encountered size when found, 1 by default 
275  *          (The ACR-MEMA file contains a Signal, not an Image).
276  */
277 int gdcmHeader::GetYSize(void) {
278    std::string StrSize = GetEntryByNumber(0x0028,0x0010);
279    if (StrSize != GDCM_UNFOUND)
280       return atoi(StrSize.c_str());
281    if ( IsDicomV3() )
282       return 0;
283    else
284       // The Rows (0028,0010) entry was optional for ACR/NEMA. It might
285       // hence be a signal (1d image). So we default to 1:
286       return 1;
287 }
288
289 /**
290  * \ingroup gdcmHeader
291  * \brief   Retrieve the number of planes of volume or the number
292  *          of frames of a multiframe.
293  * \warning When present we consider the "Number of Frames" as the third
294  *          dimension. When absent we consider the third dimension as
295  *          being the ACR-NEMA "Planes" tag content.
296  * @return  The encountered size when found, 1 by default (single image).
297  */
298 int gdcmHeader::GetZSize(void) {
299    // Both  DicomV3 and ACR/Nema consider the "Number of Frames"
300    // as the third dimension.
301    std::string StrSize = GetEntryByNumber(0x0028,0x0008);
302    if (StrSize != GDCM_UNFOUND)
303       return atoi(StrSize.c_str());
304
305    // We then consider the "Planes" entry as the third dimension 
306    StrSize = GetEntryByNumber(0x0028,0x0012);
307    if (StrSize != GDCM_UNFOUND)
308       return atoi(StrSize.c_str());
309    return 1;
310 }
311
312 /**
313  * \ingroup gdcmHeader
314  * \brief   Retrieve the number of Bits Stored (actually used)
315  *          (as opposite to number of Bits Allocated)
316  * @return  The encountered number of Bits Stored, 0 by default.
317  *          0 means the file is NOT USABLE. The caller has to check it !
318  */
319 int gdcmHeader::GetBitsStored(void) {  
320    std::string StrSize = GetEntryByNumber(0x0028,0x0101);
321    if (StrSize == GDCM_UNFOUND)
322       return 0;  // It's supposed to be mandatory
323                  // the caller will have to check
324    return atoi(StrSize.c_str());
325 }
326
327 /**
328  * \ingroup gdcmHeader
329  * \brief   Retrieve the number of Bits Allocated
330  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
331  * @return  The encountered number of Bits Allocated, 0 by default.
332  *          0 means the file is NOT USABLE. The caller has to check it !
333  */
334 int gdcmHeader::GetBitsAllocated(void) {
335    std::string StrSize = GetEntryByNumber(0x0028,0x0100);
336    if (StrSize == GDCM_UNFOUND)
337       return 0; // It's supposed to be mandatory
338                 // the caller will have to check
339    return atoi(StrSize.c_str());
340 }
341
342 /**
343  * \ingroup gdcmHeader
344  * \brief   Retrieve the number of Samples Per Pixel
345  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
346  * @return  The encountered number of Samples Per Pixel, 1 by default.
347  *          (Gray level Pixels)
348  */
349 int gdcmHeader::GetSamplesPerPixel(void) {
350    std::string StrSize = GetEntryByNumber(0x0028,0x0002);
351    if (StrSize == GDCM_UNFOUND)
352       return 1; // Well, it's supposed to be mandatory ...
353                 // but sometimes it's missing : *we* assume Gray pixels
354    return atoi(StrSize.c_str());
355 }
356
357 /**
358  * \ingroup gdcmHeader
359  * \brief   Retrieve the Planar Configuration for RGB images
360  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
361  * @return  The encountered Planar Configuration, 0 by default.
362  */
363 int gdcmHeader::GetPlanarConfiguration(void) {
364    std::string StrSize = GetEntryByNumber(0x0028,0x0006);
365    if (StrSize == GDCM_UNFOUND)
366       return 0;
367    return atoi(StrSize.c_str());
368 }
369
370 /**
371  * \ingroup gdcmHeader
372  * \brief   Return the size (in bytes) of a single pixel of data.
373  * @return  The size in bytes of a single pixel of data; 0 by default
374  *          0 means the file is NOT USABLE; the caller will have to check        
375  */
376 int gdcmHeader::GetPixelSize(void) {
377    std::string PixelType = GetPixelType();
378    if (PixelType == "8U"  || PixelType == "8S")
379       return 1;
380    if (PixelType == "16U" || PixelType == "16S")
381       return 2;
382    if (PixelType == "32U" || PixelType == "32S")
383       return 4;
384    if (PixelType == "FD")
385       return 8;         
386    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
387    return 0;
388 }
389
390 /**
391  * \ingroup gdcmHeader
392  * \brief   Build the Pixel Type of the image.
393  *          Possible values are:
394  *          - 8U  unsigned  8 bit,
395  *          - 8S    signed  8 bit,
396  *          - 16U unsigned 16 bit,
397  *          - 16S   signed 16 bit,
398  *          - 32U unsigned 32 bit,
399  *          - 32S   signed 32 bit,
400  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
401  * \warning 12 bit images appear as 16 bit.
402  *          24 bit images appear as 8 bit
403  * @return  0S if nothing found. NOT USABLE file. The caller has to check
404  */
405 std::string gdcmHeader::GetPixelType(void) { 
406    std::string BitsAlloc = GetEntryByNumber(0x0028, 0x0100); // Bits Allocated
407    if (BitsAlloc == GDCM_UNFOUND) {
408       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
409       BitsAlloc = std::string("16");
410    }
411    if (BitsAlloc == "64")            // )
412       return ("FD");
413    if (BitsAlloc == "12")            // It will be unpacked
414       BitsAlloc = std::string("16");
415    else if (BitsAlloc == "24")       // (in order no to be messed up
416       BitsAlloc = std::string("8");  // by old RGB images)
417      
418    std::string Signed = GetEntryByNumber(0x0028, 0x0103); // "Pixel Representation"
419    if (Signed == GDCM_UNFOUND) {
420       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
421       BitsAlloc = std::string("0");
422    }
423    if (Signed == "0")
424       Signed = std::string("U");
425    else
426       Signed = std::string("S");
427
428    return( BitsAlloc + Signed);
429 }
430
431
432 /**
433  * \ingroup gdcmHeader
434  * \brief   Recover the offset (from the beginning of the file) 
435  *          of *image* pixels (not *icone image* pixels, if any !)
436  * @return Pixel Offset
437  */
438 size_t gdcmHeader::GetPixelOffset(void) { 
439    //
440    // If the element (0x0088,0x0200) 'icone image sequence' is found
441    // (grPixel,numPixel) is stored twice : the first one for the icon
442    // the second one for the image ...
443    // pb : sometimes , (0x0088,0x0200) exists, but doesn't contain *anything*
444    // see gdcmData/MxTwinLossLess.dcm ...
445
446    //std::string icone = GetEntryByNumber(0x0088,0x0200); //icone image sequence
447       
448    IterHT it = GetHeaderEntrySameNumber(GrPixel,NumPixel);          
449    TagKey key = gdcmDictEntry::TranslateToKey(GrPixel,NumPixel);
450    gdcmHeaderEntry* PixelElement;
451    if (countGrPixel == 1)   
452       PixelElement = (it.first)->second;
453    else {
454       PixelElement = (++it.first)->second; // hope there are no more than 2 !
455    } 
456    if (PixelElement) {
457       return PixelElement->GetOffset();
458    } else {
459 /*      std::cout << "Big trouble : Pixel Element ("
460                 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found"
461                 << std::endl;  */
462       return 0;
463    }     
464 }
465 // TODO : unify those two (previous one and next one)
466 /**
467  * \ingroup gdcmHeader
468  * \brief   Recover the pixel area length (in Bytes)
469  * @return Pixel Element Length, as stored in the header
470  *         (NOT the memory space necessary to hold the Pixels 
471  *          -in case of embeded compressed image-)
472  *         0 : NOT USABLE file. The caller has to check.
473  */
474 size_t gdcmHeader::GetPixelAreaLength(void) { 
475           
476    IterHT it = GetHeaderEntrySameNumber(GrPixel,NumPixel);          
477    TagKey key = gdcmDictEntry::TranslateToKey(GrPixel,NumPixel);
478    gdcmHeaderEntry* PixelElement;
479   
480   if (countGrPixel==1)  
481       PixelElement = (it.first)->second;
482    else
483       PixelElement = (++it.first)->second;
484
485    if (PixelElement) {
486       return PixelElement->GetLength();
487    } else {
488 /*      std::cout << "Big trouble : Pixel Element ("
489                 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found"
490                 << std::endl;*/
491       return 0;
492    }
493 }
494
495 /**
496   * \ingroup gdcmHeader
497   * \brief tells us if LUT are used
498   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
499   *          are NOT considered as LUT, since nobody knows
500   *          how to deal with them
501   *          Please warn me if you know sbdy that *does* know ... jprx
502   * @return true if LUT Descriptors and LUT Tables were found 
503   */
504 bool gdcmHeader::HasLUT(void) {
505
506    // Check the presence of the LUT Descriptors, and LUT Tables    
507    // LutDescriptorRed    
508    if ( !GetHeaderEntryByNumber(0x0028,0x1101) )
509       return false;
510    // LutDescriptorGreen 
511    if ( !GetHeaderEntryByNumber(0x0028,0x1102) )
512       return false;
513    // LutDescriptorBlue 
514    if ( !GetHeaderEntryByNumber(0x0028,0x1103) )
515       return false;   
516    // Red Palette Color Lookup Table Data
517    if ( !GetHeaderEntryByNumber(0x0028,0x1201) )
518       return false; 
519    // Green Palette Color Lookup Table Data       
520    if ( !GetHeaderEntryByNumber(0x0028,0x1202) )
521       return false;
522    // Blue Palette Color Lookup Table Data      
523    if ( !GetHeaderEntryByNumber(0x0028,0x1203) )
524       return false;   
525    return true;
526 }
527
528 /**
529   * \ingroup gdcmHeader
530   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
531   *             else 0
532   * @return Lookup Table number of Bits , 0 by default
533   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
534   * @ return bit number of each LUT item 
535   */
536 int gdcmHeader::GetLUTNbits(void) {
537    std::vector<std::string> tokens;
538    //int LutLength;
539    //int LutDepth;
540    int LutNbits;
541    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
542    // Consistency already checked in GetLUTLength
543    std::string LutDescription = GetEntryByNumber(0x0028,0x1101);
544    if (LutDescription == GDCM_UNFOUND)
545       return 0;
546    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
547    Tokenize (LutDescription, tokens, "\\");
548    //LutLength=atoi(tokens[0].c_str());
549    //LutDepth=atoi(tokens[1].c_str());
550    LutNbits=atoi(tokens[2].c_str());
551    tokens.clear();
552    return LutNbits;
553 }
554
555 /**
556   * \ingroup gdcmHeader
557   * \brief builts Red/Green/Blue/Alpha LUT from Header
558   *         when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
559   *          and (0028,1101),(0028,1102),(0028,1102)  
560   *            - xxx Palette Color Lookup Table Descriptor - are found
561   *          and (0028,1201),(0028,1202),(0028,1202) 
562   *            - xxx Palette Color Lookup Table Data - are found 
563   * \warning does NOT deal with :
564   *   0028 1100 Gray Lookup Table Descriptor (Retired)
565   *   0028 1221 Segmented Red Palette Color Lookup Table Data
566   *   0028 1222 Segmented Green Palette Color Lookup Table Data
567   *   0028 1223 Segmented Blue Palette Color Lookup Table Data 
568   *   no known Dicom reader deals with them :-(
569   * @return a RGBA Lookup Table 
570   */ 
571 unsigned char * gdcmHeader::GetLUTRGBA(void) {
572 // Not so easy : see 
573 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
574
575 //  if Photometric Interpretation # PALETTE COLOR, no LUT to be done
576    if (GetEntryByNumber(0x0028,0x0004) != "PALETTE COLOR ") {
577       return NULL;
578    }  
579    int lengthR, debR, nbitsR;
580    int lengthG, debG, nbitsG;
581    int lengthB, debB, nbitsB;
582    
583 // Get info from Lut Descriptors
584 // (the 3 LUT descriptors may be different)    
585    std::string LutDescriptionR = GetEntryByNumber(0x0028,0x1101);
586    if (LutDescriptionR == GDCM_UNFOUND)
587       return NULL;
588    std::string LutDescriptionG = GetEntryByNumber(0x0028,0x1102);
589    if (LutDescriptionG == GDCM_UNFOUND)
590       return NULL;   
591    std::string LutDescriptionB = GetEntryByNumber(0x0028,0x1103);
592    if (LutDescriptionB == GDCM_UNFOUND)
593       return NULL;
594       
595    std::vector<std::string> tokens;
596       
597    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
598    Tokenize (LutDescriptionR, tokens, "\\");
599    lengthR=atoi(tokens[0].c_str()); // Red LUT length in Bytes
600    debR   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
601    nbitsR =atoi(tokens[2].c_str()); // Lut item size (in Bits)
602    tokens.clear();
603    
604    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
605    Tokenize (LutDescriptionG, tokens, "\\");
606    lengthG=atoi(tokens[0].c_str()); // Green LUT length in Bytes
607    debG   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
608    nbitsG =atoi(tokens[2].c_str()); // Lut item size (in Bits)
609    tokens.clear();  
610    
611    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
612    Tokenize (LutDescriptionB, tokens, "\\");
613    lengthB=atoi(tokens[0].c_str()); // Blue LUT length in Bytes
614    debB   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
615    nbitsB =atoi(tokens[2].c_str()); // Lut item size (in Bits)
616    tokens.clear();
617  
618    // Load LUTs into memory, (as they were stored on disk)
619    unsigned char *lutR = (unsigned char *)
620                          GetEntryVoidAreaByNumber(0x0028,0x1201);
621    unsigned char *lutG = (unsigned char *)
622                          GetEntryVoidAreaByNumber(0x0028,0x1202);
623    unsigned char *lutB = (unsigned char *)
624                          GetEntryVoidAreaByNumber(0x0028,0x1203); 
625    
626    if (!lutR || !lutG || !lutB ) {
627       return NULL;
628    } 
629    // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT 
630    
631    unsigned char *LUTRGBA = (unsigned char *)calloc(1024,1); // 256 * 4 (R, G, B, Alpha) 
632    if (!LUTRGBA) {
633       return NULL;
634    }
635    memset(LUTRGBA, 0, 1024);
636    // Bits Allocated
637    int nb;
638    std::string str_nb = GetEntryByNumber(0x0028,0x0100);
639    if (str_nb == GDCM_UNFOUND ) {
640       nb = 16;
641    } else {
642       nb = atoi(str_nb.c_str() );
643    }  
644    int mult;
645
646    if (nbitsR==16 && nb==8) // when LUT item size is different than pixel size
647       mult=2;               // high byte must be = low byte 
648    else                     // See PS 3.3-2003 C.11.1.1.2 p 619
649       mult=1; 
650  
651    // if we get a black image, let's just remove the '+1'
652    // from 'i*mult+1' and check again 
653    // if it works, we shall have to check the 3 Palettes
654    // to see which byte is ==0 (first one, or second one)
655    // and fix the code
656    // We give up the checking to avoid some (useless ?)overhead 
657    // (optimistic asumption)
658    unsigned char *a;      
659    int i;
660
661    a = LUTRGBA+0;
662    for(i=0;i<lengthR;i++) {
663       *a = lutR[i*mult+1]; 
664       a+=4;       
665    }        
666    a = LUTRGBA+1;
667    for(i=0;i<lengthG;i++) {
668       *a = lutG[i*mult+1]; 
669       a+=4;       
670    }  
671    a = LUTRGBA+2;
672    for(i=0;i<lengthB;i++) {
673       *a = lutB[i*mult+1]; 
674       a+=4;       
675    }  
676    a = LUTRGBA+3;
677    for(i=0;i<256;i++) {
678       *a = 1; // Alpha component
679       a+=4; 
680    } 
681    
682    //How to free the now useless LUTs?
683    //free(LutR); free(LutB); free(LutG); // Seg Fault when used
684    return(LUTRGBA);   
685
686
687 /**
688  * \ingroup gdcmHeader
689  * \brief gets the info from 0002,0010 : Transfert Syntax and gdcmTS
690  *        else 1.
691  * @return the full Transfert Syntax Name (as oposite to Transfert Syntax UID)
692  */
693 std::string gdcmHeader::GetTransfertSyntaxName(void) { 
694    // use the gdcmTS (TS : Transfert Syntax)
695    std::string TransfertSyntax = GetEntryByNumber(0x0002,0x0010);
696    if (TransfertSyntax == GDCM_UNFOUND) {
697       dbg.Verbose(0, "gdcmHeader::GetTransfertSyntaxName: unfound Transfert Syntax (0002,0010)");
698       return "Uncompressed ACR-NEMA";
699    }
700    // we do it only when we need it
701    gdcmTS * ts = gdcmGlobal::GetTS();
702    std::string tsName=ts->GetValue(TransfertSyntax);
703    //delete ts; // Seg Fault when deleted ?!
704    return tsName;
705 }
706
707 /**
708  * \ingroup   gdcmHeader
709  * \brief Sets the Pixel Area size in the Header
710  *        --> not-for-rats function
711  * @param ImageDataSize new Pixel Area Size
712  *        warning : nothing else is checked
713  */
714 void gdcmHeader::SetImageDataSize(size_t ImageDataSize) {
715    std::string content1;
716    char car[20];
717
718    // Assumes HeaderEntry (GrPixel, NumPixel) is unique ...   
719    // TODO deal with multiplicity (see gdcmData/icone.dcm)
720    sprintf(car,"%d",ImageDataSize);
721  
722    gdcmHeaderEntry *a = GetHeaderEntryByNumber(GrPixel, NumPixel);
723    a->SetLength(ImageDataSize);
724
725    ImageDataSize+=8;
726    sprintf(car,"%d",ImageDataSize);
727    content1=car;
728    SetEntryByNumber(content1, GrPixel, NumPixel);
729 }
730
731
732 /**
733  * \ingroup   gdcmHeader
734  * \brief compares 2 Headers, according to DICOMDIR rules
735  *        --> not-for-rats function
736  * \warning does NOT work with ACR-NEMA files
737  * \todo find a trick to solve the pb (use RET fields ?)
738  * @param header 
739  * @return true if 'smaller'
740  */
741  bool gdcmHeader::operator<(gdcmHeader &header){
742    std::string s1,s2;
743
744    // Patient Name
745    s1=this->GetEntryByNumber(0x0010,0x0010);
746    s2=header.GetEntryByNumber(0x0010,0x0010);
747    if(s1 < s2)
748       return(true);
749    else if(s1 > s2)
750       return(false);
751    else
752    {
753       // Patient ID
754       s1=this->GetEntryByNumber(0x0010,0x0020);
755       s2=header.GetEntryByNumber(0x0010,0x0020);
756       if (s1 < s2)
757          return(true);
758       else if (s1 > s2)
759          return(1);
760       else
761       {
762          // Study Instance UID
763          s1=this->GetEntryByNumber(0x0020,0x000d);
764          s2=header.GetEntryByNumber(0x0020,0x000d);
765          if (s1 < s2)
766             return(true);
767          else if(s1 > s2)
768             return(false);
769          else
770          {
771             // Serie Instance UID
772             s1=this->GetEntryByNumber(0x0020,0x000e);
773             s2=header.GetEntryByNumber(0x0020,0x000e);
774             if (s1 < s2)
775                return(true);
776             else if(s1 > s2)
777                return(false);
778          }
779       }
780    }
781    return(false);
782 }
783
784 bool gdcmHeader::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
785 {
786    guint32 length = tag->GetLength();
787                                                                                 
788    // The value of a tag MUST (see the DICOM norm) be an odd number of
789    // bytes. When this is not the case, pad with an additional byte:
790    if(length%2==1)
791    {
792       tag->SetValue(tag->GetValue()+"\0");
793       tag->SetLength(tag->GetReadLength()+1);
794    }
795                                                                                 
796    WriteEntryTagVRLength(tag, _fp, type);
797                                                                                 
798    // Pixels are never loaded in the element !
799    // we stop writting when Pixel are processed
800    // FIX : we loose trailing elements (RAB, right now)
801    guint16 el     = tag->GetElement();
802    guint16 group  = tag->GetGroup();
803    int compte =0;
804    if ((group == GrPixel) && (el == NumPixel) ) {
805       compte++;
806       if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel
807          return false;
808       }
809    }
810    WriteEntryValue(tag, _fp, type);
811    return true;
812 }
813
814 //-----------------------------------------------------------------------------
815 // Protected
816
817 /**
818  * \ingroup   gdcmHeader
819  * \brief anonymize a Header (removes Patient's personal info)
820  *        (read the code to see which ones ...)
821  */
822 bool gdcmHeader::anonymizeHeader() {
823
824   gdcmHeaderEntry *patientNameHE = GetHeaderEntryByNumber (0x0010, 0x0010);
825  // gdcmHeaderEntry *patientIDHE   = GetHeaderEntryByNumber (0x0010, 0x0020); 
826     
827   ReplaceIfExistByNumber ("  ",0x0010, 0x2154); // Telephone   
828   ReplaceIfExistByNumber ("  ",0x0010, 0x1040); // Adress
829   ReplaceIfExistByNumber ("  ",0x0010, 0x0020); // Patient ID
830   
831   if (patientNameHE) {
832      std::string StudyInstanceUID =  GetEntryByNumber (0x0020, 0x000d);
833      if (StudyInstanceUID !=GDCM_UNFOUND)
834         ReplaceOrCreateByNumber(StudyInstanceUID, 0x0010, 0x0010);
835      else
836         ReplaceOrCreateByNumber(std::string("anonymised"), 0x0010, 0x0010);
837   }
838   
839   // Just for fun :-(
840   // (if any) remove or replace all the stuff that contains a Date
841   
842 //0008 0012 DA ID Instance Creation Date
843 //0008 0020 DA ID Study Date
844 //0008 0021 DA ID Series Date
845 //0008 0022 DA ID Acquisition Date
846 //0008 0023 DA ID Content Date
847 //0008 0024 DA ID Overlay Date
848 //0008 0025 DA ID Curve Date
849 //0008 002a DT ID Acquisition Datetime
850 //0018 9074 DT ACQ Frame Acquisition Datetime
851 //0018 9151 DT ACQ Frame Reference Datetime
852 //0018 a002 DT ACQ Contribution Date Time
853 //0020 3403 SH REL Modified Image Date (RET)
854 //0032 0032 DA SDY Study Verified Date
855 //0032 0034 DA SDY Study Read Date
856 //0032 1000 DA SDY Scheduled Study Start Date
857 //0032 1010 DA SDY Scheduled Study Stop Date
858 //0032 1040 DA SDY Study Arrival Date
859 //0032 1050 DA SDY Study Completion Date
860 //0038 001a DA VIS Scheduled Admission Date
861 //0038 001c DA VIS Scheduled Discharge Date
862 //0038 0020 DA VIS Admitting Date
863 //0038 0030 DA VIS Discharge Date
864 //0040 0002 DA PRC Scheduled Procedure Step Start Date
865 //0040 0004 DA PRC Scheduled Procedure Step End Date
866 //0040 0244 DA PRC Performed Procedure Step Start Date
867 //0040 0250 DA PRC Performed Procedure Step End Date
868 //0040 2004 DA PRC Issue Date of Imaging Service Request
869 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
870 //0040 4011 DT PRC Expected Completion Date and Time
871 //0040 a030 DT PRC Verification Date Time
872 //0040 a032 DT PRC Observation Date Time
873 //0040 a120 DT PRC DateTime
874 //0040 a121 DA PRC Date
875 //0040 a13a DT PRC Referenced Datetime
876 //0070 0082 DA ??? Presentation Creation Date
877 //0100 0420 DT ??? SOP Autorization Date and Time
878 //0400 0105 DT ??? Digital Signature DateTime
879 //2100 0040 DA PJ Creation Date
880 //3006 0008 DA SSET Structure Set Date
881 //3008 0024 DA ??? Treatment Control Point Date
882 //3008 0054 DA ??? First Treatment Date
883 //3008 0056 DA ??? Most Recent Treatment Date
884 //3008 0162 DA ??? Safe Position Exit Date
885 //3008 0166 DA ??? Safe Position Return Date
886 //3008 0250 DA ??? Treatment Date
887 //300a 0006 DA RT RT Plan Date
888 //300a 022c DA RT Air Kerma Rate Reference Date
889 //300e 0004 DA RT Review Date
890  return true;  
891 }
892 //-----------------------------------------------------------------------------
893 // Private
894
895 //-----------------------------------------------------------------------------