1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/11/09 21:55:56 $
7 Version: $Revision: 1.26 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 ////////////////// TEMPORARY NOTE
20 // look for "fixMem" and convert that to a member of this class
21 // Removing the prefix fixMem and dealing with allocations should do the trick
23 // grep PIXELCONVERT everywhere and clean up !
25 #include "gdcmDebug.h"
26 #include "gdcmPixelConvert.h"
32 #define str2num(str, typeNum) *((typeNum *)(str))
34 // For JPEG 2000, body in file gdcmJpeg2000.cxx
35 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
37 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
38 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
40 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
41 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
43 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
44 // Beware this is misleading there is no 16bits DCT algorithm, only
45 // jpeg lossless compression exist in 16bits.
46 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
49 //-----------------------------------------------------------------------------
50 // Constructor / Destructor
51 PixelConvert::PixelConvert()
63 void PixelConvert::Squeeze()
71 delete [] Decompressed;
79 PixelConvert::~PixelConvert()
84 void PixelConvert::AllocateRGB()
89 RGB = new uint8_t[ RGBSize ];
92 void PixelConvert::AllocateDecompressed()
95 delete [] Decompressed;
97 Decompressed = new uint8_t[ DecompressedSize ];
101 * \brief Read from file a 12 bits per pixel image and decompress it
102 * into a 16 bits per pixel image.
104 void PixelConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
105 throw ( FormatError )
107 int nbPixels = XSize * YSize;
108 uint16_t* localDecompres = (uint16_t*)Decompressed;
110 for( int p = 0; p < nbPixels; p += 2 )
114 fp->read( (char*)&b0, 1);
115 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
117 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
118 "Unfound first block" );
121 fp->read( (char*)&b1, 1 );
122 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
124 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
125 "Unfound second block" );
128 fp->read( (char*)&b2, 1 );
129 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
131 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
132 "Unfound second block" );
135 // Two steps are necessary to please VC++
137 // 2 pixels 12bit = [0xABCDEF]
138 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
140 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
142 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
144 /// \todo JPR Troubles expected on Big-Endian processors ?
149 * \brief Try to deal with RLE 16 Bits.
150 * We assume the RLE has allready been parsed and loaded in
151 * Decompressed (through \ref ReadAndDecompressJPEGFile ).
152 * We here need to make 16 Bits Pixels from Low Byte and
153 * High Byte 'Planes'...(for what it may mean)
156 bool PixelConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
158 size_t PixelNumber = XSize * YSize;
159 size_t decompressedSize = XSize * YSize * NumberOfFrames;
161 // We assumed Decompressed contains the decoded RLE pixels but as
162 // 8 bits per pixel. In order to convert those pixels to 16 bits
163 // per pixel we cannot work in place within Decompressed and hence
164 // we copy it in a safe place, say copyDecompressed.
166 uint8_t* copyDecompressed = new uint8_t[ decompressedSize * 2 ];
167 memmove( copyDecompressed, Decompressed, decompressedSize * 2 );
169 uint8_t* x = Decompressed;
170 uint8_t* a = copyDecompressed;
171 uint8_t* b = a + PixelNumber;
173 for ( int i = 0; i < NumberOfFrames; i++ )
175 for ( unsigned int j = 0; j < PixelNumber; j++ )
182 delete[] copyDecompressed;
184 /// \todo check that operator new []didn't fail, and sometimes return false
189 * \brief Implementation of the RLE decoding algorithm for decompressing
190 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
191 * @param subDecompressed Sub region of \ref Decompressed where the de
192 * decoded fragment should be placed.
193 * @param fragmentSize The length of the binary fragment as found on the disk.
194 * @param decompressedSegmentSize The expected length of the fragment ONCE
196 * @param fp File Pointer: on entry the position should be the one of
197 * the fragment to be decoded.
199 bool PixelConvert::ReadAndDecompressRLEFragment( uint8_t* subDecompressed,
201 long decompressedSegmentSize,
205 long numberOfOutputBytes = 0;
206 long numberOfReadBytes = 0;
208 while( numberOfOutputBytes < decompressedSegmentSize )
210 fp->read( (char*)&count, 1 );
211 numberOfReadBytes += 1;
213 // Note: count <= 127 comparison is always true due to limited range
214 // of data type int8_t [since the maximum of an exact width
215 // signed integer of width N is 2^(N-1) - 1, which for int8_t
218 fp->read( (char*)subDecompressed, count + 1);
219 numberOfReadBytes += count + 1;
220 subDecompressed += count + 1;
221 numberOfOutputBytes += count + 1;
225 if ( ( count <= -1 ) && ( count >= -127 ) )
228 fp->read( (char*)&newByte, 1);
229 numberOfReadBytes += 1;
230 for( int i = 0; i < -count + 1; i++ )
232 subDecompressed[i] = newByte;
234 subDecompressed += -count + 1;
235 numberOfOutputBytes += -count + 1;
238 // if count = 128 output nothing
240 if ( numberOfReadBytes > fragmentSize )
242 dbg.Verbose(0, "PixelConvert::ReadAndDecompressRLEFragment: we "
243 "read more bytes than the segment size.");
251 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
252 * Dicom encapsulated file and decompress it.
253 * @param fp already open File Pointer
254 * at which the pixel data should be copied
257 bool PixelConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
259 uint8_t* subDecompressed = Decompressed;
260 long decompressedSegmentSize = XSize * YSize;
262 // Loop on the frame[s]
263 for( RLEFramesInfo::RLEFrameList::iterator
264 it = RLEInfo->Frames.begin();
265 it != RLEInfo->Frames.end();
268 // Loop on the fragments
269 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
271 fp->seekg( (*it)->Offset[k] , std::ios_base::beg );
272 (void)ReadAndDecompressRLEFragment( subDecompressed,
274 decompressedSegmentSize,
276 subDecompressed += decompressedSegmentSize;
280 if ( BitsAllocated == 16 )
282 // Try to deal with RLE 16 Bits
283 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
290 * \brief Swap the bytes, according to \ref SwapCode.
292 void PixelConvert::ConvertSwapZone()
296 if( BitsAllocated == 16 )
298 uint16_t* im16 = (uint16_t*)Decompressed;
309 for( i = 0; i < DecompressedSize / 2; i++ )
311 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
315 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
316 "(16 bits) not allowed." );
319 else if( BitsAllocated == 32 )
324 uint32_t* im32 = (uint32_t*)Decompressed;
331 for( i = 0; i < DecompressedSize / 4; i++ )
333 low = im32[i] & 0x0000ffff; // 4321
334 high = im32[i] >> 16;
335 high = ( high >> 8 ) | ( high << 8 );
336 low = ( low >> 8 ) | ( low << 8 );
338 im32[i] = ( s32 << 16 ) | high;
342 for( i = 0; i < DecompressedSize / 4; i++ )
344 low = im32[i] & 0x0000ffff; // 2143
345 high = im32[i] >> 16;
346 high = ( high >> 8 ) | ( high << 8 );
347 low = ( low >> 8 ) | ( low << 8 );
349 im32[i] = ( s32 << 16 ) | low;
353 for( i = 0; i < DecompressedSize / 4; i++ )
355 low = im32[i] & 0x0000ffff; // 3412
356 high = im32[i] >> 16;
358 im32[i] = ( s32 << 16 ) | high;
362 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
363 "(32 bits) not allowed." );
369 * \brief Deal with endianity i.e. re-arange bytes inside the integer
371 void PixelConvert::ConvertReorderEndianity()
373 if ( BitsAllocated != 8 )
378 // Special kludge in order to deal with xmedcon broken images:
379 if ( ( BitsAllocated == 16 )
380 && ( BitsStored < BitsAllocated )
383 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
384 uint16_t *deb = (uint16_t *)Decompressed;
385 for(int i = 0; i<l; i++)
397 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
398 & file and decompress it.
399 * @param fp File Pointer
402 bool PixelConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
404 uint8_t* localDecompressed = Decompressed;
405 // Loop on the fragment[s]
406 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
407 it = JPEGInfo->Fragments.begin();
408 it != JPEGInfo->Fragments.end();
411 fp->seekg( (*it)->Offset, std::ios_base::beg);
415 if ( ! gdcm_read_JPEG2000_file( fp,localDecompressed ) )
420 else if ( BitsStored == 8)
422 // JPEG Lossy : call to IJG 6b
423 if ( ! gdcm_read_JPEG_file8( fp, localDecompressed ) )
428 else if ( BitsStored <= 12)
430 // Reading Fragment pixels
431 if ( ! gdcm_read_JPEG_file12 ( fp, localDecompressed ) )
436 else if ( BitsStored <= 16)
438 // Reading Fragment pixels
439 if ( ! gdcm_read_JPEG_file16 ( fp, localDecompressed ) )
443 //assert( IsJPEGLossless );
447 // other JPEG lossy not supported
448 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
449 "jpeg lossy compression ");
453 // Advance to next free location in Decompressed
454 // for next fragment decompression (if any)
455 int length = XSize * YSize * SamplesPerPixel;
456 int numberBytes = BitsAllocated / 8;
458 localDecompressed += length * numberBytes;
464 * \brief Re-arrange the bits within the bytes.
467 bool PixelConvert::ConvertReArrangeBits() throw ( FormatError )
469 if ( BitsStored != BitsAllocated )
471 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
472 if ( BitsAllocated == 16 )
474 uint16_t mask = 0xffff;
475 mask = mask >> ( BitsAllocated - BitsStored );
476 uint16_t* deb = (uint16_t*)Decompressed;
477 for(int i = 0; i<l; i++)
479 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
483 else if ( BitsAllocated == 32 )
485 uint32_t mask = 0xffffffff;
486 mask = mask >> ( BitsAllocated - BitsStored );
487 uint32_t* deb = (uint32_t*)Decompressed;
488 for(int i = 0; i<l; i++)
490 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
496 dbg.Verbose(0, "PixelConvert::ConvertReArrangeBits: weird image");
497 throw FormatError( "PixelConvert::ConvertReArrangeBits()",
505 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
506 * \warning Works on all the frames at a time
508 void PixelConvert::ConvertYcBcRPlanesToRGBPixels()
510 uint8_t* localDecompressed = Decompressed;
511 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
512 memmove( copyDecompressed, localDecompressed, DecompressedSize );
514 // to see the tricks about YBR_FULL, YBR_FULL_422,
515 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
516 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
517 // and be *very* affraid
519 int l = XSize * YSize;
520 int nbFrames = ZSize;
522 uint8_t* a = copyDecompressed;
523 uint8_t* b = copyDecompressed + l;
524 uint8_t* c = copyDecompressed + l + l;
527 /// \todo : Replace by the 'well known' integer computation
528 /// counterpart. Refer to
529 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
530 /// for code optimisation.
532 for ( int i = 0; i < nbFrames; i++ )
534 for ( int j = 0; j < l; j++ )
536 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
537 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
538 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
540 if (R < 0.0) R = 0.0;
541 if (G < 0.0) G = 0.0;
542 if (B < 0.0) B = 0.0;
543 if (R > 255.0) R = 255.0;
544 if (G > 255.0) G = 255.0;
545 if (B > 255.0) B = 255.0;
547 *(localDecompressed++) = (uint8_t)R;
548 *(localDecompressed++) = (uint8_t)G;
549 *(localDecompressed++) = (uint8_t)B;
555 delete[] copyDecompressed;
559 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
560 * \warning Works on all the frames at a time
562 void PixelConvert::ConvertRGBPlanesToRGBPixels()
564 uint8_t* localDecompressed = Decompressed;
565 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
566 memmove( copyDecompressed, localDecompressed, DecompressedSize );
568 int l = XSize * YSize * ZSize;
570 uint8_t* a = copyDecompressed;
571 uint8_t* b = copyDecompressed + l;
572 uint8_t* c = copyDecompressed + l + l;
574 for (int j = 0; j < l; j++)
576 *(localDecompressed++) = *(a++);
577 *(localDecompressed++) = *(b++);
578 *(localDecompressed++) = *(c++);
580 delete[] copyDecompressed;
583 bool PixelConvert::ReadAndDecompressPixelData( std::ifstream* fp )
585 ComputeDecompressedAndRGBSizes();
586 AllocateDecompressed();
587 //////////////////////////////////////////////////
588 //// First stage: get our hands on the Pixel Data.
591 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
592 "unavailable file pointer." );
596 fp->seekg( PixelOffset, std::ios_base::beg );
597 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
599 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
600 "unable to find PixelOffset in file." );
604 //////////////////////////////////////////////////
605 //// Second stage: read from disk dans decompress.
606 if ( BitsAllocated == 12 )
608 ReadAndDecompress12BitsTo16Bits( fp);
610 else if ( IsDecompressed )
612 fp->read( (char*)Decompressed, PixelDataLength);
613 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
615 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
616 "reading of decompressed pixel data failed." );
620 else if ( IsRLELossless )
622 if ( ! ReadAndDecompressRLEFile( fp ) )
624 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
625 "RLE decompressor failed." );
631 // Default case concerns JPEG family
632 if ( ! ReadAndDecompressJPEGFile( fp ) )
634 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
635 "JPEG decompressor failed." );
640 ////////////////////////////////////////////
641 //// Third stage: twigle the bytes and bits.
642 ConvertReorderEndianity();
643 ConvertReArrangeBits();
644 ConvertHandleColor();
649 void PixelConvert::ConvertHandleColor()
651 //////////////////////////////////
652 // Deal with the color decoding i.e. handle:
653 // - R, G, B planes (as opposed to RGB pixels)
654 // - YBR (various) encodings.
655 // - LUT[s] (or "PALETTE COLOR").
657 // The classification in the color decoding schema is based on the blending
658 // of two Dicom tags values:
659 // * "Photometric Interpretation" for which we have the cases:
660 // - [Photo A] MONOCHROME[1|2] pictures,
661 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
662 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
663 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
664 // * "Planar Configuration" for which we have the cases:
665 // - [Planar 0] 0 then Pixels are already RGB
666 // - [Planar 1] 1 then we have 3 planes : R, G, B,
667 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
669 // Now in theory, one could expect some coherence when blending the above
670 // cases. For example we should not encounter files belonging at the
671 // time to case [Planar 0] and case [Photo D].
672 // Alas, this was only theory ! Because in practice some odd (read ill
673 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
674 // - "Planar Configuration" = 0,
675 // - "Photometric Interpretation" = "PALETTE COLOR".
676 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
677 // towards Dicom-non-conformance files:
678 // << whatever the "Planar Configuration" value might be, a
679 // "Photometric Interpretation" set to "PALETTE COLOR" forces
680 // a LUT intervention >>
682 // Now we are left with the following handling of the cases:
683 // - [Planar 0] OR [Photo A] no color decoding (since respectively
684 // Pixels are already RGB and monochrome pictures have no color :),
685 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
686 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
687 // - [Planar 2] OR [Photo D] requires LUT intervention.
689 if ( ! IsDecompressedRGB() )
691 // [Planar 2] OR [Photo D]: LUT intervention done outside
695 if ( PlanarConfiguration == 1 )
699 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
700 ConvertYcBcRPlanesToRGBPixels();
704 // [Planar 1] AND [Photo C]
705 ConvertRGBPlanesToRGBPixels();
710 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
711 // pixels need to be RGB-fied anyway
714 ConvertRGBPlanesToRGBPixels();
716 // In *normal *case, when planarConf is 0, pixels are already in RGB
720 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
721 * \note See comments of \ref ConvertHandleColor
723 bool PixelConvert::IsDecompressedRGB()
726 || PlanarConfiguration == 2
734 void PixelConvert::ComputeDecompressedAndRGBSizes()
736 int bitsAllocated = BitsAllocated;
737 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
738 // in this case we will expand the image to 16 bits (see
739 // \ref ReadAndDecompress12BitsTo16Bits() )
740 if ( BitsAllocated == 12 )
745 DecompressedSize = XSize * YSize * ZSize
746 * ( bitsAllocated / 8 )
750 RGBSize = 3 * DecompressedSize;
755 void PixelConvert::GrabInformationsFromHeader( Header* header )
757 // Just in case some access to a Header element requires disk access.
758 // Note: gdcmDocument::Fp is leaved open after OpenFile.
759 std::ifstream* fp = header->OpenFile();
760 // Number of Bits Allocated for storing a Pixel is defaulted to 16
761 // when absent from the header.
762 BitsAllocated = header->GetBitsAllocated();
763 if ( BitsAllocated == 0 )
768 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
769 // when absent from the header.
770 BitsStored = header->GetBitsStored();
771 if ( BitsStored == 0 )
773 BitsStored = BitsAllocated;
777 HighBitPosition = header->GetHighBitPosition();
778 if ( HighBitPosition == 0 )
780 HighBitPosition = BitsAllocated - 1;
783 XSize = header->GetXSize();
784 YSize = header->GetYSize();
785 ZSize = header->GetZSize();
786 SamplesPerPixel = header->GetSamplesPerPixel();
787 PixelSize = header->GetPixelSize();
788 PixelSign = header->IsSignedPixelData();
789 SwapCode = header->GetSwapCode();
790 TransferSyntaxType ts = header->GetTransferSyntax();
792 ( ! header->IsDicomV3() )
793 || ts == ImplicitVRLittleEndian
794 || ts == ExplicitVRLittleEndian
795 || ts == ExplicitVRBigEndian
796 || ts == DeflatedExplicitVRLittleEndian;
797 IsJPEG2000 = header->IsJPEG2000();
798 IsJPEGLossless = header->IsJPEGLossless();
799 IsRLELossless = ( ts == RLELossless );
800 PixelOffset = header->GetPixelOffset();
801 PixelDataLength = header->GetPixelAreaLength();
802 RLEInfo = header->GetRLEInfo();
803 JPEGInfo = header->GetJPEGInfo();
805 PlanarConfiguration = header->GetPlanarConfiguration();
806 IsMonochrome = header->IsMonochrome();
807 IsPaletteColor = header->IsPaletteColor();
808 IsYBRFull = header->IsYBRFull();
810 /////////////////////////////////////////////////////////////////
812 HasLUT = header->HasLUT();
815 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
816 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
817 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
819 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
820 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
821 // Document::Document() ], the loading of the value (content) of a
822 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
823 // loaded). Hence, we first try to obtain the LUTs data from the header
824 // and when this fails we read the LUTs data directely from disk.
825 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
826 /// We should NOT bypass the [Bin|Val]Entry class. Instead
827 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
828 /// (e.g. BinEntry::GetBinArea()) should force disk access from
829 /// within the [Bin|Val]Entry class itself. The only problem
830 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
831 /// parsed from. Fix that. FIXME.
834 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
837 // Read the Lut Data from disk
838 DocEntry* lutRedDataEntry = header->GetDocEntryByNumber( 0x0028,
840 LutRedData = new uint8_t[ lutRedDataEntry->GetLength() ];
841 fp->seekg( lutRedDataEntry->GetOffset() ,std::ios_base::beg );
842 fp->read( (char*)LutRedData, (size_t)lutRedDataEntry->GetLength());
843 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
845 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
846 "unable to read red LUT data" );
852 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
855 // Read the Lut Data from disk
856 DocEntry* lutGreenDataEntry = header->GetDocEntryByNumber( 0x0028,
858 LutGreenData = new uint8_t[ lutGreenDataEntry->GetLength() ];
859 fp->seekg( lutGreenDataEntry->GetOffset() , std::ios_base::beg );
860 fp->read( (char*)LutGreenData, (size_t)lutGreenDataEntry->GetLength() );
861 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
863 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
864 "unable to read green LUT data" );
870 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
873 // Read the Lut Data from disk
874 DocEntry* lutBlueDataEntry = header->GetDocEntryByNumber( 0x0028,
876 LutBlueData = new uint8_t[ lutBlueDataEntry->GetLength() ];
877 fp->seekg( lutBlueDataEntry->GetOffset() , std::ios_base::beg );
878 fp->read( (char*)LutBlueData, (size_t)lutBlueDataEntry->GetLength() );
879 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
881 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
882 "unable to read blue LUT data" );
892 * \brief Build Red/Green/Blue/Alpha LUT from Header
893 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
894 * and (0028,1101),(0028,1102),(0028,1102)
895 * - xxx Palette Color Lookup Table Descriptor - are found
896 * and (0028,1201),(0028,1202),(0028,1202)
897 * - xxx Palette Color Lookup Table Data - are found
898 * \warning does NOT deal with :
899 * 0028 1100 Gray Lookup Table Descriptor (Retired)
900 * 0028 1221 Segmented Red Palette Color Lookup Table Data
901 * 0028 1222 Segmented Green Palette Color Lookup Table Data
902 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
903 * no known Dicom reader deals with them :-(
904 * @return a RGBA Lookup Table
906 void PixelConvert::BuildLUTRGBA()
913 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
915 if ( ! IsPaletteColor )
920 if ( LutRedDescriptor == GDCM_UNFOUND
921 || LutGreenDescriptor == GDCM_UNFOUND
922 || LutBlueDescriptor == GDCM_UNFOUND )
927 ////////////////////////////////////////////
928 // Extract the info from the LUT descriptors
929 int lengthR; // Red LUT length in Bytes
930 int debR; // Subscript of the first Lut Value
931 int nbitsR; // Lut item size (in Bits)
932 int nbRead = sscanf( LutRedDescriptor.c_str(),
934 &lengthR, &debR, &nbitsR );
937 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong red LUT descriptor");
940 int lengthG; // Green LUT length in Bytes
941 int debG; // Subscript of the first Lut Value
942 int nbitsG; // Lut item size (in Bits)
943 nbRead = sscanf( LutGreenDescriptor.c_str(),
945 &lengthG, &debG, &nbitsG );
948 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong green LUT descriptor");
951 int lengthB; // Blue LUT length in Bytes
952 int debB; // Subscript of the first Lut Value
953 int nbitsB; // Lut item size (in Bits)
954 nbRead = sscanf( LutRedDescriptor.c_str(),
956 &lengthB, &debB, &nbitsB );
959 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong blue LUT descriptor");
962 ////////////////////////////////////////////////////////
963 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
968 ////////////////////////////////////////////////
969 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
970 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
975 memset( LutRGBA, 0, 1024 );
978 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
980 // when LUT item size is different than pixel size
981 mult = 2; // high byte must be = low byte
985 // See PS 3.3-2003 C.11.1.1.2 p 619
989 // if we get a black image, let's just remove the '+1'
990 // from 'i*mult+1' and check again
991 // if it works, we shall have to check the 3 Palettes
992 // to see which byte is ==0 (first one, or second one)
994 // We give up the checking to avoid some (useless ?)overhead
995 // (optimistic asumption)
997 uint8_t* a = LutRGBA + 0;
998 for( i=0; i < lengthR; ++i )
1000 *a = LutRedData[i*mult+1];
1005 for( i=0; i < lengthG; ++i)
1007 *a = LutGreenData[i*mult+1];
1012 for(i=0; i < lengthB; ++i)
1014 *a = LutBlueData[i*mult+1];
1019 for(i=0; i < 256; ++i)
1021 *a = 1; // Alpha component
1027 * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1029 bool PixelConvert::BuildRGBImage()
1033 // The job is already done.
1037 if ( ! Decompressed )
1039 // The job can't be done
1046 // The job can't be done
1052 uint8_t* localRGB = RGB;
1053 for (size_t i = 0; i < DecompressedSize; ++i )
1055 int j = Decompressed[i] * 4;
1056 *localRGB++ = LutRGBA[j];
1057 *localRGB++ = LutRGBA[j+1];
1058 *localRGB++ = LutRGBA[j+2];
1064 * \brief Print self.
1065 * @param indent Indentation string to be prepended during printing.
1066 * @param os Stream to print to.
1068 void PixelConvert::Print( std::string indent, std::ostream &os )
1071 << "--- Pixel information -------------------------"
1074 << "Pixel Data: offset " << PixelOffset
1075 << " x" << std::hex << PixelOffset << std::dec
1076 << " length " << PixelDataLength
1077 << " x" << std::hex << PixelDataLength << std::dec
1080 if ( IsRLELossless )
1084 RLEInfo->Print( indent, os );
1088 dbg.Verbose(0, "PixelConvert::Print: set as RLE file "
1089 "but NO RLEinfo present.");
1093 if ( IsJPEG2000 || IsJPEGLossless )
1097 JPEGInfo->Print( indent, os );
1101 dbg.Verbose(0, "PixelConvert::Print: set as JPEG file "
1102 "but NO JPEGinfo present.");
1107 } // end namespace gdcm
1109 // NOTES on File internal calls
1111 // ---> GetImageData
1112 // ---> GetImageDataIntoVector
1113 // |---> GetImageDataIntoVectorRaw
1114 // | lut intervention
1116 // ---> GetImageDataRaw
1117 // ---> GetImageDataIntoVectorRaw