1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/24 14:52:50 $
7 Version: $Revision: 1.33 $
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 decoded fragment
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 endianness 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;
411 JPEGInfo->DecompressJPEGFramesFromFile(fp, Raw, BitsStored, numberBytes, length );
416 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
417 * file and decompress it. This function assumes that the dicom
418 * image is a single frame split into several JPEG fragments.
419 * Those fragments will be glued together into a memory buffer
421 * @param fp File Pointer
424 bool PixelReadConvert::
425 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
427 // Loop on the fragment[s] to get total length
428 size_t totalLength = JPEGInfo->GetFragmentsLength();
430 // Concatenate the jpeg fragments into a local buffer
431 JOCTET *buffer = new JOCTET [totalLength];
432 // Fill in the buffer:
433 JPEGInfo->ReadAllFragments(fp, buffer);
436 JPEGFragmentsInfo::JPEGFragmentsList::const_iterator it = JPEGInfo->Fragments.begin();
437 (*it)->DecompressJPEGSingleFrameFragmentsFromFile(buffer, totalLength, Raw, BitsStored);
446 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
447 * file and decompress it. This function handles the generic
448 * and complex case where the DICOM contains several frames,
449 * and some of the frames are possibly split into several JPEG
451 * @param fp File Pointer
454 bool PixelReadConvert::
455 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
457 // Loop on the fragment[s] to get total length
458 size_t totalLength = JPEGInfo->GetFragmentsLength();
460 // Concatenate the jpeg fragments into a local buffer
461 JOCTET *buffer = new JOCTET [totalLength];
462 // Fill in the buffer:
463 JPEGInfo->ReadAllFragments(fp, buffer);
465 size_t howManyRead = 0;
466 size_t howManyWritten = 0;
467 size_t fragmentLength = 0;
469 JPEGFragmentsInfo::JPEGFragmentsList::const_iterator it;
470 for( it = JPEGInfo->Fragments.begin() ;
471 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
474 fragmentLength += (*it)->Length;
476 if (howManyRead > fragmentLength) continue;
478 (*it)->DecompressJPEGFragmentedFramesFromFile(buffer, Raw, BitsStored, howManyRead, howManyWritten, totalLength);
480 if (howManyRead < fragmentLength)
481 howManyRead = fragmentLength;
491 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
492 * file and decompress it.
493 * @param fp File Pointer
496 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
500 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
501 // if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
505 // if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
507 // // we have one frame split into several fragments
508 // // we will pack those fragments into a single buffer and
510 // return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
512 // else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
514 // suppose each fragment is a frame
515 return ReadAndDecompressJPEGFramesFromFile( fp );
519 // // The dicom image contains frames containing fragments of images
520 // // a more complex algorithm :-)
521 // return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
526 * \brief Re-arrange the bits within the bytes.
529 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
531 if ( BitsStored != BitsAllocated )
533 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
534 if ( BitsAllocated == 16 )
536 uint16_t mask = 0xffff;
537 mask = mask >> ( BitsAllocated - BitsStored );
538 uint16_t* deb = (uint16_t*)Raw;
539 for(int i = 0; i<l; i++)
541 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
545 else if ( BitsAllocated == 32 )
547 uint32_t mask = 0xffffffff;
548 mask = mask >> ( BitsAllocated - BitsStored );
549 uint32_t* deb = (uint32_t*)Raw;
550 for(int i = 0; i<l; i++)
552 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
558 gdcmVerboseMacro("Weird image");
559 throw FormatError( "Weird image !?" );
566 * \brief Convert (cY plane, cB plane, cR plane) to RGB pixels
567 * \warning Works on all the frames at a time
569 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
571 uint8_t *localRaw = Raw;
572 uint8_t *copyRaw = new uint8_t[ RawSize ];
573 memmove( copyRaw, localRaw, RawSize );
575 // to see the tricks about YBR_FULL, YBR_FULL_422,
576 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
577 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
578 // and be *very* affraid
580 int l = XSize * YSize;
581 int nbFrames = ZSize;
583 uint8_t *a = copyRaw;
584 uint8_t *b = copyRaw + l;
585 uint8_t *c = copyRaw + l + l;
588 /// \todo : Replace by the 'well known' integer computation
589 /// counterpart. Refer to
590 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
591 /// for code optimisation.
593 for ( int i = 0; i < nbFrames; i++ )
595 for ( int j = 0; j < l; j++ )
597 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
598 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
599 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
601 if (R < 0.0) R = 0.0;
602 if (G < 0.0) G = 0.0;
603 if (B < 0.0) B = 0.0;
604 if (R > 255.0) R = 255.0;
605 if (G > 255.0) G = 255.0;
606 if (B > 255.0) B = 255.0;
608 *(localRaw++) = (uint8_t)R;
609 *(localRaw++) = (uint8_t)G;
610 *(localRaw++) = (uint8_t)B;
620 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
621 * \warning Works on all the frames at a time
623 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
625 uint8_t *localRaw = Raw;
626 uint8_t *copyRaw = new uint8_t[ RawSize ];
627 memmove( copyRaw, localRaw, RawSize );
629 int l = XSize * YSize * ZSize;
631 uint8_t* a = copyRaw;
632 uint8_t* b = copyRaw + l;
633 uint8_t* c = copyRaw + l + l;
635 for (int j = 0; j < l; j++)
637 *(localRaw++) = *(a++);
638 *(localRaw++) = *(b++);
639 *(localRaw++) = *(c++);
644 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
646 // ComputeRawAndRGBSizes is already made by
647 // ::GrabInformationsFromHeader. So, the structure sizes are
651 //////////////////////////////////////////////////
652 //// First stage: get our hands on the Pixel Data.
655 gdcmVerboseMacro( "Unavailable file pointer." );
659 fp->seekg( PixelOffset, std::ios::beg );
660 if( fp->fail() || fp->eof())
662 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
668 //////////////////////////////////////////////////
669 //// Second stage: read from disk dans decompress.
670 if ( BitsAllocated == 12 )
672 ReadAndDecompress12BitsTo16Bits( fp);
676 // This problem can be found when some obvious informations are found
677 // after the field containing the image data. In this case, these
678 // bad data are added to the size of the image (in the PixelDataLength
679 // variable). But RawSize is the right size of the image !
680 if( PixelDataLength != RawSize)
682 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
684 if( PixelDataLength > RawSize)
686 fp->read( (char*)Raw, RawSize);
690 fp->read( (char*)Raw, PixelDataLength);
693 if ( fp->fail() || fp->eof())
695 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
699 else if ( IsRLELossless )
701 if ( ! ReadAndDecompressRLEFile( fp ) )
703 gdcmVerboseMacro( "RLE decompressor failed." );
709 // Default case concerns JPEG family
710 if ( ! ReadAndDecompressJPEGFile( fp ) )
712 gdcmVerboseMacro( "JPEG decompressor failed." );
717 ////////////////////////////////////////////
718 //// Third stage: twigle the bytes and bits.
719 ConvertReorderEndianity();
720 ConvertReArrangeBits();
721 ConvertHandleColor();
726 void PixelReadConvert::ConvertHandleColor()
728 //////////////////////////////////
729 // Deal with the color decoding i.e. handle:
730 // - R, G, B planes (as opposed to RGB pixels)
731 // - YBR (various) encodings.
732 // - LUT[s] (or "PALETTE COLOR").
734 // The classification in the color decoding schema is based on the blending
735 // of two Dicom tags values:
736 // * "Photometric Interpretation" for which we have the cases:
737 // - [Photo A] MONOCHROME[1|2] pictures,
738 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
739 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
740 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
741 // * "Planar Configuration" for which we have the cases:
742 // - [Planar 0] 0 then Pixels are already RGB
743 // - [Planar 1] 1 then we have 3 planes : R, G, B,
744 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
746 // Now in theory, one could expect some coherence when blending the above
747 // cases. For example we should not encounter files belonging at the
748 // time to case [Planar 0] and case [Photo D].
749 // Alas, this was only theory ! Because in practice some odd (read ill
750 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
751 // - "Planar Configuration" = 0,
752 // - "Photometric Interpretation" = "PALETTE COLOR".
753 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
754 // towards Dicom-non-conformance files:
755 // << whatever the "Planar Configuration" value might be, a
756 // "Photometric Interpretation" set to "PALETTE COLOR" forces
757 // a LUT intervention >>
759 // Now we are left with the following handling of the cases:
760 // - [Planar 0] OR [Photo A] no color decoding (since respectively
761 // Pixels are already RGB and monochrome pictures have no color :),
762 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
763 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
764 // - [Planar 2] OR [Photo D] requires LUT intervention.
768 // [Planar 2] OR [Photo D]: LUT intervention done outside
772 if ( PlanarConfiguration == 1 )
776 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
777 ConvertYcBcRPlanesToRGBPixels();
781 // [Planar 1] AND [Photo C]
782 ConvertRGBPlanesToRGBPixels();
787 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
788 // pixels need to be RGB-fied anyway
791 ConvertRGBPlanesToRGBPixels();
793 // In *normal *case, when planarConf is 0, pixels are already in RGB
797 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
798 * \note See comments of \ref ConvertHandleColor
800 bool PixelReadConvert::IsRawRGB()
803 || PlanarConfiguration == 2
811 void PixelReadConvert::ComputeRawAndRGBSizes()
813 int bitsAllocated = BitsAllocated;
814 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
815 // in this case we will expand the image to 16 bits (see
816 // \ref ReadAndDecompress12BitsTo16Bits() )
817 if ( BitsAllocated == 12 )
822 RawSize = XSize * YSize * ZSize
823 * ( bitsAllocated / 8 )
827 RGBSize = 3 * RawSize;
835 void PixelReadConvert::GrabInformationsFromHeader( File *header )
837 // Number of Bits Allocated for storing a Pixel is defaulted to 16
838 // when absent from the header.
839 BitsAllocated = header->GetBitsAllocated();
840 if ( BitsAllocated == 0 )
845 // Number of "Bits Stored", defaulted to number of "Bits Allocated"
846 // when absent from the header.
847 BitsStored = header->GetBitsStored();
848 if ( BitsStored == 0 )
850 BitsStored = BitsAllocated;
853 // High Bit Position, defaulted to "Bits Allocated" - 1
854 HighBitPosition = header->GetHighBitPosition();
855 if ( HighBitPosition == 0 )
857 HighBitPosition = BitsAllocated - 1;
860 XSize = header->GetXSize();
861 YSize = header->GetYSize();
862 ZSize = header->GetZSize();
863 SamplesPerPixel = header->GetSamplesPerPixel();
864 PixelSize = header->GetPixelSize();
865 PixelSign = header->IsSignedPixelData();
866 SwapCode = header->GetSwapCode();
867 std::string ts = header->GetTransferSyntax();
869 ( ! header->IsDicomV3() )
870 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
871 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
872 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
873 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
874 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
876 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
877 IsJPEGLS = Global::GetTS()->IsJPEGLS(ts);
878 IsJPEGLossy = Global::GetTS()->IsJPEGLossy(ts);
879 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
880 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
882 PixelOffset = header->GetPixelOffset();
883 PixelDataLength = header->GetPixelAreaLength();
884 RLEInfo = header->GetRLEInfo();
885 JPEGInfo = header->GetJPEGInfo();
887 PlanarConfiguration = header->GetPlanarConfiguration();
888 IsMonochrome = header->IsMonochrome();
889 IsPaletteColor = header->IsPaletteColor();
890 IsYBRFull = header->IsYBRFull();
892 /////////////////////////////////////////////////////////////////
894 HasLUT = header->HasLUT();
897 // Just in case some access to a File element requires disk access.
898 LutRedDescriptor = header->GetEntry( 0x0028, 0x1101 );
899 LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
900 LutBlueDescriptor = header->GetEntry( 0x0028, 0x1103 );
902 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
903 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
904 // Document::Document() ], the loading of the value (content) of a
905 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
906 // loaded). Hence, we first try to obtain the LUTs data from the file
907 // and when this fails we read the LUTs data directly from disk.
908 /// \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
909 /// We should NOT bypass the [Bin|Val]Entry class. Instead
910 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
911 /// (e.g. BinEntry::GetBinArea()) should force disk access from
912 /// within the [Bin|Val]Entry class itself. The only problem
913 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
914 /// parsed from. Fix that. FIXME.
917 header->LoadEntryBinArea(0x0028, 0x1201);
918 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
921 gdcmVerboseMacro( "Unable to read Red LUT data" );
925 header->LoadEntryBinArea(0x0028, 0x1202);
926 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
929 gdcmVerboseMacro( "Unable to read Green LUT data" );
933 header->LoadEntryBinArea(0x0028, 0x1203);
934 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
937 gdcmVerboseMacro( "Unable to read Blue LUT data" );
941 ComputeRawAndRGBSizes();
945 * \brief Build Red/Green/Blue/Alpha LUT from File
946 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
947 * and (0028,1101),(0028,1102),(0028,1102)
948 * - xxx Palette Color Lookup Table Descriptor - are found
949 * and (0028,1201),(0028,1202),(0028,1202)
950 * - xxx Palette Color Lookup Table Data - are found
951 * \warning does NOT deal with :
952 * 0028 1100 Gray Lookup Table Descriptor (Retired)
953 * 0028 1221 Segmented Red Palette Color Lookup Table Data
954 * 0028 1222 Segmented Green Palette Color Lookup Table Data
955 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
956 * no known Dicom reader deals with them :-(
957 * @return a RGBA Lookup Table
959 void PixelReadConvert::BuildLUTRGBA()
966 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
968 if ( ! IsPaletteColor )
973 if ( LutRedDescriptor == GDCM_UNFOUND
974 || LutGreenDescriptor == GDCM_UNFOUND
975 || LutBlueDescriptor == GDCM_UNFOUND )
980 ////////////////////////////////////////////
981 // Extract the info from the LUT descriptors
982 int lengthR; // Red LUT length in Bytes
983 int debR; // Subscript of the first Lut Value
984 int nbitsR; // Lut item size (in Bits)
985 int nbRead = sscanf( LutRedDescriptor.c_str(),
987 &lengthR, &debR, &nbitsR );
990 gdcmVerboseMacro( "Wrong Red LUT descriptor" );
993 int lengthG; // Green LUT length in Bytes
994 int debG; // Subscript of the first Lut Value
995 int nbitsG; // Lut item size (in Bits)
996 nbRead = sscanf( LutGreenDescriptor.c_str(),
998 &lengthG, &debG, &nbitsG );
1001 gdcmVerboseMacro( "Wrong Green LUT descriptor" );
1004 int lengthB; // Blue LUT length in Bytes
1005 int debB; // Subscript of the first Lut Value
1006 int nbitsB; // Lut item size (in Bits)
1007 nbRead = sscanf( LutRedDescriptor.c_str(),
1009 &lengthB, &debB, &nbitsB );
1012 gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
1015 ////////////////////////////////////////////////////////
1016 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1021 ////////////////////////////////////////////////
1022 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1023 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1028 memset( LutRGBA, 0, 1024 );
1031 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1033 // when LUT item size is different than pixel size
1034 mult = 2; // high byte must be = low byte
1038 // See PS 3.3-2003 C.11.1.1.2 p 619
1042 // if we get a black image, let's just remove the '+1'
1043 // from 'i*mult+1' and check again
1044 // if it works, we shall have to check the 3 Palettes
1045 // to see which byte is ==0 (first one, or second one)
1047 // We give up the checking to avoid some (useless ?) overhead
1048 // (optimistic asumption)
1050 uint8_t* a = LutRGBA + 0;
1051 for( i=0; i < lengthR; ++i )
1053 *a = LutRedData[i*mult+1];
1058 for( i=0; i < lengthG; ++i)
1060 *a = LutGreenData[i*mult+1];
1065 for(i=0; i < lengthB; ++i)
1067 *a = LutBlueData[i*mult+1];
1072 for(i=0; i < 256; ++i)
1074 *a = 1; // Alpha component
1080 * \brief Build the RGB image from the Raw imagage and the LUTs.
1082 bool PixelReadConvert::BuildRGBImage()
1086 // The job is already done.
1092 // The job can't be done
1099 // The job can't be done
1105 uint8_t* localRGB = RGB;
1106 for (size_t i = 0; i < RawSize; ++i )
1109 *localRGB++ = LutRGBA[j];
1110 *localRGB++ = LutRGBA[j+1];
1111 *localRGB++ = LutRGBA[j+2];
1117 * \brief Print self.
1118 * @param indent Indentation string to be prepended during printing.
1119 * @param os Stream to print to.
1121 void PixelReadConvert::Print( std::ostream &os, std::string const & indent )
1124 << "--- Pixel information -------------------------"
1127 << "Pixel Data: offset " << PixelOffset
1128 << " x(" << std::hex << PixelOffset << std::dec
1129 << ") length " << PixelDataLength
1130 << " x(" << std::hex << PixelDataLength << std::dec
1131 << ")" << std::endl;
1133 if ( IsRLELossless )
1137 RLEInfo->Print( os, indent );
1141 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1145 if ( IsJPEG2000 || IsJPEGLossless || IsJPEGLossy || IsJPEGLS )
1149 JPEGInfo->Print( os, indent );
1153 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1158 } // end namespace gdcm
1160 // NOTES on File internal calls
1162 // ---> GetImageData
1163 // ---> GetImageDataIntoVector
1164 // |---> GetImageDataIntoVectorRaw
1165 // | lut intervention
1167 // ---> GetImageDataRaw
1168 // ---> GetImageDataIntoVectorRaw