]> Creatis software - gdcm.git/blob - src/gdcmPixelReadConvert.cxx
Taking into account MONOCHROME1 + Signed Pixels (?!)
[gdcm.git] / src / gdcmPixelReadConvert.cxx
1 /*=========================================================================
2
3   Program:   gdcm
4   Module:    $RCSfile: gdcmPixelReadConvert.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/02/16 10:19:19 $
7   Version:   $Revision: 1.51 $
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 #include "gdcmDebug.h"
20 #include "gdcmFile.h"
21 #include "gdcmGlobal.h"
22 #include "gdcmTS.h"
23 #include "gdcmPixelReadConvert.h"
24 #include "gdcmDocEntry.h"
25 #include "gdcmRLEFramesInfo.h"
26 #include "gdcmJPEGFragmentsInfo.h"
27
28 #include <fstream>
29 #include <stdio.h> //for sscanf
30
31 namespace gdcm
32 {
33 //-----------------------------------------------------------------------------
34 #define str2num(str, typeNum) *((typeNum *)(str))
35
36 //-----------------------------------------------------------------------------
37 // Constructor / Destructor
38 /// Constructor
39 PixelReadConvert::PixelReadConvert() 
40 {
41    RGB          = 0;
42    RGBSize      = 0;
43    Raw          = 0;
44    RawSize      = 0;
45    LutRGBA      = 0;
46    LutRedData   = 0;
47    LutGreenData = 0;
48    LutBlueData  = 0;
49 }
50
51 /// Canonical Destructor
52 PixelReadConvert::~PixelReadConvert() 
53 {
54    Squeeze();
55 }
56
57 //-----------------------------------------------------------------------------
58 // Public
59 /**
60  * \brief Predicate to know whether the image[s] (once Raw) is RGB.
61  * \note See comments of \ref ConvertHandleColor
62  */
63 bool PixelReadConvert::IsRawRGB()
64 {
65    if (   IsMonochrome
66        || PlanarConfiguration == 2
67        || IsPaletteColor )
68    {
69       return false;
70    }
71    return true;
72 }
73 /**
74  * \brief Gets various usefull informations from the file header
75  * @param file gdcm::File pointer
76  */
77 void PixelReadConvert::GrabInformationsFromFile( File *file )
78 {
79    // Number of Bits Allocated for storing a Pixel is defaulted to 16
80    // when absent from the file.
81    BitsAllocated = file->GetBitsAllocated();
82    if ( BitsAllocated == 0 )
83    {
84       BitsAllocated = 16;
85    }
86
87    // Number of "Bits Stored", defaulted to number of "Bits Allocated"
88    // when absent from the file.
89    BitsStored = file->GetBitsStored();
90    if ( BitsStored == 0 )
91    {
92       BitsStored = BitsAllocated;
93    }
94
95    // High Bit Position, defaulted to "Bits Allocated" - 1
96    HighBitPosition = file->GetHighBitPosition();
97    if ( HighBitPosition == 0 )
98    {
99       HighBitPosition = BitsAllocated - 1;
100    }
101
102    XSize           = file->GetXSize();
103    YSize           = file->GetYSize();
104    ZSize           = file->GetZSize();
105    SamplesPerPixel = file->GetSamplesPerPixel();
106    PixelSize       = file->GetPixelSize();
107    PixelSign       = file->IsSignedPixelData();
108    SwapCode        = file->GetSwapCode();
109    std::string ts  = file->GetTransferSyntax();
110    IsRaw =
111         ( ! file->IsDicomV3() )
112      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
113      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
114      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
115      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
116      || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
117
118    IsJPEG2000      = Global::GetTS()->IsJPEG2000(ts);
119    IsJPEGLS        = Global::GetTS()->IsJPEGLS(ts);
120    IsJPEGLossy     = Global::GetTS()->IsJPEGLossy(ts);
121    IsJPEGLossless  = Global::GetTS()->IsJPEGLossless(ts);
122    IsRLELossless   = Global::GetTS()->IsRLELossless(ts);
123
124    PixelOffset     = file->GetPixelOffset();
125    PixelDataLength = file->GetPixelAreaLength();
126    RLEInfo         = file->GetRLEInfo();
127    JPEGInfo        = file->GetJPEGInfo();
128
129    IsMonochrome    = file->IsMonochrome();
130    IsMonochrome1   = file->IsMonochrome1();
131    IsPaletteColor  = file->IsPaletteColor();
132    IsYBRFull       = file->IsYBRFull();
133
134    PlanarConfiguration = file->GetPlanarConfiguration();
135
136    /////////////////////////////////////////////////////////////////
137    // LUT section:
138    HasLUT = file->HasLUT();
139    if ( HasLUT )
140    {
141       // Just in case some access to a File element requires disk access.
142       LutRedDescriptor   = file->GetEntryValue( 0x0028, 0x1101 );
143       LutGreenDescriptor = file->GetEntryValue( 0x0028, 0x1102 );
144       LutBlueDescriptor  = file->GetEntryValue( 0x0028, 0x1103 );
145    
146       // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
147       // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
148       // Document::Document() ], the loading of the value (content) of a
149       // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
150       // loaded). Hence, we first try to obtain the LUTs data from the file
151       // and when this fails we read the LUTs data directly from disk.
152       // \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
153       //       We should NOT bypass the [Bin|Val]Entry class. Instead
154       //       an access to an UNLOADED content of a [Bin|Val]Entry occurence
155       //       (e.g. BinEntry::GetBinArea()) should force disk access from
156       //       within the [Bin|Val]Entry class itself. The only problem
157       //       is that the [Bin|Val]Entry is unaware of the FILE* is was
158       //       parsed from. Fix that. FIXME.
159    
160       // //// Red round
161       file->LoadEntryBinArea(0x0028, 0x1201);
162       LutRedData = (uint8_t*)file->GetEntryBinArea( 0x0028, 0x1201 );
163       if ( ! LutRedData )
164       {
165          gdcmWarningMacro( "Unable to read Red LUT data" );
166       }
167
168       // //// Green round:
169       file->LoadEntryBinArea(0x0028, 0x1202);
170       LutGreenData = (uint8_t*)file->GetEntryBinArea(0x0028, 0x1202 );
171       if ( ! LutGreenData)
172       {
173          gdcmWarningMacro( "Unable to read Green LUT data" );
174       }
175
176       // //// Blue round:
177       file->LoadEntryBinArea(0x0028, 0x1203);
178       LutBlueData = (uint8_t*)file->GetEntryBinArea( 0x0028, 0x1203 );
179       if ( ! LutBlueData )
180       {
181          gdcmWarningMacro( "Unable to read Blue LUT data" );
182       }
183    }
184
185    ComputeRawAndRGBSizes();
186 }
187
188 /// \brief Reads from disk and decompresses Pixels
189 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
190 {
191    // ComputeRawAndRGBSizes is already made by 
192    // ::GrabInformationsFromfile. So, the structure sizes are
193    // correct
194    Squeeze();
195
196    //////////////////////////////////////////////////
197    //// First stage: get our hands on the Pixel Data.
198    if ( !fp )
199    {
200       gdcmWarningMacro( "Unavailable file pointer." );
201       return false;
202    }
203
204    fp->seekg( PixelOffset, std::ios::beg );
205    if( fp->fail() || fp->eof())
206    {
207       gdcmWarningMacro( "Unable to find PixelOffset in file." );
208       return false;
209    }
210
211    AllocateRaw();
212
213    //////////////////////////////////////////////////
214    //// Second stage: read from disk dans decompress.
215    if ( BitsAllocated == 12 )
216    {
217       ReadAndDecompress12BitsTo16Bits( fp);
218    }
219    else if ( IsRaw )
220    {
221       // This problem can be found when some obvious informations are found
222       // after the field containing the image data. In this case, these
223       // bad data are added to the size of the image (in the PixelDataLength
224       // variable). But RawSize is the right size of the image !
225       if( PixelDataLength != RawSize)
226       {
227          gdcmWarningMacro( "Mismatch between PixelReadConvert : "
228                             << PixelDataLength << " and RawSize : " << RawSize );
229       }
230       if( PixelDataLength > RawSize)
231       {
232          fp->read( (char*)Raw, RawSize);
233       }
234       else
235       {
236          fp->read( (char*)Raw, PixelDataLength);
237       }
238
239       if ( fp->fail() || fp->eof())
240       {
241          gdcmWarningMacro( "Reading of Raw pixel data failed." );
242          return false;
243       }
244    } 
245    else if ( IsRLELossless )
246    {
247       if ( ! RLEInfo->DecompressRLEFile( fp, Raw, XSize, YSize, ZSize, BitsAllocated ) )
248       {
249          gdcmWarningMacro( "RLE decompressor failed." );
250          return false;
251       }
252    }
253    else
254    {
255       // Default case concerns JPEG family
256       if ( ! ReadAndDecompressJPEGFile( fp ) )
257       {
258          gdcmWarningMacro( "JPEG decompressor failed." );
259          return false;
260       }
261    }
262
263    ////////////////////////////////////////////
264    //// Third stage: twigle the bytes and bits.
265    ConvertReorderEndianity();
266    ConvertReArrangeBits();
267    ConvertFixGreyLevels();
268    ConvertHandleColor();
269
270    return true;
271 }
272
273 /// Deletes Pixels Area
274 void PixelReadConvert::Squeeze() 
275 {
276    if ( RGB )
277       delete [] RGB;
278    RGB = 0;
279
280    if ( Raw )
281       delete [] Raw;
282    Raw = 0;
283
284    if ( LutRGBA )
285       delete [] LutRGBA;
286    LutRGBA = 0;
287 }
288
289 /**
290  * \brief Build the RGB image from the Raw imagage and the LUTs.
291  */
292 bool PixelReadConvert::BuildRGBImage()
293 {
294    if ( RGB )
295    {
296       // The job is already done.
297       return true;
298    }
299
300    if ( ! Raw )
301    {
302       // The job can't be done
303       return false;
304    }
305
306    BuildLUTRGBA();
307    if ( ! LutRGBA )
308    {
309       // The job can't be done
310       return false;
311    }
312                                                                                 
313    // Build RGB Pixels
314    AllocateRGB();
315    uint8_t *localRGB = RGB;
316    for (size_t i = 0; i < RawSize; ++i )
317    {
318       int j  = Raw[i] * 4;
319       *localRGB++ = LutRGBA[j];
320       *localRGB++ = LutRGBA[j+1];
321       *localRGB++ = LutRGBA[j+2];
322    }
323    return true;
324 }
325
326 //-----------------------------------------------------------------------------
327 // Protected
328
329 //-----------------------------------------------------------------------------
330 // Private
331 /**
332  * \brief Read from file a 12 bits per pixel image and decompress it
333  *        into a 16 bits per pixel image.
334  */
335 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
336                throw ( FormatError )
337 {
338    int nbPixels = XSize * YSize;
339    uint16_t *localDecompres = (uint16_t*)Raw;
340
341    for( int p = 0; p < nbPixels; p += 2 )
342    {
343       uint8_t b0, b1, b2;
344
345       fp->read( (char*)&b0, 1);
346       if ( fp->fail() || fp->eof() )
347       {
348          throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
349                                 "Unfound first block" );
350       }
351
352       fp->read( (char*)&b1, 1 );
353       if ( fp->fail() || fp->eof())
354       {
355          throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
356                                 "Unfound second block" );
357       }
358
359       fp->read( (char*)&b2, 1 );
360       if ( fp->fail() || fp->eof())
361       {
362          throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
363                                 "Unfound second block" );
364       }
365
366       // Two steps are necessary to please VC++
367       //
368       // 2 pixels 12bit =     [0xABCDEF]
369       // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
370       //                        A                     B                 D
371       *localDecompres++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
372       //                        F                     C                 E
373       *localDecompres++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
374
375       /// \todo JPR Troubles expected on Big-Endian processors ?
376    }
377 }
378
379 /**
380  * \brief     Reads from disk the Pixel Data of JPEG Dicom encapsulated
381  *            file and decompress it.
382  * @param     fp File Pointer
383  * @return    Boolean
384  */
385 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
386 {
387    if ( IsJPEG2000 )
388    {
389       gdcmWarningMacro( "Sorry, JPEG2000 not yet taken into account" );
390       fp->seekg( JPEGInfo->GetFirstFragment()->GetOffset(), std::ios::beg);
391 //    if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
392           return false;
393    }
394
395    if ( IsJPEGLS )
396    {
397       gdcmWarningMacro( "Sorry, JPEG-LS not yet taken into account" );
398       fp->seekg( JPEGInfo->GetFirstFragment()->GetOffset(), std::ios::beg);
399 //    if ( ! gdcm_read_JPEGLS_file( fp,Raw ) )
400          return false;
401    }
402
403    // else ??
404    // Precompute the offset localRaw will be shifted with
405    int length = XSize * YSize * SamplesPerPixel;
406    int numberBytes = BitsAllocated / 8;
407
408    JPEGInfo->DecompressFromFile(fp, Raw, BitsStored, numberBytes, length );
409    return true;
410 }
411
412 /**
413  * \brief Build Red/Green/Blue/Alpha LUT from File
414  *         when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
415  *          and (0028,1101),(0028,1102),(0028,1102)
416  *            - xxx Palette Color Lookup Table Descriptor - are found
417  *          and (0028,1201),(0028,1202),(0028,1202)
418  *            - xxx Palette Color Lookup Table Data - are found
419  * \warning does NOT deal with :
420  *   0028 1100 Gray Lookup Table Descriptor (Retired)
421  *   0028 1221 Segmented Red Palette Color Lookup Table Data
422  *   0028 1222 Segmented Green Palette Color Lookup Table Data
423  *   0028 1223 Segmented Blue Palette Color Lookup Table Data
424  *   no known Dicom reader deals with them :-(
425  * @return a RGBA Lookup Table
426  */
427 void PixelReadConvert::BuildLUTRGBA()
428 {
429    if ( LutRGBA )
430    {
431       return;
432    }
433    // Not so easy : see
434    // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
435                                                                                 
436    if ( ! IsPaletteColor )
437    {
438       return;
439    }
440                                                                                 
441    if (   LutRedDescriptor   == GDCM_UNFOUND
442        || LutGreenDescriptor == GDCM_UNFOUND
443        || LutBlueDescriptor  == GDCM_UNFOUND )
444    {
445       return;
446    }
447
448    ////////////////////////////////////////////
449    // Extract the info from the LUT descriptors
450    int lengthR;   // Red LUT length in Bytes
451    int debR;      // Subscript of the first Lut Value
452    int nbitsR;    // Lut item size (in Bits)
453    int nbRead = sscanf( LutRedDescriptor.c_str(),
454                         "%d\\%d\\%d",
455                         &lengthR, &debR, &nbitsR );
456    if( nbRead != 3 )
457    {
458       gdcmWarningMacro( "Wrong Red LUT descriptor" );
459    }
460                                                                                 
461    int lengthG;  // Green LUT length in Bytes
462    int debG;     // Subscript of the first Lut Value
463    int nbitsG;   // Lut item size (in Bits)
464    nbRead = sscanf( LutGreenDescriptor.c_str(),
465                     "%d\\%d\\%d",
466                     &lengthG, &debG, &nbitsG );
467    if( nbRead != 3 )
468    {
469       gdcmWarningMacro( "Wrong Green LUT descriptor" );
470    }
471                                                                                 
472    int lengthB;  // Blue LUT length in Bytes
473    int debB;     // Subscript of the first Lut Value
474    int nbitsB;   // Lut item size (in Bits)
475    nbRead = sscanf( LutRedDescriptor.c_str(),
476                     "%d\\%d\\%d",
477                     &lengthB, &debB, &nbitsB );
478    if( nbRead != 3 )
479    {
480       gdcmWarningMacro( "Wrong Blue LUT descriptor" );
481    }
482                                                                                 
483    ////////////////////////////////////////////////////////
484    if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
485    {
486       return;
487    }
488
489    ////////////////////////////////////////////////
490    // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
491    LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
492    if ( !LutRGBA )
493       return;
494
495    memset( LutRGBA, 0, 1024 );
496                                                                                 
497    int mult;
498    if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
499    {
500       // when LUT item size is different than pixel size
501       mult = 2; // high byte must be = low byte
502    }
503    else
504    {
505       // See PS 3.3-2003 C.11.1.1.2 p 619
506       mult = 1;
507    }
508                                                                                 
509    // if we get a black image, let's just remove the '+1'
510    // from 'i*mult+1' and check again
511    // if it works, we shall have to check the 3 Palettes
512    // to see which byte is ==0 (first one, or second one)
513    // and fix the code
514    // We give up the checking to avoid some (useless ?) overhead
515    // (optimistic asumption)
516    int i;
517    uint8_t *a = LutRGBA + 0;
518    for( i=0; i < lengthR; ++i )
519    {
520       *a = LutRedData[i*mult+1];
521       a += 4;
522    }
523                                                                                 
524    a = LutRGBA + 1;
525    for( i=0; i < lengthG; ++i)
526    {
527       *a = LutGreenData[i*mult+1];
528       a += 4;
529    }
530                                                                                 
531    a = LutRGBA + 2;
532    for(i=0; i < lengthB; ++i)
533    {
534       *a = LutBlueData[i*mult+1];
535       a += 4;
536    }
537                                                                                 
538    a = LutRGBA + 3;
539    for(i=0; i < 256; ++i)
540    {
541       *a = 1; // Alpha component
542       a += 4;
543    }
544 }
545
546 /**
547  * \brief Swap the bytes, according to \ref SwapCode.
548  */
549 void PixelReadConvert::ConvertSwapZone()
550 {
551    unsigned int i;
552
553    if( BitsAllocated == 16 )
554    {
555       uint16_t *im16 = (uint16_t*)Raw;
556       switch( SwapCode )
557       {
558          case 1234:
559             break;
560          case 3412:
561          case 2143:
562          case 4321:
563             for( i = 0; i < RawSize / 2; i++ )
564             {
565                im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
566             }
567             break;
568          default:
569             gdcmWarningMacro("SwapCode value (16 bits) not allowed.");
570       }
571    }
572    else if( BitsAllocated == 32 )
573    {
574       uint32_t s32;
575       uint16_t high;
576       uint16_t low;
577       uint32_t *im32 = (uint32_t*)Raw;
578       switch ( SwapCode )
579       {
580          case 1234:
581             break;
582          case 4321:
583             for( i = 0; i < RawSize / 4; i++ )
584             {
585                low     = im32[i] & 0x0000ffff;  // 4321
586                high    = im32[i] >> 16;
587                high    = ( high >> 8 ) | ( high << 8 );
588                low     = ( low  >> 8 ) | ( low  << 8 );
589                s32     = low;
590                im32[i] = ( s32 << 16 ) | high;
591             }
592             break;
593          case 2143:
594             for( i = 0; i < RawSize / 4; i++ )
595             {
596                low     = im32[i] & 0x0000ffff;   // 2143
597                high    = im32[i] >> 16;
598                high    = ( high >> 8 ) | ( high << 8 );
599                low     = ( low  >> 8 ) | ( low  << 8 );
600                s32     = high;
601                im32[i] = ( s32 << 16 ) | low;
602             }
603             break;
604          case 3412:
605             for( i = 0; i < RawSize / 4; i++ )
606             {
607                low     = im32[i] & 0x0000ffff; // 3412
608                high    = im32[i] >> 16;
609                s32     = low;
610                im32[i] = ( s32 << 16 ) | high;
611             }
612             break;
613          default:
614             gdcmWarningMacro("SwapCode value (32 bits) not allowed." );
615       }
616    }
617 }
618
619 /**
620  * \brief Deal with endianness i.e. re-arange bytes inside the integer
621  */
622 void PixelReadConvert::ConvertReorderEndianity()
623 {
624    if ( BitsAllocated != 8 )
625    {
626       ConvertSwapZone();
627    }
628
629    // Special kludge in order to deal with xmedcon broken images:
630    if ( BitsAllocated == 16
631      && BitsStored < BitsAllocated
632      && !PixelSign )
633    {
634       int l = (int)( RawSize / ( BitsAllocated / 8 ) );
635       uint16_t *deb = (uint16_t *)Raw;
636       for(int i = 0; i<l; i++)
637       {
638          if( *deb == 0xffff )
639          {
640            *deb = 0;
641          }
642          deb++;
643       }
644    }
645 }
646
647
648
649 /**
650  * \brief Deal with Grey levels i.e. re-arange them
651  *        to have low values = dark, high values = bright
652  */
653 void PixelReadConvert::ConvertFixGreyLevels()
654 {
655    if (!IsMonochrome1)
656       return;
657
658    int i; // to please M$VC6
659
660    if (!PixelSign)
661    {
662       if ( BitsAllocated == 8 )
663       {
664          uint8_t *deb = (uint8_t *)Raw;
665          for (i=0; i<RawSize; i++)      
666          {
667             *deb = 255 - *deb;
668             deb++;
669          }
670          return;
671       }
672
673       if ( BitsAllocated == 16 )
674       {
675          uint16_t mask =1;
676          int bitStored = 12;   
677          for (i=0; i<BitsStored-1; i++)
678          {
679             mask = (mask << 1) +1; // will be fff when BitsStored=12
680          }
681
682          uint16_t *deb = (uint16_t *)Raw;
683          for (i=0; i<RawSize/2; i++)      
684          {
685             *deb = mask - *deb;
686             deb++;
687          }
688          return;
689        }
690    }
691    else
692    {
693       if ( BitsAllocated == 8 )
694       {
695          int8_t smask8 = 255;
696          int8_t *deb = (int8_t *)Raw;
697          for (i=0; i<RawSize; i++)      
698          {
699             *deb = smask8 - *deb;
700             deb++;
701          }
702          return;
703       }
704       if ( BitsAllocated == 16 )
705       {
706          int16_t smask16 = 65535;
707          int16_t *deb = (int16_t *)Raw;
708          for (i=0; i<RawSize/2; i++)      
709          {
710             *deb = smask16 - *deb;
711             deb++;
712          }
713          return;
714       }
715    }
716 }
717
718 /**
719  * \brief  Re-arrange the bits within the bytes.
720  * @return Boolean always true
721  */
722 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
723 {
724    if ( BitsStored != BitsAllocated )
725    {
726       int l = (int)( RawSize / ( BitsAllocated / 8 ) );
727       if ( BitsAllocated == 16 )
728       {
729          uint16_t mask = 0xffff;
730          mask = mask >> ( BitsAllocated - BitsStored );
731          uint16_t *deb = (uint16_t*)Raw;
732          for(int i = 0; i<l; i++)
733          {
734             *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
735             deb++;
736          }
737       }
738       else if ( BitsAllocated == 32 )
739       {
740          uint32_t mask = 0xffffffff;
741          mask = mask >> ( BitsAllocated - BitsStored );
742          uint32_t *deb = (uint32_t*)Raw;
743          for(int i = 0; i<l; i++)
744          {
745             *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
746             deb++;
747          }
748       }
749       else
750       {
751          gdcmWarningMacro("Weird image");
752          throw FormatError( "Weird image !?" );
753       }
754    }
755    return true;
756 }
757
758 /**
759  * \brief   Convert (Red plane, Green plane, Blue plane) to RGB pixels
760  * \warning Works on all the frames at a time
761  */
762 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
763 {
764    uint8_t *localRaw = Raw;
765    uint8_t *copyRaw = new uint8_t[ RawSize ];
766    memmove( copyRaw, localRaw, RawSize );
767
768    int l = XSize * YSize * ZSize;
769
770    uint8_t *a = copyRaw;
771    uint8_t *b = copyRaw + l;
772    uint8_t *c = copyRaw + l + l;
773
774    for (int j = 0; j < l; j++)
775    {
776       *(localRaw++) = *(a++);
777       *(localRaw++) = *(b++);
778       *(localRaw++) = *(c++);
779    }
780    delete[] copyRaw;
781 }
782
783 /**
784  * \brief   Convert (cY plane, cB plane, cR plane) to RGB pixels
785  * \warning Works on all the frames at a time
786  */
787 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
788 {
789    uint8_t *localRaw = Raw;
790    uint8_t *copyRaw = new uint8_t[ RawSize ];
791    memmove( copyRaw, localRaw, RawSize );
792
793    // to see the tricks about YBR_FULL, YBR_FULL_422,
794    // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
795    // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
796    // and be *very* affraid
797    //
798    int l        = XSize * YSize;
799    int nbFrames = ZSize;
800
801    uint8_t *a = copyRaw;
802    uint8_t *b = copyRaw + l;
803    uint8_t *c = copyRaw + l + l;
804    double R, G, B;
805
806    /// \todo : Replace by the 'well known' integer computation
807    ///         counterpart. Refer to
808    ///            http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
809    ///         for code optimisation.
810
811    for ( int i = 0; i < nbFrames; i++ )
812    {
813       for ( int j = 0; j < l; j++ )
814       {
815          R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
816          G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
817          B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
818
819          if (R < 0.0)   R = 0.0;
820          if (G < 0.0)   G = 0.0;
821          if (B < 0.0)   B = 0.0;
822          if (R > 255.0) R = 255.0;
823          if (G > 255.0) G = 255.0;
824          if (B > 255.0) B = 255.0;
825
826          *(localRaw++) = (uint8_t)R;
827          *(localRaw++) = (uint8_t)G;
828          *(localRaw++) = (uint8_t)B;
829          a++;
830          b++;
831          c++;
832       }
833    }
834    delete[] copyRaw;
835 }
836
837 /// \brief Deals with the color decoding i.e. handle:
838 ///   - R, G, B planes (as opposed to RGB pixels)
839 ///   - YBR (various) encodings.
840 ///   - LUT[s] (or "PALETTE COLOR").
841
842 void PixelReadConvert::ConvertHandleColor()
843 {
844    //////////////////////////////////
845    // Deal with the color decoding i.e. handle:
846    //   - R, G, B planes (as opposed to RGB pixels)
847    //   - YBR (various) encodings.
848    //   - LUT[s] (or "PALETTE COLOR").
849    //
850    // The classification in the color decoding schema is based on the blending
851    // of two Dicom tags values:
852    // * "Photometric Interpretation" for which we have the cases:
853    //  - [Photo A] MONOCHROME[1|2] pictures,
854    //  - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
855    //  - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
856    //  - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
857    // * "Planar Configuration" for which we have the cases:
858    //  - [Planar 0] 0 then Pixels are already RGB
859    //  - [Planar 1] 1 then we have 3 planes : R, G, B,
860    //  - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
861    //
862    // Now in theory, one could expect some coherence when blending the above
863    // cases. For example we should not encounter files belonging at the
864    // time to case [Planar 0] and case [Photo D].
865    // Alas, this was only theory ! Because in practice some odd (read ill
866    // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
867    //     - "Planar Configuration" = 0,
868    //     - "Photometric Interpretation" = "PALETTE COLOR".
869    // Hence gdcm will use the folowing "heuristic" in order to be tolerant
870    // towards Dicom-non-conformance files:
871    //   << whatever the "Planar Configuration" value might be, a
872    //      "Photometric Interpretation" set to "PALETTE COLOR" forces
873    //      a LUT intervention >>
874    //
875    // Now we are left with the following handling of the cases:
876    // - [Planar 0] OR  [Photo A] no color decoding (since respectively
877    //       Pixels are already RGB and monochrome pictures have no color :),
878    // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
879    // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
880    // - [Planar 2] OR  [Photo D] requires LUT intervention.
881
882    if ( ! IsRawRGB() )
883    {
884       // [Planar 2] OR  [Photo D]: LUT intervention done outside
885       return;
886    }
887                                                                                 
888    if ( PlanarConfiguration == 1 )
889    {
890       if ( IsYBRFull )
891       {
892          // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
893          ConvertYcBcRPlanesToRGBPixels();
894       }
895       else
896       {
897          // [Planar 1] AND [Photo C]
898          ConvertRGBPlanesToRGBPixels();
899       }
900       return;
901    }
902                                                                                 
903    // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
904    // pixels need to be RGB-fied anyway
905    if (IsRLELossless)
906    {
907      ConvertRGBPlanesToRGBPixels();
908    }
909    // In *normal *case, when planarConf is 0, pixels are already in RGB
910 }
911
912 /// Computes the Pixels Size
913 void PixelReadConvert::ComputeRawAndRGBSizes()
914 {
915    int bitsAllocated = BitsAllocated;
916    // Number of "Bits Allocated" is fixed to 16 when it's 12, since
917    // in this case we will expand the image to 16 bits (see
918    //    \ref ReadAndDecompress12BitsTo16Bits() )
919    if (  BitsAllocated == 12 )
920    {
921       bitsAllocated = 16;
922    }
923                                                                                 
924    RawSize =  XSize * YSize * ZSize
925                      * ( bitsAllocated / 8 )
926                      * SamplesPerPixel;
927    if ( HasLUT )
928    {
929       RGBSize = 3 * RawSize;
930    }
931    else
932    {
933       RGBSize = RawSize;
934    }
935 }
936
937 /// Allocates room for RGB Pixels
938 void PixelReadConvert::AllocateRGB()
939 {
940   if ( RGB )
941      delete [] RGB;
942   RGB = new uint8_t[RGBSize];
943 }
944
945 /// Allocates room for RAW Pixels
946 void PixelReadConvert::AllocateRaw()
947 {
948   if ( Raw )
949      delete [] Raw;
950   Raw = new uint8_t[RawSize];
951 }
952
953 //-----------------------------------------------------------------------------
954 // Print
955 /**
956  * \brief        Print self.
957  * @param indent Indentation string to be prepended during printing.
958  * @param os     Stream to print to.
959  */
960 void PixelReadConvert::Print( std::ostream &os, std::string const &indent )
961 {
962    os << indent
963       << "--- Pixel information -------------------------"
964       << std::endl;
965    os << indent
966       << "Pixel Data: offset " << PixelOffset
967       << " x(" << std::hex << PixelOffset << std::dec
968       << ")   length " << PixelDataLength
969       << " x(" << std::hex << PixelDataLength << std::dec
970       << ")" << std::endl;
971
972    if ( IsRLELossless )
973    {
974       if ( RLEInfo )
975       {
976          RLEInfo->Print( os, indent );
977       }
978       else
979       {
980          gdcmWarningMacro("Set as RLE file but NO RLEinfo present.");
981       }
982    }
983
984    if ( IsJPEG2000 || IsJPEGLossless || IsJPEGLossy || IsJPEGLS )
985    {
986       if ( JPEGInfo )
987       {
988          JPEGInfo->Print( os, indent );
989       }
990       else
991       {
992          gdcmWarningMacro("Set as JPEG file but NO JPEGinfo present.");
993       }
994    }
995 }
996
997 //-----------------------------------------------------------------------------
998 } // end namespace gdcm
999
1000 // NOTES on File internal calls
1001 // User
1002 // ---> GetImageData
1003 //     ---> GetImageDataIntoVector
1004 //        |---> GetImageDataIntoVectorRaw
1005 //        | lut intervention
1006 // User
1007 // ---> GetImageDataRaw
1008 //     ---> GetImageDataIntoVectorRaw
1009