1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/11/04 18:14:34 $
7 Version: $Revision: 1.23 $
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"
31 #define str2num(str, typeNum) *((typeNum *)(str))
33 // For JPEG 2000, body in file gdcmJpeg2000.cxx
34 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
36 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
37 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
39 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
40 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
42 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
43 // Beware this is misleading there is no 16bits DCT algorithm, only
44 // jpeg lossless compression exist in 16bits.
45 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
48 //-----------------------------------------------------------------------------
49 // Constructor / Destructor
50 PixelConvert::PixelConvert()
62 void PixelConvert::Squeeze()
70 delete [] Decompressed;
78 PixelConvert::~PixelConvert()
83 void PixelConvert::AllocateRGB()
88 RGB = new uint8_t[ RGBSize ];
91 void PixelConvert::AllocateDecompressed()
94 delete [] Decompressed;
96 Decompressed = new uint8_t[ DecompressedSize ];
100 * \brief Read from file a 12 bits per pixel image and decompress it
101 * into a 16 bits per pixel image.
103 void PixelConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
104 throw ( FormatError )
106 int nbPixels = XSize * YSize;
107 uint16_t* localDecompres = (uint16_t*)Decompressed;
109 for( int p = 0; p < nbPixels; p += 2 )
113 fp->read( (char*)&b0, 1);
114 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
116 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
117 "Unfound first block" );
120 fp->read( (char*)&b1, 1 );
121 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
123 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
124 "Unfound second block" );
127 fp->read( (char*)&b2, 1 );
128 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
130 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
131 "Unfound second block" );
134 // Two steps are necessary to please VC++
136 // 2 pixels 12bit = [0xABCDEF]
137 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
139 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
141 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
143 /// \todo JPR Troubles expected on Big-Endian processors ?
148 * \brief Try to deal with RLE 16 Bits.
149 * We assume the RLE has allready been parsed and loaded in
150 * Decompressed (through \ref ReadAndDecompressJPEGFile ).
151 * We here need to make 16 Bits Pixels from Low Byte and
152 * High Byte 'Planes'...(for what it may mean)
155 bool PixelConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
157 size_t PixelNumber = XSize * YSize;
158 size_t decompressedSize = XSize * YSize * NumberOfFrames;
160 // We assumed Decompressed contains the decoded RLE pixels but as
161 // 8 bits per pixel. In order to convert those pixels to 16 bits
162 // per pixel we cannot work in place within Decompressed and hence
163 // we copy it in a safe place, say copyDecompressed.
165 uint8_t* copyDecompressed = new uint8_t[ decompressedSize * 2 ];
166 memmove( copyDecompressed, Decompressed, decompressedSize * 2 );
168 uint8_t* x = Decompressed;
169 uint8_t* a = copyDecompressed;
170 uint8_t* b = a + PixelNumber;
172 for ( int i = 0; i < NumberOfFrames; i++ )
174 for ( unsigned int j = 0; j < PixelNumber; j++ )
181 delete[] copyDecompressed;
183 /// \todo check that operator new []didn't fail, and sometimes return false
188 * \brief Implementation of the RLE decoding algorithm for decompressing
189 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
190 * @param subDecompressed Sub region of \ref Decompressed where the de
191 * decoded fragment should be placed.
192 * @param fragmentSize The length of the binary fragment as found on the disk.
193 * @param decompressedSegmentSize The expected length of the fragment ONCE
195 * @param fp File Pointer: on entry the position should be the one of
196 * the fragment to be decoded.
198 bool PixelConvert::ReadAndDecompressRLEFragment( uint8_t* subDecompressed,
200 long decompressedSegmentSize,
204 long numberOfOutputBytes = 0;
205 long numberOfReadBytes = 0;
207 while( numberOfOutputBytes < decompressedSegmentSize )
209 fp->read( (char*)&count, 1 );
210 numberOfReadBytes += 1;
212 // Note: count <= 127 comparison is always true due to limited range
213 // of data type int8_t [since the maximum of an exact width
214 // signed integer of width N is 2^(N-1) - 1, which for int8_t
217 fp->read( (char*)subDecompressed, count + 1);
218 numberOfReadBytes += count + 1;
219 subDecompressed += count + 1;
220 numberOfOutputBytes += count + 1;
224 if ( ( count <= -1 ) && ( count >= -127 ) )
227 fp->read( (char*)&newByte, 1);
228 numberOfReadBytes += 1;
229 for( int i = 0; i < -count + 1; i++ )
231 subDecompressed[i] = newByte;
233 subDecompressed += -count + 1;
234 numberOfOutputBytes += -count + 1;
237 // if count = 128 output nothing
239 if ( numberOfReadBytes > fragmentSize )
241 dbg.Verbose(0, "PixelConvert::ReadAndDecompressRLEFragment: we "
242 "read more bytes than the segment size.");
250 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
251 * Dicom encapsulated file and decompress it.
252 * @param fp already open File Pointer
253 * at which the pixel data should be copied
256 bool PixelConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
258 uint8_t* subDecompressed = Decompressed;
259 long decompressedSegmentSize = XSize * YSize;
261 // Loop on the frame[s]
262 for( RLEFramesInfo::RLEFrameList::iterator
263 it = RLEInfo->Frames.begin();
264 it != RLEInfo->Frames.end();
267 // Loop on the fragments
268 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
270 fp->seekg( (*it)->Offset[k] , std::ios_base::beg );
271 (void)ReadAndDecompressRLEFragment( subDecompressed,
273 decompressedSegmentSize,
275 subDecompressed += decompressedSegmentSize;
279 if ( BitsAllocated == 16 )
281 // Try to deal with RLE 16 Bits
282 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
289 * \brief Swap the bytes, according to \ref SwapCode.
291 void PixelConvert::ConvertSwapZone()
295 if( BitsAllocated == 16 )
297 uint16_t* im16 = (uint16_t*)Decompressed;
308 for( i = 0; i < DecompressedSize / 2; i++ )
310 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
314 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
315 "(16 bits) not allowed." );
318 else if( BitsAllocated == 32 )
323 uint32_t* im32 = (uint32_t*)Decompressed;
330 for( i = 0; i < DecompressedSize / 4; i++ )
332 low = im32[i] & 0x0000ffff; // 4321
333 high = im32[i] >> 16;
334 high = ( high >> 8 ) | ( high << 8 );
335 low = ( low >> 8 ) | ( low << 8 );
337 im32[i] = ( s32 << 16 ) | high;
341 for( i = 0; i < DecompressedSize / 4; i++ )
343 low = im32[i] & 0x0000ffff; // 2143
344 high = im32[i] >> 16;
345 high = ( high >> 8 ) | ( high << 8 );
346 low = ( low >> 8 ) | ( low << 8 );
348 im32[i] = ( s32 << 16 ) | low;
352 for( i = 0; i < DecompressedSize / 4; i++ )
354 low = im32[i] & 0x0000ffff; // 3412
355 high = im32[i] >> 16;
357 im32[i] = ( s32 << 16 ) | high;
361 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
362 "(32 bits) not allowed." );
368 * \brief Deal with endianity i.e. re-arange bytes inside the integer
370 void PixelConvert::ConvertReorderEndianity()
372 if ( BitsAllocated != 8 )
377 // Special kludge in order to deal with xmedcon broken images:
378 if ( ( BitsAllocated == 16 )
379 && ( BitsStored < BitsAllocated )
382 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
383 uint16_t *deb = (uint16_t *)Decompressed;
384 for(int i = 0; i<l; i++)
396 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
397 & file and decompress it.
398 * @param fp File Pointer
401 bool PixelConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
403 uint8_t* localDecompressed = Decompressed;
404 // Loop on the fragment[s]
405 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
406 it = JPEGInfo->Fragments.begin();
407 it != JPEGInfo->Fragments.end();
410 fp->seekg( (*it)->Offset, std::ios_base::beg);
414 if ( ! gdcm_read_JPEG2000_file( fp,localDecompressed ) )
419 else if ( BitsStored == 8)
421 // JPEG Lossy : call to IJG 6b
422 if ( ! gdcm_read_JPEG_file8( fp, localDecompressed ) )
427 else if ( BitsStored == 12)
429 // Reading Fragment pixels
430 if ( ! gdcm_read_JPEG_file12 ( fp, localDecompressed ) )
435 else if ( BitsStored == 16)
437 // Reading Fragment pixels
438 if ( ! gdcm_read_JPEG_file16 ( fp, localDecompressed ) )
442 //assert( IsJPEGLossless );
446 // other JPEG lossy not supported
447 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
448 "jpeg lossy compression ");
452 // Advance to next free location in Decompressed
453 // for next fragment decompression (if any)
454 int length = XSize * YSize * SamplesPerPixel;
455 int numberBytes = BitsAllocated / 8;
457 localDecompressed += length * numberBytes;
463 * \brief Re-arrange the bits within the bytes.
466 bool PixelConvert::ConvertReArrangeBits() throw ( FormatError )
468 if ( BitsStored != BitsAllocated )
470 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
471 if ( BitsAllocated == 16 )
473 uint16_t mask = 0xffff;
474 mask = mask >> ( BitsAllocated - BitsStored );
475 uint16_t* deb = (uint16_t*)Decompressed;
476 for(int i = 0; i<l; i++)
478 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
482 else if ( BitsAllocated == 32 )
484 uint32_t mask = 0xffffffff;
485 mask = mask >> ( BitsAllocated - BitsStored );
486 uint32_t* deb = (uint32_t*)Decompressed;
487 for(int i = 0; i<l; i++)
489 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
495 dbg.Verbose(0, "PixelConvert::ConvertReArrangeBits: weird image");
496 throw FormatError( "PixelConvert::ConvertReArrangeBits()",
504 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
505 * \warning Works on all the frames at a time
507 void PixelConvert::ConvertYcBcRPlanesToRGBPixels()
509 uint8_t* localDecompressed = Decompressed;
510 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
511 memmove( copyDecompressed, localDecompressed, DecompressedSize );
513 // to see the tricks about YBR_FULL, YBR_FULL_422,
514 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
515 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
516 // and be *very* affraid
518 int l = XSize * YSize;
519 int nbFrames = ZSize;
521 uint8_t* a = copyDecompressed;
522 uint8_t* b = copyDecompressed + l;
523 uint8_t* c = copyDecompressed + l + l;
526 /// \todo : Replace by the 'well known' integer computation
527 /// counterpart. Refer to
528 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
529 /// for code optimisation.
531 for ( int i = 0; i < nbFrames; i++ )
533 for ( int j = 0; j < l; j++ )
535 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
536 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
537 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
539 if (R < 0.0) R = 0.0;
540 if (G < 0.0) G = 0.0;
541 if (B < 0.0) B = 0.0;
542 if (R > 255.0) R = 255.0;
543 if (G > 255.0) G = 255.0;
544 if (B > 255.0) B = 255.0;
546 *(localDecompressed++) = (uint8_t)R;
547 *(localDecompressed++) = (uint8_t)G;
548 *(localDecompressed++) = (uint8_t)B;
554 delete[] copyDecompressed;
558 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
559 * \warning Works on all the frames at a time
561 void PixelConvert::ConvertRGBPlanesToRGBPixels()
563 uint8_t* localDecompressed = Decompressed;
564 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
565 memmove( copyDecompressed, localDecompressed, DecompressedSize );
567 int l = XSize * YSize * ZSize;
569 uint8_t* a = copyDecompressed;
570 uint8_t* b = copyDecompressed + l;
571 uint8_t* c = copyDecompressed + l + l;
573 for (int j = 0; j < l; j++)
575 *(localDecompressed++) = *(a++);
576 *(localDecompressed++) = *(b++);
577 *(localDecompressed++) = *(c++);
579 delete[] copyDecompressed;
582 bool PixelConvert::ReadAndDecompressPixelData( std::ifstream* fp )
584 ComputeDecompressedAndRGBSizes();
585 AllocateDecompressed();
586 //////////////////////////////////////////////////
587 //// First stage: get our hands on the Pixel Data.
590 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
591 "unavailable file pointer." );
595 fp->seekg( PixelOffset, std::ios_base::beg );
596 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
598 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
599 "unable to find PixelOffset in file." );
603 //////////////////////////////////////////////////
604 //// Second stage: read from disk dans decompress.
605 if ( BitsAllocated == 12 )
607 ReadAndDecompress12BitsTo16Bits( fp);
609 else if ( IsDecompressed )
611 fp->read( (char*)Decompressed, PixelDataLength);
612 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
614 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
615 "reading of decompressed pixel data failed." );
619 else if ( IsRLELossless )
621 if ( ! ReadAndDecompressRLEFile( fp ) )
623 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
624 "RLE decompressor failed." );
630 // Default case concerns JPEG family
631 if ( ! ReadAndDecompressJPEGFile( fp ) )
633 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
634 "JPEG decompressor failed." );
639 ////////////////////////////////////////////
640 //// Third stage: twigle the bytes and bits.
641 ConvertReorderEndianity();
642 ConvertReArrangeBits();
643 ConvertHandleColor();
648 void PixelConvert::ConvertHandleColor()
650 //////////////////////////////////
651 // Deal with the color decoding i.e. handle:
652 // - R, G, B planes (as opposed to RGB pixels)
653 // - YBR (various) encodings.
654 // - LUT[s] (or "PALETTE COLOR").
656 // The classification in the color decoding schema is based on the blending
657 // of two Dicom tags values:
658 // * "Photometric Interpretation" for which we have the cases:
659 // - [Photo A] MONOCHROME[1|2] pictures,
660 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
661 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
662 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
663 // * "Planar Configuration" for which we have the cases:
664 // - [Planar 0] 0 then Pixels are already RGB
665 // - [Planar 1] 1 then we have 3 planes : R, G, B,
666 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
668 // Now in theory, one could expect some coherence when blending the above
669 // cases. For example we should not encounter files belonging at the
670 // time to case [Planar 0] and case [Photo D].
671 // Alas, this was only theory ! Because in practice some odd (read ill
672 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
673 // - "Planar Configuration" = 0,
674 // - "Photometric Interpretation" = "PALETTE COLOR".
675 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
676 // towards Dicom-non-conformance files:
677 // << whatever the "Planar Configuration" value might be, a
678 // "Photometric Interpretation" set to "PALETTE COLOR" forces
679 // a LUT intervention >>
681 // Now we are left with the following handling of the cases:
682 // - [Planar 0] OR [Photo A] no color decoding (since respectively
683 // Pixels are already RGB and monochrome pictures have no color :),
684 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
685 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
686 // - [Planar 2] OR [Photo D] requires LUT intervention.
688 if ( ! IsDecompressedRGB() )
690 // [Planar 2] OR [Photo D]: LUT intervention done outside
694 if ( PlanarConfiguration == 1 )
698 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
699 ConvertYcBcRPlanesToRGBPixels();
703 // [Planar 1] AND [Photo C]
704 ConvertRGBPlanesToRGBPixels();
709 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
710 // pixels need to be RGB-fied anyway
713 ConvertRGBPlanesToRGBPixels();
715 // In *normal *case, when planarConf is 0, pixels are already in RGB
719 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
720 * \note See comments of \ref ConvertHandleColor
722 bool PixelConvert::IsDecompressedRGB()
725 || PlanarConfiguration == 2
733 void PixelConvert::ComputeDecompressedAndRGBSizes()
735 int bitsAllocated = BitsAllocated;
736 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
737 // in this case we will expand the image to 16 bits (see
738 // \ref ReadAndDecompress12BitsTo16Bits() )
739 if ( BitsAllocated == 12 )
744 DecompressedSize = XSize * YSize * ZSize
745 * ( bitsAllocated / 8 )
749 RGBSize = 3 * DecompressedSize;
754 void PixelConvert::GrabInformationsFromHeader( Header* header )
756 // Just in case some access to a Header element requires disk access.
757 // Note: gdcmDocument::Fp is leaved open after OpenFile.
758 std::ifstream* fp = header->OpenFile();
759 // Number of Bits Allocated for storing a Pixel is defaulted to 16
760 // when absent from the header.
761 BitsAllocated = header->GetBitsAllocated();
762 if ( BitsAllocated == 0 )
767 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
768 // when absent from the header.
769 BitsStored = header->GetBitsStored();
770 if ( BitsStored == 0 )
772 BitsStored = BitsAllocated;
776 HighBitPosition = header->GetHighBitPosition();
777 if ( HighBitPosition == 0 )
779 HighBitPosition = BitsAllocated - 1;
782 XSize = header->GetXSize();
783 YSize = header->GetYSize();
784 ZSize = header->GetZSize();
785 SamplesPerPixel = header->GetSamplesPerPixel();
786 PixelSize = header->GetPixelSize();
787 PixelSign = header->IsSignedPixelData();
788 SwapCode = header->GetSwapCode();
789 TransferSyntaxType ts = header->GetTransferSyntax();
791 ( ! header->IsDicomV3() )
792 || ts == ImplicitVRLittleEndian
793 || ts == ExplicitVRLittleEndian
794 || ts == ExplicitVRBigEndian
795 || ts == DeflatedExplicitVRLittleEndian;
796 IsJPEG2000 = header->IsJPEG2000();
797 IsJPEGLossless = header->IsJPEGLossless();
798 IsRLELossless = ( ts == RLELossless );
799 PixelOffset = header->GetPixelOffset();
800 PixelDataLength = header->GetPixelAreaLength();
801 RLEInfo = header->GetRLEInfo();
802 JPEGInfo = header->GetJPEGInfo();
804 PlanarConfiguration = header->GetPlanarConfiguration();
805 IsMonochrome = header->IsMonochrome();
806 IsPaletteColor = header->IsPaletteColor();
807 IsYBRFull = header->IsYBRFull();
809 /////////////////////////////////////////////////////////////////
811 HasLUT = header->HasLUT();
814 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
815 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
816 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
818 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
819 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
820 // Document::Document() ], the loading of the value (content) of a
821 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
822 // loaded). Hence, we first try to obtain the LUTs data from the header
823 // and when this fails we read the LUTs data directely from disk.
824 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
825 /// We should NOT bypass the [Bin|Val]Entry class. Instead
826 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
827 /// (e.g. BinEntry::GetBinArea()) should force disk access from
828 /// within the [Bin|Val]Entry class itself. The only problem
829 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
830 /// parsed from. Fix that. FIXME.
833 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
836 // Read the Lut Data from disk
837 DocEntry* lutRedDataEntry = header->GetDocEntryByNumber( 0x0028,
839 LutRedData = new uint8_t[ lutRedDataEntry->GetLength() ];
840 fp->seekg( lutRedDataEntry->GetOffset() ,std::ios_base::beg );
841 fp->read( (char*)LutRedData, (size_t)lutRedDataEntry->GetLength());
842 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
844 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
845 "unable to read red LUT data" );
851 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
854 // Read the Lut Data from disk
855 DocEntry* lutGreenDataEntry = header->GetDocEntryByNumber( 0x0028,
857 LutGreenData = new uint8_t[ lutGreenDataEntry->GetLength() ];
858 fp->seekg( lutGreenDataEntry->GetOffset() , std::ios_base::beg );
859 fp->read( (char*)LutGreenData, (size_t)lutGreenDataEntry->GetLength() );
860 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
862 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
863 "unable to read green LUT data" );
869 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
872 // Read the Lut Data from disk
873 DocEntry* lutBlueDataEntry = header->GetDocEntryByNumber( 0x0028,
875 LutBlueData = new uint8_t[ lutBlueDataEntry->GetLength() ];
876 fp->seekg( lutBlueDataEntry->GetOffset() , std::ios_base::beg );
877 fp->read( (char*)LutBlueData, (size_t)lutBlueDataEntry->GetLength() );
878 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
880 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
881 "unable to read blue LUT data" );
891 * \brief Build Red/Green/Blue/Alpha LUT from Header
892 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
893 * and (0028,1101),(0028,1102),(0028,1102)
894 * - xxx Palette Color Lookup Table Descriptor - are found
895 * and (0028,1201),(0028,1202),(0028,1202)
896 * - xxx Palette Color Lookup Table Data - are found
897 * \warning does NOT deal with :
898 * 0028 1100 Gray Lookup Table Descriptor (Retired)
899 * 0028 1221 Segmented Red Palette Color Lookup Table Data
900 * 0028 1222 Segmented Green Palette Color Lookup Table Data
901 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
902 * no known Dicom reader deals with them :-(
903 * @return a RGBA Lookup Table
905 void PixelConvert::BuildLUTRGBA()
912 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
914 if ( ! IsPaletteColor )
919 if ( LutRedDescriptor == GDCM_UNFOUND
920 || LutGreenDescriptor == GDCM_UNFOUND
921 || LutBlueDescriptor == GDCM_UNFOUND )
926 ////////////////////////////////////////////
927 // Extract the info from the LUT descriptors
928 int lengthR; // Red LUT length in Bytes
929 int debR; // Subscript of the first Lut Value
930 int nbitsR; // Lut item size (in Bits)
931 int nbRead = sscanf( LutRedDescriptor.c_str(),
933 &lengthR, &debR, &nbitsR );
936 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong red LUT descriptor");
939 int lengthG; // Green LUT length in Bytes
940 int debG; // Subscript of the first Lut Value
941 int nbitsG; // Lut item size (in Bits)
942 nbRead = sscanf( LutGreenDescriptor.c_str(),
944 &lengthG, &debG, &nbitsG );
947 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong green LUT descriptor");
950 int lengthB; // Blue LUT length in Bytes
951 int debB; // Subscript of the first Lut Value
952 int nbitsB; // Lut item size (in Bits)
953 nbRead = sscanf( LutRedDescriptor.c_str(),
955 &lengthB, &debB, &nbitsB );
958 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong blue LUT descriptor");
961 ////////////////////////////////////////////////////////
962 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
967 ////////////////////////////////////////////////
968 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
969 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
974 memset( LutRGBA, 0, 1024 );
977 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
979 // when LUT item size is different than pixel size
980 mult = 2; // high byte must be = low byte
984 // See PS 3.3-2003 C.11.1.1.2 p 619
988 // if we get a black image, let's just remove the '+1'
989 // from 'i*mult+1' and check again
990 // if it works, we shall have to check the 3 Palettes
991 // to see which byte is ==0 (first one, or second one)
993 // We give up the checking to avoid some (useless ?)overhead
994 // (optimistic asumption)
996 uint8_t* a = LutRGBA + 0;
997 for( i=0; i < lengthR; ++i )
999 *a = LutRedData[i*mult+1];
1004 for( i=0; i < lengthG; ++i)
1006 *a = LutGreenData[i*mult+1];
1011 for(i=0; i < lengthB; ++i)
1013 *a = LutBlueData[i*mult+1];
1018 for(i=0; i < 256; ++i)
1020 *a = 1; // Alpha component
1026 * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1028 bool PixelConvert::BuildRGBImage()
1032 // The job is already done.
1036 if ( ! Decompressed )
1038 // The job can't be done
1045 // The job can't be done
1051 uint8_t* localRGB = RGB;
1052 for (size_t i = 0; i < DecompressedSize; ++i )
1054 int j = Decompressed[i] * 4;
1055 *localRGB++ = LutRGBA[j];
1056 *localRGB++ = LutRGBA[j+1];
1057 *localRGB++ = LutRGBA[j+2];
1063 * \brief Print self.
1064 * @param indent Indentation string to be prepended during printing.
1065 * @param os Stream to print to.
1067 void PixelConvert::Print( std::string indent, std::ostream &os )
1070 << "--- Pixel information -------------------------"
1073 << "Pixel Data: offset " << PixelOffset
1074 << " x" << std::hex << PixelOffset << std::dec
1075 << " length " << PixelDataLength
1076 << " x" << std::hex << PixelDataLength << std::dec
1079 if ( IsRLELossless )
1083 RLEInfo->Print( indent, os );
1087 dbg.Verbose(0, "PixelConvert::Print: set as RLE file "
1088 "but NO RLEinfo present.");
1092 if ( IsJPEG2000 || IsJPEGLossless )
1096 JPEGInfo->Print( indent, os );
1100 dbg.Verbose(0, "PixelConvert::Print: set as JPEG file "
1101 "but NO JPEGinfo present.");
1106 } // end namespace gdcm
1108 // NOTES on File internal calls
1110 // ---> GetImageData
1111 // ---> GetImageDataIntoVector
1112 // |---> GetImageDataIntoVectorRaw
1113 // | lut intervention
1115 // ---> GetImageDataRaw
1116 // ---> GetImageDataIntoVectorRaw