1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2004/12/09 10:11:38 $
7 Version: $Revision: 1.4 $
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 PixelReadConvert everywhere and clean up !
25 #include "gdcmDebug.h"
26 #include "gdcmHeader.h"
27 #include "gdcmPixelReadConvert.h"
28 #include "gdcmDocEntry.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
33 #include <stdio.h> //for sscanf
37 #define str2num(str, typeNum) *((typeNum *)(str))
39 // For JPEG 2000, body in file gdcmJpeg2000.cxx
40 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
42 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
43 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
45 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
46 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
48 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
49 // Beware this is misleading there is no 16bits DCT algorithm, only
50 // jpeg lossless compression exist in 16bits.
51 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
54 //-----------------------------------------------------------------------------
55 // Constructor / Destructor
56 PixelReadConvert::PixelReadConvert()
68 void PixelReadConvert::Squeeze()
78 delete [] Decompressed;
89 PixelReadConvert::~PixelReadConvert()
94 void PixelReadConvert::AllocateRGB()
99 RGB = new uint8_t[ RGBSize ];
102 void PixelReadConvert::AllocateDecompressed()
104 if ( Decompressed ) {
105 delete [] Decompressed;
107 Decompressed = new uint8_t[ DecompressedSize ];
111 * \brief Read from file a 12 bits per pixel image and decompress it
112 * into a 16 bits per pixel image.
114 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
115 throw ( FormatError )
117 int nbPixels = XSize * YSize;
118 uint16_t* localDecompres = (uint16_t*)Decompressed;
120 for( int p = 0; p < nbPixels; p += 2 )
124 fp->read( (char*)&b0, 1);
125 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
127 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
128 "Unfound first block" );
131 fp->read( (char*)&b1, 1 );
132 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
134 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
135 "Unfound second block" );
138 fp->read( (char*)&b2, 1 );
139 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
141 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
142 "Unfound second block" );
145 // Two steps are necessary to please VC++
147 // 2 pixels 12bit = [0xABCDEF]
148 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
150 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
152 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
154 /// \todo JPR Troubles expected on Big-Endian processors ?
159 * \brief Try to deal with RLE 16 Bits.
160 * We assume the RLE has allready been parsed and loaded in
161 * Decompressed (through \ref ReadAndDecompressJPEGFile ).
162 * We here need to make 16 Bits Pixels from Low Byte and
163 * High Byte 'Planes'...(for what it may mean)
166 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
168 size_t PixelNumber = XSize * YSize;
169 size_t decompressedSize = XSize * YSize * NumberOfFrames;
171 // We assumed Decompressed contains the decoded RLE pixels but as
172 // 8 bits per pixel. In order to convert those pixels to 16 bits
173 // per pixel we cannot work in place within Decompressed and hence
174 // we copy it in a safe place, say copyDecompressed.
176 uint8_t* copyDecompressed = new uint8_t[ decompressedSize * 2 ];
177 memmove( copyDecompressed, Decompressed, decompressedSize * 2 );
179 uint8_t* x = Decompressed;
180 uint8_t* a = copyDecompressed;
181 uint8_t* b = a + PixelNumber;
183 for ( int i = 0; i < NumberOfFrames; i++ )
185 for ( unsigned int j = 0; j < PixelNumber; j++ )
192 delete[] copyDecompressed;
194 /// \todo check that operator new []didn't fail, and sometimes return false
199 * \brief Implementation of the RLE decoding algorithm for decompressing
200 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
201 * @param subDecompressed Sub region of \ref Decompressed where the de
202 * decoded fragment should be placed.
203 * @param fragmentSize The length of the binary fragment as found on the disk.
204 * @param decompressedSegmentSize The expected length of the fragment ONCE
206 * @param fp File Pointer: on entry the position should be the one of
207 * the fragment to be decoded.
209 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t* subDecompressed,
211 long decompressedSegmentSize,
215 long numberOfOutputBytes = 0;
216 long numberOfReadBytes = 0;
218 while( numberOfOutputBytes < decompressedSegmentSize )
220 fp->read( (char*)&count, 1 );
221 numberOfReadBytes += 1;
223 // Note: count <= 127 comparison is always true due to limited range
224 // of data type int8_t [since the maximum of an exact width
225 // signed integer of width N is 2^(N-1) - 1, which for int8_t
228 fp->read( (char*)subDecompressed, count + 1);
229 numberOfReadBytes += count + 1;
230 subDecompressed += count + 1;
231 numberOfOutputBytes += count + 1;
235 if ( ( count <= -1 ) && ( count >= -127 ) )
238 fp->read( (char*)&newByte, 1);
239 numberOfReadBytes += 1;
240 for( int i = 0; i < -count + 1; i++ )
242 subDecompressed[i] = newByte;
244 subDecompressed += -count + 1;
245 numberOfOutputBytes += -count + 1;
248 // if count = 128 output nothing
250 if ( numberOfReadBytes > fragmentSize )
252 dbg.Verbose(0, "PixelReadConvert::ReadAndDecompressRLEFragment: we "
253 "read more bytes than the segment size.");
261 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
262 * Dicom encapsulated file and decompress it.
263 * @param fp already open File Pointer
264 * at which the pixel data should be copied
267 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
269 uint8_t* subDecompressed = Decompressed;
270 long decompressedSegmentSize = XSize * YSize;
272 // Loop on the frame[s]
273 for( RLEFramesInfo::RLEFrameList::iterator
274 it = RLEInfo->Frames.begin();
275 it != RLEInfo->Frames.end();
278 // Loop on the fragments
279 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
281 fp->seekg( (*it)->Offset[k] , std::ios::beg );
282 (void)ReadAndDecompressRLEFragment( subDecompressed,
284 decompressedSegmentSize,
286 subDecompressed += decompressedSegmentSize;
290 if ( BitsAllocated == 16 )
292 // Try to deal with RLE 16 Bits
293 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
300 * \brief Swap the bytes, according to \ref SwapCode.
302 void PixelReadConvert::ConvertSwapZone()
306 if( BitsAllocated == 16 )
308 uint16_t* im16 = (uint16_t*)Decompressed;
319 for( i = 0; i < DecompressedSize / 2; i++ )
321 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
325 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
326 "(16 bits) not allowed." );
329 else if( BitsAllocated == 32 )
334 uint32_t* im32 = (uint32_t*)Decompressed;
341 for( i = 0; i < DecompressedSize / 4; i++ )
343 low = im32[i] & 0x0000ffff; // 4321
344 high = im32[i] >> 16;
345 high = ( high >> 8 ) | ( high << 8 );
346 low = ( low >> 8 ) | ( low << 8 );
348 im32[i] = ( s32 << 16 ) | high;
352 for( i = 0; i < DecompressedSize / 4; i++ )
354 low = im32[i] & 0x0000ffff; // 2143
355 high = im32[i] >> 16;
356 high = ( high >> 8 ) | ( high << 8 );
357 low = ( low >> 8 ) | ( low << 8 );
359 im32[i] = ( s32 << 16 ) | low;
363 for( i = 0; i < DecompressedSize / 4; i++ )
365 low = im32[i] & 0x0000ffff; // 3412
366 high = im32[i] >> 16;
368 im32[i] = ( s32 << 16 ) | high;
372 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
373 "(32 bits) not allowed." );
379 * \brief Deal with endianity i.e. re-arange bytes inside the integer
381 void PixelReadConvert::ConvertReorderEndianity()
383 if ( BitsAllocated != 8 )
388 // Special kludge in order to deal with xmedcon broken images:
389 if ( ( BitsAllocated == 16 )
390 && ( BitsStored < BitsAllocated )
393 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
394 uint16_t *deb = (uint16_t *)Decompressed;
395 for(int i = 0; i<l; i++)
407 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
408 & file and decompress it.
409 * @param fp File Pointer
412 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
414 uint8_t* localDecompressed = Decompressed;
415 // Loop on the fragment[s]
416 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
417 it = JPEGInfo->Fragments.begin();
418 it != JPEGInfo->Fragments.end();
421 fp->seekg( (*it)->Offset, std::ios::beg);
425 if ( ! gdcm_read_JPEG2000_file( fp,localDecompressed ) )
430 else if ( BitsStored == 8)
432 // JPEG Lossy : call to IJG 6b
433 if ( ! gdcm_read_JPEG_file8( fp, localDecompressed ) )
438 else if ( BitsStored <= 12)
440 // Reading Fragment pixels
441 if ( ! gdcm_read_JPEG_file12 ( fp, localDecompressed ) )
446 else if ( BitsStored <= 16)
448 // Reading Fragment pixels
449 if ( ! gdcm_read_JPEG_file16 ( fp, localDecompressed ) )
453 //assert( IsJPEGLossless );
457 // other JPEG lossy not supported
458 dbg.Error("PixelReadConvert::ReadAndDecompressJPEGFile: unknown "
459 "jpeg lossy compression ");
463 // Advance to next free location in Decompressed
464 // for next fragment decompression (if any)
465 int length = XSize * YSize * SamplesPerPixel;
466 int numberBytes = BitsAllocated / 8;
468 localDecompressed += length * numberBytes;
474 * \brief Re-arrange the bits within the bytes.
477 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
479 if ( BitsStored != BitsAllocated )
481 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
482 if ( BitsAllocated == 16 )
484 uint16_t mask = 0xffff;
485 mask = mask >> ( BitsAllocated - BitsStored );
486 uint16_t* deb = (uint16_t*)Decompressed;
487 for(int i = 0; i<l; i++)
489 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
493 else if ( BitsAllocated == 32 )
495 uint32_t mask = 0xffffffff;
496 mask = mask >> ( BitsAllocated - BitsStored );
497 uint32_t* deb = (uint32_t*)Decompressed;
498 for(int i = 0; i<l; i++)
500 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
506 dbg.Verbose(0, "PixelReadConvert::ConvertReArrangeBits: weird image");
507 throw FormatError( "PixelReadConvert::ConvertReArrangeBits()",
515 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
516 * \warning Works on all the frames at a time
518 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
520 uint8_t* localDecompressed = Decompressed;
521 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
522 memmove( copyDecompressed, localDecompressed, DecompressedSize );
524 // to see the tricks about YBR_FULL, YBR_FULL_422,
525 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
526 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
527 // and be *very* affraid
529 int l = XSize * YSize;
530 int nbFrames = ZSize;
532 uint8_t* a = copyDecompressed;
533 uint8_t* b = copyDecompressed + l;
534 uint8_t* c = copyDecompressed + l + l;
537 /// \todo : Replace by the 'well known' integer computation
538 /// counterpart. Refer to
539 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
540 /// for code optimisation.
542 for ( int i = 0; i < nbFrames; i++ )
544 for ( int j = 0; j < l; j++ )
546 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
547 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
548 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
550 if (R < 0.0) R = 0.0;
551 if (G < 0.0) G = 0.0;
552 if (B < 0.0) B = 0.0;
553 if (R > 255.0) R = 255.0;
554 if (G > 255.0) G = 255.0;
555 if (B > 255.0) B = 255.0;
557 *(localDecompressed++) = (uint8_t)R;
558 *(localDecompressed++) = (uint8_t)G;
559 *(localDecompressed++) = (uint8_t)B;
565 delete[] copyDecompressed;
569 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
570 * \warning Works on all the frames at a time
572 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
574 uint8_t* localDecompressed = Decompressed;
575 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
576 memmove( copyDecompressed, localDecompressed, DecompressedSize );
578 int l = XSize * YSize * ZSize;
580 uint8_t* a = copyDecompressed;
581 uint8_t* b = copyDecompressed + l;
582 uint8_t* c = copyDecompressed + l + l;
584 for (int j = 0; j < l; j++)
586 *(localDecompressed++) = *(a++);
587 *(localDecompressed++) = *(b++);
588 *(localDecompressed++) = *(c++);
590 delete[] copyDecompressed;
593 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream* fp )
595 // ComputeDecompressedAndRGBSizes is already made by
596 // ::GrabInformationsFromHeader. So, the structure sizes are
600 //////////////////////////////////////////////////
601 //// First stage: get our hands on the Pixel Data.
604 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
605 "unavailable file pointer." );
609 fp->seekg( PixelOffset, std::ios::beg );
610 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
612 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
613 "unable to find PixelOffset in file." );
617 AllocateDecompressed();
619 //////////////////////////////////////////////////
620 //// Second stage: read from disk dans decompress.
621 if ( BitsAllocated == 12 )
623 ReadAndDecompress12BitsTo16Bits( fp);
625 else if ( IsDecompressed )
627 // This problem can be found when some obvious informations are found
628 // after the field containing the image datas. In this case, these
629 // bad datas are added to the size of the image (in the PixelDataLength
630 // variable). But DecompressedSize is the right size of the image !
631 if( PixelDataLength != DecompressedSize)
633 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
634 "Mismatch between PixelReadConvert and DecompressedSize." );
636 if( PixelDataLength > DecompressedSize)
638 fp->read( (char*)Decompressed, DecompressedSize);
642 fp->read( (char*)Decompressed, PixelDataLength);
645 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
647 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
648 "reading of decompressed pixel data failed." );
652 else if ( IsRLELossless )
654 if ( ! ReadAndDecompressRLEFile( fp ) )
656 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
657 "RLE decompressor failed." );
663 // Default case concerns JPEG family
664 if ( ! ReadAndDecompressJPEGFile( fp ) )
666 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
667 "JPEG decompressor failed." );
672 ////////////////////////////////////////////
673 //// Third stage: twigle the bytes and bits.
674 ConvertReorderEndianity();
675 ConvertReArrangeBits();
676 ConvertHandleColor();
681 void PixelReadConvert::ConvertHandleColor()
683 //////////////////////////////////
684 // Deal with the color decoding i.e. handle:
685 // - R, G, B planes (as opposed to RGB pixels)
686 // - YBR (various) encodings.
687 // - LUT[s] (or "PALETTE COLOR").
689 // The classification in the color decoding schema is based on the blending
690 // of two Dicom tags values:
691 // * "Photometric Interpretation" for which we have the cases:
692 // - [Photo A] MONOCHROME[1|2] pictures,
693 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
694 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
695 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
696 // * "Planar Configuration" for which we have the cases:
697 // - [Planar 0] 0 then Pixels are already RGB
698 // - [Planar 1] 1 then we have 3 planes : R, G, B,
699 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
701 // Now in theory, one could expect some coherence when blending the above
702 // cases. For example we should not encounter files belonging at the
703 // time to case [Planar 0] and case [Photo D].
704 // Alas, this was only theory ! Because in practice some odd (read ill
705 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
706 // - "Planar Configuration" = 0,
707 // - "Photometric Interpretation" = "PALETTE COLOR".
708 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
709 // towards Dicom-non-conformance files:
710 // << whatever the "Planar Configuration" value might be, a
711 // "Photometric Interpretation" set to "PALETTE COLOR" forces
712 // a LUT intervention >>
714 // Now we are left with the following handling of the cases:
715 // - [Planar 0] OR [Photo A] no color decoding (since respectively
716 // Pixels are already RGB and monochrome pictures have no color :),
717 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
718 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
719 // - [Planar 2] OR [Photo D] requires LUT intervention.
721 if ( ! IsDecompressedRGB() )
723 // [Planar 2] OR [Photo D]: LUT intervention done outside
727 if ( PlanarConfiguration == 1 )
731 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
732 ConvertYcBcRPlanesToRGBPixels();
736 // [Planar 1] AND [Photo C]
737 ConvertRGBPlanesToRGBPixels();
742 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
743 // pixels need to be RGB-fied anyway
746 ConvertRGBPlanesToRGBPixels();
748 // In *normal *case, when planarConf is 0, pixels are already in RGB
752 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
753 * \note See comments of \ref ConvertHandleColor
755 bool PixelReadConvert::IsDecompressedRGB()
758 || PlanarConfiguration == 2
766 void PixelReadConvert::ComputeDecompressedAndRGBSizes()
768 int bitsAllocated = BitsAllocated;
769 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
770 // in this case we will expand the image to 16 bits (see
771 // \ref ReadAndDecompress12BitsTo16Bits() )
772 if ( BitsAllocated == 12 )
777 DecompressedSize = XSize * YSize * ZSize
778 * ( bitsAllocated / 8 )
782 RGBSize = 3 * DecompressedSize;
786 RGBSize = DecompressedSize;
790 void PixelReadConvert::GrabInformationsFromHeader( Header* header )
792 // Number of Bits Allocated for storing a Pixel is defaulted to 16
793 // when absent from the header.
794 BitsAllocated = header->GetBitsAllocated();
795 if ( BitsAllocated == 0 )
800 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
801 // when absent from the header.
802 BitsStored = header->GetBitsStored();
803 if ( BitsStored == 0 )
805 BitsStored = BitsAllocated;
809 HighBitPosition = header->GetHighBitPosition();
810 if ( HighBitPosition == 0 )
812 HighBitPosition = BitsAllocated - 1;
815 XSize = header->GetXSize();
816 YSize = header->GetYSize();
817 ZSize = header->GetZSize();
818 SamplesPerPixel = header->GetSamplesPerPixel();
819 PixelSize = header->GetPixelSize();
820 PixelSign = header->IsSignedPixelData();
821 SwapCode = header->GetSwapCode();
822 TransferSyntaxType ts = header->GetTransferSyntax();
824 ( ! header->IsDicomV3() )
825 || ts == ImplicitVRLittleEndian
826 || ts == ImplicitVRLittleEndianDLXGE
827 || ts == ExplicitVRLittleEndian
828 || ts == ExplicitVRBigEndian
829 || ts == DeflatedExplicitVRLittleEndian;
830 IsJPEG2000 = header->IsJPEG2000();
831 IsJPEGLossless = header->IsJPEGLossless();
832 IsRLELossless = ( ts == RLELossless );
833 PixelOffset = header->GetPixelOffset();
834 PixelDataLength = header->GetPixelAreaLength();
835 RLEInfo = header->GetRLEInfo();
836 JPEGInfo = header->GetJPEGInfo();
838 PlanarConfiguration = header->GetPlanarConfiguration();
839 IsMonochrome = header->IsMonochrome();
840 IsPaletteColor = header->IsPaletteColor();
841 IsYBRFull = header->IsYBRFull();
843 /////////////////////////////////////////////////////////////////
845 HasLUT = header->HasLUT();
848 // Just in case some access to a Header element requires disk access.
849 // Note: gdcmDocument::Fp is leaved open after OpenFile.
850 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
851 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
852 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
854 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
855 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
856 // Document::Document() ], the loading of the value (content) of a
857 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
858 // loaded). Hence, we first try to obtain the LUTs data from the header
859 // and when this fails we read the LUTs data directely from disk.
860 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
861 /// We should NOT bypass the [Bin|Val]Entry class. Instead
862 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
863 /// (e.g. BinEntry::GetBinArea()) should force disk access from
864 /// within the [Bin|Val]Entry class itself. The only problem
865 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
866 /// parsed from. Fix that. FIXME.
869 header->LoadEntryBinArea(0x0028, 0x1201);
870 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
873 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
874 "unable to read red LUT data" );
878 header->LoadEntryBinArea(0x0028, 0x1202);
879 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
882 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
883 "unable to read green LUT data" );
887 header->LoadEntryBinArea(0x0028, 0x1203);
888 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
891 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
892 "unable to read blue LUT data" );
896 ComputeDecompressedAndRGBSizes();
900 * \brief Build Red/Green/Blue/Alpha LUT from Header
901 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
902 * and (0028,1101),(0028,1102),(0028,1102)
903 * - xxx Palette Color Lookup Table Descriptor - are found
904 * and (0028,1201),(0028,1202),(0028,1202)
905 * - xxx Palette Color Lookup Table Data - are found
906 * \warning does NOT deal with :
907 * 0028 1100 Gray Lookup Table Descriptor (Retired)
908 * 0028 1221 Segmented Red Palette Color Lookup Table Data
909 * 0028 1222 Segmented Green Palette Color Lookup Table Data
910 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
911 * no known Dicom reader deals with them :-(
912 * @return a RGBA Lookup Table
914 void PixelReadConvert::BuildLUTRGBA()
921 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
923 if ( ! IsPaletteColor )
928 if ( LutRedDescriptor == GDCM_UNFOUND
929 || LutGreenDescriptor == GDCM_UNFOUND
930 || LutBlueDescriptor == GDCM_UNFOUND )
935 ////////////////////////////////////////////
936 // Extract the info from the LUT descriptors
937 int lengthR; // Red LUT length in Bytes
938 int debR; // Subscript of the first Lut Value
939 int nbitsR; // Lut item size (in Bits)
940 int nbRead = sscanf( LutRedDescriptor.c_str(),
942 &lengthR, &debR, &nbitsR );
945 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong red LUT descriptor");
948 int lengthG; // Green LUT length in Bytes
949 int debG; // Subscript of the first Lut Value
950 int nbitsG; // Lut item size (in Bits)
951 nbRead = sscanf( LutGreenDescriptor.c_str(),
953 &lengthG, &debG, &nbitsG );
956 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong green LUT descriptor");
959 int lengthB; // Blue LUT length in Bytes
960 int debB; // Subscript of the first Lut Value
961 int nbitsB; // Lut item size (in Bits)
962 nbRead = sscanf( LutRedDescriptor.c_str(),
964 &lengthB, &debB, &nbitsB );
967 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong blue LUT descriptor");
970 ////////////////////////////////////////////////////////
971 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
976 ////////////////////////////////////////////////
977 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
978 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
983 memset( LutRGBA, 0, 1024 );
986 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
988 // when LUT item size is different than pixel size
989 mult = 2; // high byte must be = low byte
993 // See PS 3.3-2003 C.11.1.1.2 p 619
997 // if we get a black image, let's just remove the '+1'
998 // from 'i*mult+1' and check again
999 // if it works, we shall have to check the 3 Palettes
1000 // to see which byte is ==0 (first one, or second one)
1002 // We give up the checking to avoid some (useless ?)overhead
1003 // (optimistic asumption)
1005 uint8_t* a = LutRGBA + 0;
1006 for( i=0; i < lengthR; ++i )
1008 *a = LutRedData[i*mult+1];
1013 for( i=0; i < lengthG; ++i)
1015 *a = LutGreenData[i*mult+1];
1020 for(i=0; i < lengthB; ++i)
1022 *a = LutBlueData[i*mult+1];
1027 for(i=0; i < 256; ++i)
1029 *a = 1; // Alpha component
1035 * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1037 bool PixelReadConvert::BuildRGBImage()
1041 // The job is already done.
1045 if ( ! Decompressed )
1047 // The job can't be done
1054 // The job can't be done
1060 uint8_t* localRGB = RGB;
1061 for (size_t i = 0; i < DecompressedSize; ++i )
1063 int j = Decompressed[i] * 4;
1064 *localRGB++ = LutRGBA[j];
1065 *localRGB++ = LutRGBA[j+1];
1066 *localRGB++ = LutRGBA[j+2];
1072 * \brief Print self.
1073 * @param indent Indentation string to be prepended during printing.
1074 * @param os Stream to print to.
1076 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1079 << "--- Pixel information -------------------------"
1082 << "Pixel Data: offset " << PixelOffset
1083 << " x" << std::hex << PixelOffset << std::dec
1084 << " length " << PixelDataLength
1085 << " x" << std::hex << PixelDataLength << std::dec
1088 if ( IsRLELossless )
1092 RLEInfo->Print( indent, os );
1096 dbg.Verbose(0, "PixelReadConvert::Print: set as RLE file "
1097 "but NO RLEinfo present.");
1101 if ( IsJPEG2000 || IsJPEGLossless )
1105 JPEGInfo->Print( indent, os );
1109 dbg.Verbose(0, "PixelReadConvert::Print: set as JPEG file "
1110 "but NO JPEGinfo present.");
1115 } // end namespace gdcm
1117 // NOTES on File internal calls
1119 // ---> GetImageData
1120 // ---> GetImageDataIntoVector
1121 // |---> GetImageDataIntoVectorRaw
1122 // | lut intervention
1124 // ---> GetImageDataRaw
1125 // ---> GetImageDataIntoVectorRaw