1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/21 11:40:55 $
7 Version: $Revision: 1.31 $
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 #include "gdcmDebug.h"
21 #include "gdcmGlobal.h"
23 #include "gdcmPixelReadConvert.h"
24 #include "gdcmDocEntry.h"
25 #include "gdcmRLEFramesInfo.h"
26 #include "gdcmJPEGFragmentsInfo.h"
29 #include <stdio.h> //for sscanf
33 #define str2num(str, typeNum) *((typeNum *)(str))
36 //-----------------------------------------------------------------------------
37 // Constructor / Destructor
38 PixelReadConvert::PixelReadConvert()
50 void PixelReadConvert::Squeeze()
71 PixelReadConvert::~PixelReadConvert()
76 void PixelReadConvert::AllocateRGB()
81 RGB = new uint8_t[ RGBSize ];
84 void PixelReadConvert::AllocateRaw()
89 Raw = new uint8_t[ RawSize ];
93 * \brief Read from file a 12 bits per pixel image and decompress it
94 * into a 16 bits per pixel image.
96 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
99 int nbPixels = XSize * YSize;
100 uint16_t* localDecompres = (uint16_t*)Raw;
102 for( int p = 0; p < nbPixels; p += 2 )
106 fp->read( (char*)&b0, 1);
107 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
109 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
110 "Unfound first block" );
113 fp->read( (char*)&b1, 1 );
114 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
116 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
117 "Unfound second block" );
120 fp->read( (char*)&b2, 1 );
121 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
123 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
124 "Unfound second block" );
127 // Two steps are necessary to please VC++
129 // 2 pixels 12bit = [0xABCDEF]
130 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
132 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
134 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
136 /// \todo JPR Troubles expected on Big-Endian processors ?
141 * \brief Try to deal with RLE 16 Bits.
142 * We assume the RLE has already been parsed and loaded in
143 * Raw (through \ref ReadAndDecompressJPEGFile ).
144 * We here need to make 16 Bits Pixels from Low Byte and
145 * High Byte 'Planes'...(for what it may mean)
148 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
150 size_t pixelNumber = XSize * YSize;
151 size_t rawSize = XSize * YSize * NumberOfFrames;
153 // We assumed Raw contains the decoded RLE pixels but as
154 // 8 bits per pixel. In order to convert those pixels to 16 bits
155 // per pixel we cannot work in place within Raw and hence
156 // we copy it in a safe place, say copyRaw.
158 uint8_t* copyRaw = new uint8_t[ rawSize * 2 ];
159 memmove( copyRaw, Raw, rawSize * 2 );
162 uint8_t* a = copyRaw;
163 uint8_t* b = a + pixelNumber;
165 for ( int i = 0; i < NumberOfFrames; i++ )
167 for ( unsigned int j = 0; j < pixelNumber; j++ )
176 /// \todo check that operator new []didn't fail, and sometimes return false
181 * \brief Implementation of the RLE decoding algorithm for decompressing
182 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
183 * @param subRaw Sub region of \ref Raw where the de
184 * decoded fragment should be placed.
185 * @param fragmentSize The length of the binary fragment as found on the disk.
186 * @param RawSegmentSize The expected length of the fragment ONCE
188 * @param fp File Pointer: on entry the position should be the one of
189 * the fragment to be decoded.
191 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t *subRaw,
197 long numberOfOutputBytes = 0;
198 long numberOfReadBytes = 0;
200 while( numberOfOutputBytes < RawSegmentSize )
202 fp->read( (char*)&count, 1 );
203 numberOfReadBytes += 1;
205 // Note: count <= 127 comparison is always true due to limited range
206 // of data type int8_t [since the maximum of an exact width
207 // signed integer of width N is 2^(N-1) - 1, which for int8_t
210 fp->read( (char*)subRaw, count + 1);
211 numberOfReadBytes += count + 1;
213 numberOfOutputBytes += count + 1;
217 if ( ( count <= -1 ) && ( count >= -127 ) )
220 fp->read( (char*)&newByte, 1);
221 numberOfReadBytes += 1;
222 for( int i = 0; i < -count + 1; i++ )
226 subRaw += -count + 1;
227 numberOfOutputBytes += -count + 1;
230 // if count = 128 output nothing
232 if ( numberOfReadBytes > fragmentSize )
234 gdcmVerboseMacro( "Read more bytes than the segment size.");
242 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
243 * Dicom encapsulated file and decompress it.
244 * @param fp already open File Pointer
245 * at which the pixel data should be copied
248 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream *fp )
250 uint8_t *subRaw = Raw;
251 long RawSegmentSize = XSize * YSize;
253 // Loop on the frame[s]
254 for( RLEFramesInfo::RLEFrameList::iterator
255 it = RLEInfo->Frames.begin();
256 it != RLEInfo->Frames.end();
259 // Loop on the fragments
260 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
262 fp->seekg( (*it)->Offset[k] , std::ios::beg );
263 (void)ReadAndDecompressRLEFragment( subRaw,
267 subRaw += RawSegmentSize;
271 if ( BitsAllocated == 16 )
273 // Try to deal with RLE 16 Bits
274 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
281 * \brief Swap the bytes, according to \ref SwapCode.
283 void PixelReadConvert::ConvertSwapZone()
287 if( BitsAllocated == 16 )
289 uint16_t *im16 = (uint16_t*)Raw;
297 for( i = 0; i < RawSize / 2; i++ )
299 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
303 gdcmVerboseMacro("SwapCode value (16 bits) not allowed.");
306 else if( BitsAllocated == 32 )
311 uint32_t* im32 = (uint32_t*)Raw;
317 for( i = 0; i < RawSize / 4; i++ )
319 low = im32[i] & 0x0000ffff; // 4321
320 high = im32[i] >> 16;
321 high = ( high >> 8 ) | ( high << 8 );
322 low = ( low >> 8 ) | ( low << 8 );
324 im32[i] = ( s32 << 16 ) | high;
328 for( i = 0; i < RawSize / 4; i++ )
330 low = im32[i] & 0x0000ffff; // 2143
331 high = im32[i] >> 16;
332 high = ( high >> 8 ) | ( high << 8 );
333 low = ( low >> 8 ) | ( low << 8 );
335 im32[i] = ( s32 << 16 ) | low;
339 for( i = 0; i < RawSize / 4; i++ )
341 low = im32[i] & 0x0000ffff; // 3412
342 high = im32[i] >> 16;
344 im32[i] = ( s32 << 16 ) | high;
348 gdcmVerboseMacro("SwapCode value (32 bits) not allowed." );
354 * \brief Deal with endianity i.e. re-arange bytes inside the integer
356 void PixelReadConvert::ConvertReorderEndianity()
358 if ( BitsAllocated != 8 )
363 // Special kludge in order to deal with xmedcon broken images:
364 if ( BitsAllocated == 16
365 && BitsStored < BitsAllocated
368 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
369 uint16_t *deb = (uint16_t *)Raw;
370 for(int i = 0; i<l; i++)
383 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
384 * file and decompress it. This function assumes that each
385 * jpeg fragment contains a whole frame (jpeg file).
386 * @param fp File Pointer
389 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream *fp )
391 // Pointer to the Raw image
392 uint8_t *localRaw = Raw;
394 // Precompute the offset localRaw will be shifted with
395 int length = XSize * YSize * SamplesPerPixel;
396 int numberBytes = BitsAllocated / 8;
398 // Loop on the fragment[s]
399 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
400 it = JPEGInfo->Fragments.begin();
401 it != JPEGInfo->Fragments.end();
404 (*it)->DecompressJPEGFramesFromFile(fp, localRaw, BitsStored );
406 // Advance to next free location in Raw
407 // for next fragment decompression (if any)
409 localRaw += length * numberBytes;
415 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
416 * file and decompress it. This function assumes that the dicom
417 * image is a single frame split into several JPEG fragments.
418 * Those fragments will be glued together into a memory buffer
420 * @param fp File Pointer
423 bool PixelReadConvert::
424 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
426 // Loop on the fragment[s] to get total length
427 size_t totalLength = JPEGInfo->GetFragmentsLength();
429 // Concatenate the jpeg fragments into a local buffer
430 JOCTET *buffer = new JOCTET [totalLength];
431 // Fill in the buffer:
432 JPEGInfo->ReadAllFragments(fp, buffer);
435 JPEGFragmentsInfo::JPEGFragmentsList::const_iterator it = JPEGInfo->Fragments.begin();
436 (*it)->DecompressJPEGSingleFrameFragmentsFromFile(buffer, totalLength, Raw, BitsStored);
445 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
446 * file and decompress it. This function handles the generic
447 * and complex case where the DICOM contains several frames,
448 * and some of the frames are possibly split into several JPEG
450 * @param fp File Pointer
453 bool PixelReadConvert::
454 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
456 // Loop on the fragment[s] to get total length
457 size_t totalLength = JPEGInfo->GetFragmentsLength();
459 // Concatenate the jpeg fragments into a local buffer
460 JOCTET *buffer = new JOCTET [totalLength];
461 // Fill in the buffer:
462 JPEGInfo->ReadAllFragments(fp, buffer);
464 size_t howManyRead = 0;
465 size_t howManyWritten = 0;
466 size_t fragmentLength = 0;
468 JPEGFragmentsInfo::JPEGFragmentsList::const_iterator it;
469 for( it = JPEGInfo->Fragments.begin() ;
470 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
473 fragmentLength += (*it)->Length;
475 if (howManyRead > fragmentLength) continue;
477 (*it)->DecompressJPEGFragmentedFramesFromFile(buffer, Raw, BitsStored, howManyRead, howManyWritten, totalLength);
479 if (howManyRead < fragmentLength)
480 howManyRead = fragmentLength;
490 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
491 * file and decompress it.
492 * @param fp File Pointer
495 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
499 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
500 // if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
504 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
506 // we have one frame split into several fragments
507 // we will pack those fragments into a single buffer and
509 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
511 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
513 // suppose each fragment is a frame
514 return ReadAndDecompressJPEGFramesFromFile( fp );
518 // The dicom image contains frames containing fragments of images
519 // a more complex algorithm :-)
520 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
525 * \brief Re-arrange the bits within the bytes.
528 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
530 if ( BitsStored != BitsAllocated )
532 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
533 if ( BitsAllocated == 16 )
535 uint16_t mask = 0xffff;
536 mask = mask >> ( BitsAllocated - BitsStored );
537 uint16_t* deb = (uint16_t*)Raw;
538 for(int i = 0; i<l; i++)
540 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
544 else if ( BitsAllocated == 32 )
546 uint32_t mask = 0xffffffff;
547 mask = mask >> ( BitsAllocated - BitsStored );
548 uint32_t* deb = (uint32_t*)Raw;
549 for(int i = 0; i<l; i++)
551 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
557 gdcmVerboseMacro("Weird image");
558 throw FormatError( "Weird image !?" );
565 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
566 * \warning Works on all the frames at a time
568 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
570 uint8_t *localRaw = Raw;
571 uint8_t *copyRaw = new uint8_t[ RawSize ];
572 memmove( copyRaw, localRaw, RawSize );
574 // to see the tricks about YBR_FULL, YBR_FULL_422,
575 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
576 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
577 // and be *very* affraid
579 int l = XSize * YSize;
580 int nbFrames = ZSize;
582 uint8_t *a = copyRaw;
583 uint8_t *b = copyRaw + l;
584 uint8_t *c = copyRaw + l + l;
587 /// \todo : Replace by the 'well known' integer computation
588 /// counterpart. Refer to
589 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
590 /// for code optimisation.
592 for ( int i = 0; i < nbFrames; i++ )
594 for ( int j = 0; j < l; j++ )
596 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
597 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
598 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
600 if (R < 0.0) R = 0.0;
601 if (G < 0.0) G = 0.0;
602 if (B < 0.0) B = 0.0;
603 if (R > 255.0) R = 255.0;
604 if (G > 255.0) G = 255.0;
605 if (B > 255.0) B = 255.0;
607 *(localRaw++) = (uint8_t)R;
608 *(localRaw++) = (uint8_t)G;
609 *(localRaw++) = (uint8_t)B;
619 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
620 * \warning Works on all the frames at a time
622 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
624 uint8_t *localRaw = Raw;
625 uint8_t *copyRaw = new uint8_t[ RawSize ];
626 memmove( copyRaw, localRaw, RawSize );
628 int l = XSize * YSize * ZSize;
630 uint8_t* a = copyRaw;
631 uint8_t* b = copyRaw + l;
632 uint8_t* c = copyRaw + l + l;
634 for (int j = 0; j < l; j++)
636 *(localRaw++) = *(a++);
637 *(localRaw++) = *(b++);
638 *(localRaw++) = *(c++);
643 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
645 // ComputeRawAndRGBSizes is already made by
646 // ::GrabInformationsFromHeader. So, the structure sizes are
650 //////////////////////////////////////////////////
651 //// First stage: get our hands on the Pixel Data.
654 gdcmVerboseMacro( "Unavailable file pointer." );
658 fp->seekg( PixelOffset, std::ios::beg );
659 if( fp->fail() || fp->eof())
661 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
667 //////////////////////////////////////////////////
668 //// Second stage: read from disk dans decompress.
669 if ( BitsAllocated == 12 )
671 ReadAndDecompress12BitsTo16Bits( fp);
675 // This problem can be found when some obvious informations are found
676 // after the field containing the image datas. In this case, these
677 // bad datas are added to the size of the image (in the PixelDataLength
678 // variable). But RawSize is the right size of the image !
679 if( PixelDataLength != RawSize)
681 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
683 if( PixelDataLength > RawSize)
685 fp->read( (char*)Raw, RawSize);
689 fp->read( (char*)Raw, PixelDataLength);
692 if ( fp->fail() || fp->eof())
694 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
698 else if ( IsRLELossless )
700 if ( ! ReadAndDecompressRLEFile( fp ) )
702 gdcmVerboseMacro( "RLE decompressor failed." );
708 // Default case concerns JPEG family
709 if ( ! ReadAndDecompressJPEGFile( fp ) )
711 gdcmVerboseMacro( "JPEG decompressor failed." );
716 ////////////////////////////////////////////
717 //// Third stage: twigle the bytes and bits.
718 ConvertReorderEndianity();
719 ConvertReArrangeBits();
720 ConvertHandleColor();
725 void PixelReadConvert::ConvertHandleColor()
727 //////////////////////////////////
728 // Deal with the color decoding i.e. handle:
729 // - R, G, B planes (as opposed to RGB pixels)
730 // - YBR (various) encodings.
731 // - LUT[s] (or "PALETTE COLOR").
733 // The classification in the color decoding schema is based on the blending
734 // of two Dicom tags values:
735 // * "Photometric Interpretation" for which we have the cases:
736 // - [Photo A] MONOCHROME[1|2] pictures,
737 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
738 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
739 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
740 // * "Planar Configuration" for which we have the cases:
741 // - [Planar 0] 0 then Pixels are already RGB
742 // - [Planar 1] 1 then we have 3 planes : R, G, B,
743 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
745 // Now in theory, one could expect some coherence when blending the above
746 // cases. For example we should not encounter files belonging at the
747 // time to case [Planar 0] and case [Photo D].
748 // Alas, this was only theory ! Because in practice some odd (read ill
749 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
750 // - "Planar Configuration" = 0,
751 // - "Photometric Interpretation" = "PALETTE COLOR".
752 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
753 // towards Dicom-non-conformance files:
754 // << whatever the "Planar Configuration" value might be, a
755 // "Photometric Interpretation" set to "PALETTE COLOR" forces
756 // a LUT intervention >>
758 // Now we are left with the following handling of the cases:
759 // - [Planar 0] OR [Photo A] no color decoding (since respectively
760 // Pixels are already RGB and monochrome pictures have no color :),
761 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
762 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
763 // - [Planar 2] OR [Photo D] requires LUT intervention.
767 // [Planar 2] OR [Photo D]: LUT intervention done outside
771 if ( PlanarConfiguration == 1 )
775 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
776 ConvertYcBcRPlanesToRGBPixels();
780 // [Planar 1] AND [Photo C]
781 ConvertRGBPlanesToRGBPixels();
786 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
787 // pixels need to be RGB-fied anyway
790 ConvertRGBPlanesToRGBPixels();
792 // In *normal *case, when planarConf is 0, pixels are already in RGB
796 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
797 * \note See comments of \ref ConvertHandleColor
799 bool PixelReadConvert::IsRawRGB()
802 || PlanarConfiguration == 2
810 void PixelReadConvert::ComputeRawAndRGBSizes()
812 int bitsAllocated = BitsAllocated;
813 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
814 // in this case we will expand the image to 16 bits (see
815 // \ref ReadAndDecompress12BitsTo16Bits() )
816 if ( BitsAllocated == 12 )
821 RawSize = XSize * YSize * ZSize
822 * ( bitsAllocated / 8 )
826 RGBSize = 3 * RawSize;
834 void PixelReadConvert::GrabInformationsFromHeader( File *header )
836 // Number of Bits Allocated for storing a Pixel is defaulted to 16
837 // when absent from the header.
838 BitsAllocated = header->GetBitsAllocated();
839 if ( BitsAllocated == 0 )
844 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
845 // when absent from the header.
846 BitsStored = header->GetBitsStored();
847 if ( BitsStored == 0 )
849 BitsStored = BitsAllocated;
853 HighBitPosition = header->GetHighBitPosition();
854 if ( HighBitPosition == 0 )
856 HighBitPosition = BitsAllocated - 1;
859 XSize = header->GetXSize();
860 YSize = header->GetYSize();
861 ZSize = header->GetZSize();
862 SamplesPerPixel = header->GetSamplesPerPixel();
863 PixelSize = header->GetPixelSize();
864 PixelSign = header->IsSignedPixelData();
865 SwapCode = header->GetSwapCode();
866 std::string ts = header->GetTransferSyntax();
868 ( ! header->IsDicomV3() )
869 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
870 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
871 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
872 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
873 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
874 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
875 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
876 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
877 PixelOffset = header->GetPixelOffset();
878 PixelDataLength = header->GetPixelAreaLength();
879 RLEInfo = header->GetRLEInfo();
880 JPEGInfo = header->GetJPEGInfo();
882 PlanarConfiguration = header->GetPlanarConfiguration();
883 IsMonochrome = header->IsMonochrome();
884 IsPaletteColor = header->IsPaletteColor();
885 IsYBRFull = header->IsYBRFull();
887 /////////////////////////////////////////////////////////////////
889 HasLUT = header->HasLUT();
892 // Just in case some access to a File element requires disk access.
893 LutRedDescriptor = header->GetEntry( 0x0028, 0x1101 );
894 LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
895 LutBlueDescriptor = header->GetEntry( 0x0028, 0x1103 );
897 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
898 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
899 // Document::Document() ], the loading of the value (content) of a
900 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
901 // loaded). Hence, we first try to obtain the LUTs data from the file
902 // and when this fails we read the LUTs data directly from disk.
903 /// \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
904 /// We should NOT bypass the [Bin|Val]Entry class. Instead
905 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
906 /// (e.g. BinEntry::GetBinArea()) should force disk access from
907 /// within the [Bin|Val]Entry class itself. The only problem
908 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
909 /// parsed from. Fix that. FIXME.
912 header->LoadEntryBinArea(0x0028, 0x1201);
913 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
916 gdcmVerboseMacro( "Unable to read Red LUT data" );
920 header->LoadEntryBinArea(0x0028, 0x1202);
921 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
924 gdcmVerboseMacro( "Unable to read Green LUT data" );
928 header->LoadEntryBinArea(0x0028, 0x1203);
929 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
932 gdcmVerboseMacro( "Unable to read Blue LUT data" );
936 ComputeRawAndRGBSizes();
940 * \brief Build Red/Green/Blue/Alpha LUT from File
941 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
942 * and (0028,1101),(0028,1102),(0028,1102)
943 * - xxx Palette Color Lookup Table Descriptor - are found
944 * and (0028,1201),(0028,1202),(0028,1202)
945 * - xxx Palette Color Lookup Table Data - are found
946 * \warning does NOT deal with :
947 * 0028 1100 Gray Lookup Table Descriptor (Retired)
948 * 0028 1221 Segmented Red Palette Color Lookup Table Data
949 * 0028 1222 Segmented Green Palette Color Lookup Table Data
950 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
951 * no known Dicom reader deals with them :-(
952 * @return a RGBA Lookup Table
954 void PixelReadConvert::BuildLUTRGBA()
961 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
963 if ( ! IsPaletteColor )
968 if ( LutRedDescriptor == GDCM_UNFOUND
969 || LutGreenDescriptor == GDCM_UNFOUND
970 || LutBlueDescriptor == GDCM_UNFOUND )
975 ////////////////////////////////////////////
976 // Extract the info from the LUT descriptors
977 int lengthR; // Red LUT length in Bytes
978 int debR; // Subscript of the first Lut Value
979 int nbitsR; // Lut item size (in Bits)
980 int nbRead = sscanf( LutRedDescriptor.c_str(),
982 &lengthR, &debR, &nbitsR );
985 gdcmVerboseMacro( "Wrong Red LUT descriptor" );
988 int lengthG; // Green LUT length in Bytes
989 int debG; // Subscript of the first Lut Value
990 int nbitsG; // Lut item size (in Bits)
991 nbRead = sscanf( LutGreenDescriptor.c_str(),
993 &lengthG, &debG, &nbitsG );
996 gdcmVerboseMacro( "Wrong Green LUT descriptor" );
999 int lengthB; // Blue LUT length in Bytes
1000 int debB; // Subscript of the first Lut Value
1001 int nbitsB; // Lut item size (in Bits)
1002 nbRead = sscanf( LutRedDescriptor.c_str(),
1004 &lengthB, &debB, &nbitsB );
1007 gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
1010 ////////////////////////////////////////////////////////
1011 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1016 ////////////////////////////////////////////////
1017 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1018 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1023 memset( LutRGBA, 0, 1024 );
1026 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1028 // when LUT item size is different than pixel size
1029 mult = 2; // high byte must be = low byte
1033 // See PS 3.3-2003 C.11.1.1.2 p 619
1037 // if we get a black image, let's just remove the '+1'
1038 // from 'i*mult+1' and check again
1039 // if it works, we shall have to check the 3 Palettes
1040 // to see which byte is ==0 (first one, or second one)
1042 // We give up the checking to avoid some (useless ?) overhead
1043 // (optimistic asumption)
1045 uint8_t* a = LutRGBA + 0;
1046 for( i=0; i < lengthR; ++i )
1048 *a = LutRedData[i*mult+1];
1053 for( i=0; i < lengthG; ++i)
1055 *a = LutGreenData[i*mult+1];
1060 for(i=0; i < lengthB; ++i)
1062 *a = LutBlueData[i*mult+1];
1067 for(i=0; i < 256; ++i)
1069 *a = 1; // Alpha component
1075 * \brief Build the RGB image from the Raw imagage and the LUTs.
1077 bool PixelReadConvert::BuildRGBImage()
1081 // The job is already done.
1087 // The job can't be done
1094 // The job can't be done
1100 uint8_t* localRGB = RGB;
1101 for (size_t i = 0; i < RawSize; ++i )
1104 *localRGB++ = LutRGBA[j];
1105 *localRGB++ = LutRGBA[j+1];
1106 *localRGB++ = LutRGBA[j+2];
1112 * \brief Print self.
1113 * @param indent Indentation string to be prepended during printing.
1114 * @param os Stream to print to.
1116 void PixelReadConvert::Print( std::ostream &os, std::string const & indent )
1119 << "--- Pixel information -------------------------"
1122 << "Pixel Data: offset " << PixelOffset
1123 << " x(" << std::hex << PixelOffset << std::dec
1124 << ") length " << PixelDataLength
1125 << " x(" << std::hex << PixelDataLength << std::dec
1126 << ")" << std::endl;
1128 if ( IsRLELossless )
1132 RLEInfo->Print( os, indent );
1136 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1140 if ( IsJPEG2000 || IsJPEGLossless )
1144 JPEGInfo->Print( os, indent );
1148 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1153 } // end namespace gdcm
1155 // NOTES on File internal calls
1157 // ---> GetImageData
1158 // ---> GetImageDataIntoVector
1159 // |---> GetImageDataIntoVectorRaw
1160 // | lut intervention
1162 // ---> GetImageDataRaw
1163 // ---> GetImageDataIntoVectorRaw