1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/17 03:05:55 $
7 Version: $Revision: 1.30 $
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 "gdcmGlobal.h"
29 #include "gdcmPixelReadConvert.h"
30 #include "gdcmDocEntry.h"
31 #include "gdcmRLEFramesInfo.h"
32 #include "gdcmJPEGFragmentsInfo.h"
35 #include <stdio.h> //for sscanf
39 #define str2num(str, typeNum) *((typeNum *)(str))
42 //-----------------------------------------------------------------------------
43 // Constructor / Destructor
44 PixelReadConvert::PixelReadConvert()
56 void PixelReadConvert::Squeeze()
77 PixelReadConvert::~PixelReadConvert()
82 void PixelReadConvert::AllocateRGB()
87 RGB = new uint8_t[ RGBSize ];
90 void PixelReadConvert::AllocateRaw()
95 Raw = new uint8_t[ RawSize ];
99 * \brief Read from file a 12 bits per pixel image and decompress it
100 * into a 16 bits per pixel image.
102 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
103 throw ( FormatError )
105 int nbPixels = XSize * YSize;
106 uint16_t* localDecompres = (uint16_t*)Raw;
108 for( int p = 0; p < nbPixels; p += 2 )
112 fp->read( (char*)&b0, 1);
113 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
115 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
116 "Unfound first block" );
119 fp->read( (char*)&b1, 1 );
120 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
122 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
123 "Unfound second block" );
126 fp->read( (char*)&b2, 1 );
127 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
129 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
130 "Unfound second block" );
133 // Two steps are necessary to please VC++
135 // 2 pixels 12bit = [0xABCDEF]
136 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
138 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
140 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
142 /// \todo JPR Troubles expected on Big-Endian processors ?
147 * \brief Try to deal with RLE 16 Bits.
148 * We assume the RLE has already been parsed and loaded in
149 * Raw (through \ref ReadAndDecompressJPEGFile ).
150 * We here need to make 16 Bits Pixels from Low Byte and
151 * High Byte 'Planes'...(for what it may mean)
154 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
156 size_t pixelNumber = XSize * YSize;
157 size_t rawSize = XSize * YSize * NumberOfFrames;
159 // We assumed Raw contains the decoded RLE pixels but as
160 // 8 bits per pixel. In order to convert those pixels to 16 bits
161 // per pixel we cannot work in place within Raw and hence
162 // we copy it in a safe place, say copyRaw.
164 uint8_t* copyRaw = new uint8_t[ rawSize * 2 ];
165 memmove( copyRaw, Raw, rawSize * 2 );
168 uint8_t* a = copyRaw;
169 uint8_t* b = a + pixelNumber;
171 for ( int i = 0; i < NumberOfFrames; i++ )
173 for ( unsigned int j = 0; j < pixelNumber; j++ )
182 /// \todo check that operator new []didn't fail, and sometimes return false
187 * \brief Implementation of the RLE decoding algorithm for decompressing
188 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
189 * @param subRaw Sub region of \ref Raw where the de
190 * decoded fragment should be placed.
191 * @param fragmentSize The length of the binary fragment as found on the disk.
192 * @param RawSegmentSize The expected length of the fragment ONCE
194 * @param fp File Pointer: on entry the position should be the one of
195 * the fragment to be decoded.
197 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t *subRaw,
203 long numberOfOutputBytes = 0;
204 long numberOfReadBytes = 0;
206 while( numberOfOutputBytes < RawSegmentSize )
208 fp->read( (char*)&count, 1 );
209 numberOfReadBytes += 1;
211 // Note: count <= 127 comparison is always true due to limited range
212 // of data type int8_t [since the maximum of an exact width
213 // signed integer of width N is 2^(N-1) - 1, which for int8_t
216 fp->read( (char*)subRaw, count + 1);
217 numberOfReadBytes += count + 1;
219 numberOfOutputBytes += count + 1;
223 if ( ( count <= -1 ) && ( count >= -127 ) )
226 fp->read( (char*)&newByte, 1);
227 numberOfReadBytes += 1;
228 for( int i = 0; i < -count + 1; i++ )
232 subRaw += -count + 1;
233 numberOfOutputBytes += -count + 1;
236 // if count = 128 output nothing
238 if ( numberOfReadBytes > fragmentSize )
240 gdcmVerboseMacro( "Read more bytes than the segment size.");
248 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
249 * Dicom encapsulated file and decompress it.
250 * @param fp already open File Pointer
251 * at which the pixel data should be copied
254 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream *fp )
256 uint8_t *subRaw = Raw;
257 long RawSegmentSize = XSize * YSize;
259 // Loop on the frame[s]
260 for( RLEFramesInfo::RLEFrameList::iterator
261 it = RLEInfo->Frames.begin();
262 it != RLEInfo->Frames.end();
265 // Loop on the fragments
266 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
268 fp->seekg( (*it)->Offset[k] , std::ios::beg );
269 (void)ReadAndDecompressRLEFragment( subRaw,
273 subRaw += RawSegmentSize;
277 if ( BitsAllocated == 16 )
279 // Try to deal with RLE 16 Bits
280 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
287 * \brief Swap the bytes, according to \ref SwapCode.
289 void PixelReadConvert::ConvertSwapZone()
293 if( BitsAllocated == 16 )
295 uint16_t *im16 = (uint16_t*)Raw;
303 for( i = 0; i < RawSize / 2; i++ )
305 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
309 gdcmVerboseMacro("SwapCode value (16 bits) not allowed.");
312 else if( BitsAllocated == 32 )
317 uint32_t* im32 = (uint32_t*)Raw;
323 for( i = 0; i < RawSize / 4; i++ )
325 low = im32[i] & 0x0000ffff; // 4321
326 high = im32[i] >> 16;
327 high = ( high >> 8 ) | ( high << 8 );
328 low = ( low >> 8 ) | ( low << 8 );
330 im32[i] = ( s32 << 16 ) | high;
334 for( i = 0; i < RawSize / 4; i++ )
336 low = im32[i] & 0x0000ffff; // 2143
337 high = im32[i] >> 16;
338 high = ( high >> 8 ) | ( high << 8 );
339 low = ( low >> 8 ) | ( low << 8 );
341 im32[i] = ( s32 << 16 ) | low;
345 for( i = 0; i < RawSize / 4; i++ )
347 low = im32[i] & 0x0000ffff; // 3412
348 high = im32[i] >> 16;
350 im32[i] = ( s32 << 16 ) | high;
354 gdcmVerboseMacro("SwapCode value (32 bits) not allowed." );
360 * \brief Deal with endianity i.e. re-arange bytes inside the integer
362 void PixelReadConvert::ConvertReorderEndianity()
364 if ( BitsAllocated != 8 )
369 // Special kludge in order to deal with xmedcon broken images:
370 if ( BitsAllocated == 16
371 && BitsStored < BitsAllocated
374 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
375 uint16_t *deb = (uint16_t *)Raw;
376 for(int i = 0; i<l; i++)
389 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
390 * file and decompress it. This function assumes that each
391 * jpeg fragment contains a whole frame (jpeg file).
392 * @param fp File Pointer
395 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream *fp )
397 // Pointer to the Raw image
398 uint8_t *localRaw = Raw;
400 // Precompute the offset localRaw will be shifted with
401 int length = XSize * YSize * SamplesPerPixel;
402 int numberBytes = BitsAllocated / 8;
404 // Loop on the fragment[s]
405 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
406 it = JPEGInfo->Fragments.begin();
407 it != JPEGInfo->Fragments.end();
410 (*it)->DecompressJPEGFramesFromFile(fp, localRaw, BitsStored );
412 // Advance to next free location in Raw
413 // for next fragment decompression (if any)
415 localRaw += length * numberBytes;
421 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
422 * file and decompress it. This function assumes that the dicom
423 * image is a single frame split into several JPEG fragments.
424 * Those fragments will be glued together into a memory buffer
426 * @param fp File Pointer
429 bool PixelReadConvert::
430 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
432 // Loop on the fragment[s] to get total length
433 size_t totalLength = JPEGInfo->GetFragmentsLength();
435 // Concatenate the jpeg fragments into a local buffer
436 JOCTET *buffer = new JOCTET [totalLength];
437 // Fill in the buffer:
438 JPEGInfo->ReadAllFragments(fp, buffer);
441 JPEGFragmentsInfo::JPEGFragmentsList::const_iterator it = JPEGInfo->Fragments.begin();
442 (*it)->DecompressJPEGSingleFrameFragmentsFromFile(buffer, totalLength, Raw, BitsStored);
451 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
452 * file and decompress it. This function handles the generic
453 * and complex case where the DICOM contains several frames,
454 * and some of the frames are possibly split into several JPEG
456 * @param fp File Pointer
459 bool PixelReadConvert::
460 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
462 // Loop on the fragment[s] to get total length
463 size_t totalLength = JPEGInfo->GetFragmentsLength();
465 // Concatenate the jpeg fragments into a local buffer
466 JOCTET *buffer = new JOCTET [totalLength];
467 // Fill in the buffer:
468 JPEGInfo->ReadAllFragments(fp, buffer);
470 size_t howManyRead = 0;
471 size_t howManyWritten = 0;
472 size_t fragmentLength = 0;
474 JPEGFragmentsInfo::JPEGFragmentsList::const_iterator it;
475 for( it = JPEGInfo->Fragments.begin() ;
476 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
479 fragmentLength += (*it)->Length;
481 if (howManyRead > fragmentLength) continue;
483 (*it)->DecompressJPEGFragmentedFramesFromFile(buffer, Raw, BitsStored, howManyRead, howManyWritten, totalLength);
485 if (howManyRead < fragmentLength)
486 howManyRead = fragmentLength;
496 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
497 * file and decompress it.
498 * @param fp File Pointer
501 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
505 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
506 // if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
510 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
512 // we have one frame split into several fragments
513 // we will pack those fragments into a single buffer and
515 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
517 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
519 // suppose each fragment is a frame
520 return ReadAndDecompressJPEGFramesFromFile( fp );
524 // The dicom image contains frames containing fragments of images
525 // a more complex algorithm :-)
526 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
531 * \brief Re-arrange the bits within the bytes.
534 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
536 if ( BitsStored != BitsAllocated )
538 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
539 if ( BitsAllocated == 16 )
541 uint16_t mask = 0xffff;
542 mask = mask >> ( BitsAllocated - BitsStored );
543 uint16_t* deb = (uint16_t*)Raw;
544 for(int i = 0; i<l; i++)
546 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
550 else if ( BitsAllocated == 32 )
552 uint32_t mask = 0xffffffff;
553 mask = mask >> ( BitsAllocated - BitsStored );
554 uint32_t* deb = (uint32_t*)Raw;
555 for(int i = 0; i<l; i++)
557 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
563 gdcmVerboseMacro("Weird image");
564 throw FormatError( "Weird image !?" );
571 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
572 * \warning Works on all the frames at a time
574 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
576 uint8_t *localRaw = Raw;
577 uint8_t *copyRaw = new uint8_t[ RawSize ];
578 memmove( copyRaw, localRaw, RawSize );
580 // to see the tricks about YBR_FULL, YBR_FULL_422,
581 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
582 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
583 // and be *very* affraid
585 int l = XSize * YSize;
586 int nbFrames = ZSize;
588 uint8_t *a = copyRaw;
589 uint8_t *b = copyRaw + l;
590 uint8_t *c = copyRaw + l + l;
593 /// \todo : Replace by the 'well known' integer computation
594 /// counterpart. Refer to
595 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
596 /// for code optimisation.
598 for ( int i = 0; i < nbFrames; i++ )
600 for ( int j = 0; j < l; j++ )
602 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
603 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
604 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
606 if (R < 0.0) R = 0.0;
607 if (G < 0.0) G = 0.0;
608 if (B < 0.0) B = 0.0;
609 if (R > 255.0) R = 255.0;
610 if (G > 255.0) G = 255.0;
611 if (B > 255.0) B = 255.0;
613 *(localRaw++) = (uint8_t)R;
614 *(localRaw++) = (uint8_t)G;
615 *(localRaw++) = (uint8_t)B;
625 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
626 * \warning Works on all the frames at a time
628 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
630 uint8_t *localRaw = Raw;
631 uint8_t *copyRaw = new uint8_t[ RawSize ];
632 memmove( copyRaw, localRaw, RawSize );
634 int l = XSize * YSize * ZSize;
636 uint8_t* a = copyRaw;
637 uint8_t* b = copyRaw + l;
638 uint8_t* c = copyRaw + l + l;
640 for (int j = 0; j < l; j++)
642 *(localRaw++) = *(a++);
643 *(localRaw++) = *(b++);
644 *(localRaw++) = *(c++);
649 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
651 // ComputeRawAndRGBSizes is already made by
652 // ::GrabInformationsFromHeader. So, the structure sizes are
656 //////////////////////////////////////////////////
657 //// First stage: get our hands on the Pixel Data.
660 gdcmVerboseMacro( "Unavailable file pointer." );
664 fp->seekg( PixelOffset, std::ios::beg );
665 if( fp->fail() || fp->eof())
667 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
673 //////////////////////////////////////////////////
674 //// Second stage: read from disk dans decompress.
675 if ( BitsAllocated == 12 )
677 ReadAndDecompress12BitsTo16Bits( fp);
681 // This problem can be found when some obvious informations are found
682 // after the field containing the image datas. In this case, these
683 // bad datas are added to the size of the image (in the PixelDataLength
684 // variable). But RawSize is the right size of the image !
685 if( PixelDataLength != RawSize)
687 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
689 if( PixelDataLength > RawSize)
691 fp->read( (char*)Raw, RawSize);
695 fp->read( (char*)Raw, PixelDataLength);
698 if ( fp->fail() || fp->eof())
700 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
704 else if ( IsRLELossless )
706 if ( ! ReadAndDecompressRLEFile( fp ) )
708 gdcmVerboseMacro( "RLE decompressor failed." );
714 // Default case concerns JPEG family
715 if ( ! ReadAndDecompressJPEGFile( fp ) )
717 gdcmVerboseMacro( "JPEG decompressor failed." );
722 ////////////////////////////////////////////
723 //// Third stage: twigle the bytes and bits.
724 ConvertReorderEndianity();
725 ConvertReArrangeBits();
726 ConvertHandleColor();
731 void PixelReadConvert::ConvertHandleColor()
733 //////////////////////////////////
734 // Deal with the color decoding i.e. handle:
735 // - R, G, B planes (as opposed to RGB pixels)
736 // - YBR (various) encodings.
737 // - LUT[s] (or "PALETTE COLOR").
739 // The classification in the color decoding schema is based on the blending
740 // of two Dicom tags values:
741 // * "Photometric Interpretation" for which we have the cases:
742 // - [Photo A] MONOCHROME[1|2] pictures,
743 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
744 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
745 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
746 // * "Planar Configuration" for which we have the cases:
747 // - [Planar 0] 0 then Pixels are already RGB
748 // - [Planar 1] 1 then we have 3 planes : R, G, B,
749 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
751 // Now in theory, one could expect some coherence when blending the above
752 // cases. For example we should not encounter files belonging at the
753 // time to case [Planar 0] and case [Photo D].
754 // Alas, this was only theory ! Because in practice some odd (read ill
755 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
756 // - "Planar Configuration" = 0,
757 // - "Photometric Interpretation" = "PALETTE COLOR".
758 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
759 // towards Dicom-non-conformance files:
760 // << whatever the "Planar Configuration" value might be, a
761 // "Photometric Interpretation" set to "PALETTE COLOR" forces
762 // a LUT intervention >>
764 // Now we are left with the following handling of the cases:
765 // - [Planar 0] OR [Photo A] no color decoding (since respectively
766 // Pixels are already RGB and monochrome pictures have no color :),
767 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
768 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
769 // - [Planar 2] OR [Photo D] requires LUT intervention.
773 // [Planar 2] OR [Photo D]: LUT intervention done outside
777 if ( PlanarConfiguration == 1 )
781 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
782 ConvertYcBcRPlanesToRGBPixels();
786 // [Planar 1] AND [Photo C]
787 ConvertRGBPlanesToRGBPixels();
792 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
793 // pixels need to be RGB-fied anyway
796 ConvertRGBPlanesToRGBPixels();
798 // In *normal *case, when planarConf is 0, pixels are already in RGB
802 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
803 * \note See comments of \ref ConvertHandleColor
805 bool PixelReadConvert::IsRawRGB()
808 || PlanarConfiguration == 2
816 void PixelReadConvert::ComputeRawAndRGBSizes()
818 int bitsAllocated = BitsAllocated;
819 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
820 // in this case we will expand the image to 16 bits (see
821 // \ref ReadAndDecompress12BitsTo16Bits() )
822 if ( BitsAllocated == 12 )
827 RawSize = XSize * YSize * ZSize
828 * ( bitsAllocated / 8 )
832 RGBSize = 3 * RawSize;
840 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
842 // Number of Bits Allocated for storing a Pixel is defaulted to 16
843 // when absent from the header.
844 BitsAllocated = header->GetBitsAllocated();
845 if ( BitsAllocated == 0 )
850 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
851 // when absent from the header.
852 BitsStored = header->GetBitsStored();
853 if ( BitsStored == 0 )
855 BitsStored = BitsAllocated;
859 HighBitPosition = header->GetHighBitPosition();
860 if ( HighBitPosition == 0 )
862 HighBitPosition = BitsAllocated - 1;
865 XSize = header->GetXSize();
866 YSize = header->GetYSize();
867 ZSize = header->GetZSize();
868 SamplesPerPixel = header->GetSamplesPerPixel();
869 PixelSize = header->GetPixelSize();
870 PixelSign = header->IsSignedPixelData();
871 SwapCode = header->GetSwapCode();
872 std::string ts = header->GetTransferSyntax();
874 ( ! header->IsDicomV3() )
875 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
876 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
877 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
878 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
879 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
880 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
881 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
882 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
883 PixelOffset = header->GetPixelOffset();
884 PixelDataLength = header->GetPixelAreaLength();
885 RLEInfo = header->GetRLEInfo();
886 JPEGInfo = header->GetJPEGInfo();
888 PlanarConfiguration = header->GetPlanarConfiguration();
889 IsMonochrome = header->IsMonochrome();
890 IsPaletteColor = header->IsPaletteColor();
891 IsYBRFull = header->IsYBRFull();
893 /////////////////////////////////////////////////////////////////
895 HasLUT = header->HasLUT();
898 // Just in case some access to a Header element requires disk access.
899 LutRedDescriptor = header->GetEntry( 0x0028, 0x1101 );
900 LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
901 LutBlueDescriptor = header->GetEntry( 0x0028, 0x1103 );
903 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
904 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
905 // Document::Document() ], the loading of the value (content) of a
906 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
907 // loaded). Hence, we first try to obtain the LUTs data from the header
908 // and when this fails we read the LUTs data directely from disk.
909 /// \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
910 /// We should NOT bypass the [Bin|Val]Entry class. Instead
911 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
912 /// (e.g. BinEntry::GetBinArea()) should force disk access from
913 /// within the [Bin|Val]Entry class itself. The only problem
914 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
915 /// parsed from. Fix that. FIXME.
918 header->LoadEntryBinArea(0x0028, 0x1201);
919 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
922 gdcmVerboseMacro( "Unable to read Red LUT data" );
926 header->LoadEntryBinArea(0x0028, 0x1202);
927 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
930 gdcmVerboseMacro( "Unable to read Green LUT data" );
934 header->LoadEntryBinArea(0x0028, 0x1203);
935 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
938 gdcmVerboseMacro( "Unable to read Blue LUT data" );
942 ComputeRawAndRGBSizes();
946 * \brief Build Red/Green/Blue/Alpha LUT from Header
947 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
948 * and (0028,1101),(0028,1102),(0028,1102)
949 * - xxx Palette Color Lookup Table Descriptor - are found
950 * and (0028,1201),(0028,1202),(0028,1202)
951 * - xxx Palette Color Lookup Table Data - are found
952 * \warning does NOT deal with :
953 * 0028 1100 Gray Lookup Table Descriptor (Retired)
954 * 0028 1221 Segmented Red Palette Color Lookup Table Data
955 * 0028 1222 Segmented Green Palette Color Lookup Table Data
956 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
957 * no known Dicom reader deals with them :-(
958 * @return a RGBA Lookup Table
960 void PixelReadConvert::BuildLUTRGBA()
967 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
969 if ( ! IsPaletteColor )
974 if ( LutRedDescriptor == GDCM_UNFOUND
975 || LutGreenDescriptor == GDCM_UNFOUND
976 || LutBlueDescriptor == GDCM_UNFOUND )
981 ////////////////////////////////////////////
982 // Extract the info from the LUT descriptors
983 int lengthR; // Red LUT length in Bytes
984 int debR; // Subscript of the first Lut Value
985 int nbitsR; // Lut item size (in Bits)
986 int nbRead = sscanf( LutRedDescriptor.c_str(),
988 &lengthR, &debR, &nbitsR );
991 gdcmVerboseMacro( "Wrong Red LUT descriptor" );
994 int lengthG; // Green LUT length in Bytes
995 int debG; // Subscript of the first Lut Value
996 int nbitsG; // Lut item size (in Bits)
997 nbRead = sscanf( LutGreenDescriptor.c_str(),
999 &lengthG, &debG, &nbitsG );
1002 gdcmVerboseMacro( "Wrong Green LUT descriptor" );
1005 int lengthB; // Blue LUT length in Bytes
1006 int debB; // Subscript of the first Lut Value
1007 int nbitsB; // Lut item size (in Bits)
1008 nbRead = sscanf( LutRedDescriptor.c_str(),
1010 &lengthB, &debB, &nbitsB );
1013 gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
1016 ////////////////////////////////////////////////////////
1017 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1022 ////////////////////////////////////////////////
1023 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1024 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1029 memset( LutRGBA, 0, 1024 );
1032 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1034 // when LUT item size is different than pixel size
1035 mult = 2; // high byte must be = low byte
1039 // See PS 3.3-2003 C.11.1.1.2 p 619
1043 // if we get a black image, let's just remove the '+1'
1044 // from 'i*mult+1' and check again
1045 // if it works, we shall have to check the 3 Palettes
1046 // to see which byte is ==0 (first one, or second one)
1048 // We give up the checking to avoid some (useless ?) overhead
1049 // (optimistic asumption)
1051 uint8_t* a = LutRGBA + 0;
1052 for( i=0; i < lengthR; ++i )
1054 *a = LutRedData[i*mult+1];
1059 for( i=0; i < lengthG; ++i)
1061 *a = LutGreenData[i*mult+1];
1066 for(i=0; i < lengthB; ++i)
1068 *a = LutBlueData[i*mult+1];
1073 for(i=0; i < 256; ++i)
1075 *a = 1; // Alpha component
1081 * \brief Build the RGB image from the Raw imagage and the LUTs.
1083 bool PixelReadConvert::BuildRGBImage()
1087 // The job is already done.
1093 // The job can't be done
1100 // The job can't be done
1106 uint8_t* localRGB = RGB;
1107 for (size_t i = 0; i < RawSize; ++i )
1110 *localRGB++ = LutRGBA[j];
1111 *localRGB++ = LutRGBA[j+1];
1112 *localRGB++ = LutRGBA[j+2];
1118 * \brief Print self.
1119 * @param indent Indentation string to be prepended during printing.
1120 * @param os Stream to print to.
1122 void PixelReadConvert::Print( std::ostream &os, std::string const & indent )
1125 << "--- Pixel information -------------------------"
1128 << "Pixel Data: offset " << PixelOffset
1129 << " x(" << std::hex << PixelOffset << std::dec
1130 << ") length " << PixelDataLength
1131 << " x(" << std::hex << PixelDataLength << std::dec
1132 << ")" << std::endl;
1134 if ( IsRLELossless )
1138 RLEInfo->Print( os, indent );
1142 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1146 if ( IsJPEG2000 || IsJPEGLossless )
1150 JPEGInfo->Print( os, indent );
1154 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1159 } // end namespace gdcm
1161 // NOTES on File internal calls
1163 // ---> GetImageData
1164 // ---> GetImageDataIntoVector
1165 // |---> GetImageDataIntoVectorRaw
1166 // | lut intervention
1168 // ---> GetImageDataRaw
1169 // ---> GetImageDataIntoVectorRaw