1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/17 01:14:33 $
7 Version: $Revision: 1.29 $
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 uint8_t *localRaw = Raw;
398 // Loop on the fragment[s]
399 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
400 it = JPEGInfo->Fragments.begin();
401 it != JPEGInfo->Fragments.end();
404 fp->seekg( (*it)->Offset, std::ios::beg);
406 (*it)->DecompressJPEGFramesFromFile(fp, localRaw, BitsStored );
408 // Advance to next free location in Raw
409 // for next fragment decompression (if any)
410 int length = XSize * YSize * SamplesPerPixel;
411 int numberBytes = BitsAllocated / 8;
413 localRaw += length * numberBytes;
419 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
420 * file and decompress it. This function assumes that the dicom
421 * image is a single frame split into several JPEG fragments.
422 * Those fragments will be glued together into a memory buffer
424 * @param fp File Pointer
427 bool PixelReadConvert::
428 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
430 // Loop on the fragment[s] to get total length
431 size_t totalLength = 0;
432 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
433 for( it = JPEGInfo->Fragments.begin();
434 it != JPEGInfo->Fragments.end();
437 totalLength += (*it)->Length;
440 // Concatenate the jpeg fragments into a local buffer
441 JOCTET *buffer = new JOCTET [totalLength];
444 // Loop on the fragment[s]
445 for( it = JPEGInfo->Fragments.begin();
446 it != JPEGInfo->Fragments.end();
449 fp->seekg( (*it)->Offset, std::ios::beg);
450 size_t len = (*it)->Length;
451 fp->read((char *)p,len);
455 (*it)->DecompressJPEGSingleFrameFragmentsFromFile(buffer, totalLength, Raw, BitsStored);
464 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
465 * file and decompress it. This function handles the generic
466 * and complex case where the DICOM contains several frames,
467 * and some of the frames are possibly split into several JPEG
469 * @param fp File Pointer
472 bool PixelReadConvert::
473 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
475 // Loop on the fragment[s] to get total length
476 size_t totalLength = 0;
477 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
478 for( it = JPEGInfo->Fragments.begin();
479 it != JPEGInfo->Fragments.end();
482 totalLength += (*it)->Length;
485 // Concatenate the jpeg fragments into a local buffer
486 JOCTET *buffer = new JOCTET [totalLength];
489 // Loop on the fragment[s]
490 for( it = JPEGInfo->Fragments.begin();
491 it != JPEGInfo->Fragments.end();
494 fp->seekg( (*it)->Offset, std::ios::beg);
495 size_t len = (*it)->Length;
496 fp->read((char *)p,len);
500 size_t howManyRead = 0;
501 size_t howManyWritten = 0;
502 size_t fragmentLength = 0;
504 for( it = JPEGInfo->Fragments.begin() ;
505 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
508 fragmentLength += (*it)->Length;
510 if (howManyRead > fragmentLength) continue;
512 (*it)->DecompressJPEGFragmentedFramesFromFile(buffer, Raw, BitsStored, howManyRead, howManyWritten, totalLength);
514 if (howManyRead < fragmentLength)
515 howManyRead = fragmentLength;
525 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
526 * file and decompress it.
527 * @param fp File Pointer
530 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
534 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
535 // if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
539 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
541 // we have one frame split into several fragments
542 // we will pack those fragments into a single buffer and
544 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
546 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
548 // suppose each fragment is a frame
549 return ReadAndDecompressJPEGFramesFromFile( fp );
553 // The dicom image contains frames containing fragments of images
554 // a more complex algorithm :-)
555 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
560 * \brief Re-arrange the bits within the bytes.
563 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
565 if ( BitsStored != BitsAllocated )
567 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
568 if ( BitsAllocated == 16 )
570 uint16_t mask = 0xffff;
571 mask = mask >> ( BitsAllocated - BitsStored );
572 uint16_t* deb = (uint16_t*)Raw;
573 for(int i = 0; i<l; i++)
575 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
579 else if ( BitsAllocated == 32 )
581 uint32_t mask = 0xffffffff;
582 mask = mask >> ( BitsAllocated - BitsStored );
583 uint32_t* deb = (uint32_t*)Raw;
584 for(int i = 0; i<l; i++)
586 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
592 gdcmVerboseMacro("Weird image");
593 throw FormatError( "Weird image !?" );
600 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
601 * \warning Works on all the frames at a time
603 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
605 uint8_t *localRaw = Raw;
606 uint8_t *copyRaw = new uint8_t[ RawSize ];
607 memmove( copyRaw, localRaw, RawSize );
609 // to see the tricks about YBR_FULL, YBR_FULL_422,
610 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
611 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
612 // and be *very* affraid
614 int l = XSize * YSize;
615 int nbFrames = ZSize;
617 uint8_t *a = copyRaw;
618 uint8_t *b = copyRaw + l;
619 uint8_t *c = copyRaw + l + l;
622 /// \todo : Replace by the 'well known' integer computation
623 /// counterpart. Refer to
624 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
625 /// for code optimisation.
627 for ( int i = 0; i < nbFrames; i++ )
629 for ( int j = 0; j < l; j++ )
631 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
632 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
633 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
635 if (R < 0.0) R = 0.0;
636 if (G < 0.0) G = 0.0;
637 if (B < 0.0) B = 0.0;
638 if (R > 255.0) R = 255.0;
639 if (G > 255.0) G = 255.0;
640 if (B > 255.0) B = 255.0;
642 *(localRaw++) = (uint8_t)R;
643 *(localRaw++) = (uint8_t)G;
644 *(localRaw++) = (uint8_t)B;
654 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
655 * \warning Works on all the frames at a time
657 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
659 uint8_t *localRaw = Raw;
660 uint8_t *copyRaw = new uint8_t[ RawSize ];
661 memmove( copyRaw, localRaw, RawSize );
663 int l = XSize * YSize * ZSize;
665 uint8_t* a = copyRaw;
666 uint8_t* b = copyRaw + l;
667 uint8_t* c = copyRaw + l + l;
669 for (int j = 0; j < l; j++)
671 *(localRaw++) = *(a++);
672 *(localRaw++) = *(b++);
673 *(localRaw++) = *(c++);
678 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
680 // ComputeRawAndRGBSizes is already made by
681 // ::GrabInformationsFromHeader. So, the structure sizes are
685 //////////////////////////////////////////////////
686 //// First stage: get our hands on the Pixel Data.
689 gdcmVerboseMacro( "Unavailable file pointer." );
693 fp->seekg( PixelOffset, std::ios::beg );
694 if( fp->fail() || fp->eof())
696 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
702 //////////////////////////////////////////////////
703 //// Second stage: read from disk dans decompress.
704 if ( BitsAllocated == 12 )
706 ReadAndDecompress12BitsTo16Bits( fp);
710 // This problem can be found when some obvious informations are found
711 // after the field containing the image datas. In this case, these
712 // bad datas are added to the size of the image (in the PixelDataLength
713 // variable). But RawSize is the right size of the image !
714 if( PixelDataLength != RawSize)
716 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
718 if( PixelDataLength > RawSize)
720 fp->read( (char*)Raw, RawSize);
724 fp->read( (char*)Raw, PixelDataLength);
727 if ( fp->fail() || fp->eof())
729 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
733 else if ( IsRLELossless )
735 if ( ! ReadAndDecompressRLEFile( fp ) )
737 gdcmVerboseMacro( "RLE decompressor failed." );
743 // Default case concerns JPEG family
744 if ( ! ReadAndDecompressJPEGFile( fp ) )
746 gdcmVerboseMacro( "JPEG decompressor failed." );
751 ////////////////////////////////////////////
752 //// Third stage: twigle the bytes and bits.
753 ConvertReorderEndianity();
754 ConvertReArrangeBits();
755 ConvertHandleColor();
760 void PixelReadConvert::ConvertHandleColor()
762 //////////////////////////////////
763 // Deal with the color decoding i.e. handle:
764 // - R, G, B planes (as opposed to RGB pixels)
765 // - YBR (various) encodings.
766 // - LUT[s] (or "PALETTE COLOR").
768 // The classification in the color decoding schema is based on the blending
769 // of two Dicom tags values:
770 // * "Photometric Interpretation" for which we have the cases:
771 // - [Photo A] MONOCHROME[1|2] pictures,
772 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
773 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
774 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
775 // * "Planar Configuration" for which we have the cases:
776 // - [Planar 0] 0 then Pixels are already RGB
777 // - [Planar 1] 1 then we have 3 planes : R, G, B,
778 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
780 // Now in theory, one could expect some coherence when blending the above
781 // cases. For example we should not encounter files belonging at the
782 // time to case [Planar 0] and case [Photo D].
783 // Alas, this was only theory ! Because in practice some odd (read ill
784 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
785 // - "Planar Configuration" = 0,
786 // - "Photometric Interpretation" = "PALETTE COLOR".
787 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
788 // towards Dicom-non-conformance files:
789 // << whatever the "Planar Configuration" value might be, a
790 // "Photometric Interpretation" set to "PALETTE COLOR" forces
791 // a LUT intervention >>
793 // Now we are left with the following handling of the cases:
794 // - [Planar 0] OR [Photo A] no color decoding (since respectively
795 // Pixels are already RGB and monochrome pictures have no color :),
796 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
797 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
798 // - [Planar 2] OR [Photo D] requires LUT intervention.
802 // [Planar 2] OR [Photo D]: LUT intervention done outside
806 if ( PlanarConfiguration == 1 )
810 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
811 ConvertYcBcRPlanesToRGBPixels();
815 // [Planar 1] AND [Photo C]
816 ConvertRGBPlanesToRGBPixels();
821 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
822 // pixels need to be RGB-fied anyway
825 ConvertRGBPlanesToRGBPixels();
827 // In *normal *case, when planarConf is 0, pixels are already in RGB
831 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
832 * \note See comments of \ref ConvertHandleColor
834 bool PixelReadConvert::IsRawRGB()
837 || PlanarConfiguration == 2
845 void PixelReadConvert::ComputeRawAndRGBSizes()
847 int bitsAllocated = BitsAllocated;
848 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
849 // in this case we will expand the image to 16 bits (see
850 // \ref ReadAndDecompress12BitsTo16Bits() )
851 if ( BitsAllocated == 12 )
856 RawSize = XSize * YSize * ZSize
857 * ( bitsAllocated / 8 )
861 RGBSize = 3 * RawSize;
869 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
871 // Number of Bits Allocated for storing a Pixel is defaulted to 16
872 // when absent from the header.
873 BitsAllocated = header->GetBitsAllocated();
874 if ( BitsAllocated == 0 )
879 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
880 // when absent from the header.
881 BitsStored = header->GetBitsStored();
882 if ( BitsStored == 0 )
884 BitsStored = BitsAllocated;
888 HighBitPosition = header->GetHighBitPosition();
889 if ( HighBitPosition == 0 )
891 HighBitPosition = BitsAllocated - 1;
894 XSize = header->GetXSize();
895 YSize = header->GetYSize();
896 ZSize = header->GetZSize();
897 SamplesPerPixel = header->GetSamplesPerPixel();
898 PixelSize = header->GetPixelSize();
899 PixelSign = header->IsSignedPixelData();
900 SwapCode = header->GetSwapCode();
901 std::string ts = header->GetTransferSyntax();
903 ( ! header->IsDicomV3() )
904 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
905 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
906 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
907 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
908 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
909 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
910 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
911 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
912 PixelOffset = header->GetPixelOffset();
913 PixelDataLength = header->GetPixelAreaLength();
914 RLEInfo = header->GetRLEInfo();
915 JPEGInfo = header->GetJPEGInfo();
917 PlanarConfiguration = header->GetPlanarConfiguration();
918 IsMonochrome = header->IsMonochrome();
919 IsPaletteColor = header->IsPaletteColor();
920 IsYBRFull = header->IsYBRFull();
922 /////////////////////////////////////////////////////////////////
924 HasLUT = header->HasLUT();
927 // Just in case some access to a Header element requires disk access.
928 LutRedDescriptor = header->GetEntry( 0x0028, 0x1101 );
929 LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
930 LutBlueDescriptor = header->GetEntry( 0x0028, 0x1103 );
932 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
933 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
934 // Document::Document() ], the loading of the value (content) of a
935 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
936 // loaded). Hence, we first try to obtain the LUTs data from the header
937 // and when this fails we read the LUTs data directely from disk.
938 /// \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
939 /// We should NOT bypass the [Bin|Val]Entry class. Instead
940 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
941 /// (e.g. BinEntry::GetBinArea()) should force disk access from
942 /// within the [Bin|Val]Entry class itself. The only problem
943 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
944 /// parsed from. Fix that. FIXME.
947 header->LoadEntryBinArea(0x0028, 0x1201);
948 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
951 gdcmVerboseMacro( "Unable to read Red LUT data" );
955 header->LoadEntryBinArea(0x0028, 0x1202);
956 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
959 gdcmVerboseMacro( "Unable to read Green LUT data" );
963 header->LoadEntryBinArea(0x0028, 0x1203);
964 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
967 gdcmVerboseMacro( "Unable to read Blue LUT data" );
971 ComputeRawAndRGBSizes();
975 * \brief Build Red/Green/Blue/Alpha LUT from Header
976 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
977 * and (0028,1101),(0028,1102),(0028,1102)
978 * - xxx Palette Color Lookup Table Descriptor - are found
979 * and (0028,1201),(0028,1202),(0028,1202)
980 * - xxx Palette Color Lookup Table Data - are found
981 * \warning does NOT deal with :
982 * 0028 1100 Gray Lookup Table Descriptor (Retired)
983 * 0028 1221 Segmented Red Palette Color Lookup Table Data
984 * 0028 1222 Segmented Green Palette Color Lookup Table Data
985 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
986 * no known Dicom reader deals with them :-(
987 * @return a RGBA Lookup Table
989 void PixelReadConvert::BuildLUTRGBA()
996 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
998 if ( ! IsPaletteColor )
1003 if ( LutRedDescriptor == GDCM_UNFOUND
1004 || LutGreenDescriptor == GDCM_UNFOUND
1005 || LutBlueDescriptor == GDCM_UNFOUND )
1010 ////////////////////////////////////////////
1011 // Extract the info from the LUT descriptors
1012 int lengthR; // Red LUT length in Bytes
1013 int debR; // Subscript of the first Lut Value
1014 int nbitsR; // Lut item size (in Bits)
1015 int nbRead = sscanf( LutRedDescriptor.c_str(),
1017 &lengthR, &debR, &nbitsR );
1020 gdcmVerboseMacro( "Wrong Red LUT descriptor" );
1023 int lengthG; // Green LUT length in Bytes
1024 int debG; // Subscript of the first Lut Value
1025 int nbitsG; // Lut item size (in Bits)
1026 nbRead = sscanf( LutGreenDescriptor.c_str(),
1028 &lengthG, &debG, &nbitsG );
1031 gdcmVerboseMacro( "Wrong Green LUT descriptor" );
1034 int lengthB; // Blue LUT length in Bytes
1035 int debB; // Subscript of the first Lut Value
1036 int nbitsB; // Lut item size (in Bits)
1037 nbRead = sscanf( LutRedDescriptor.c_str(),
1039 &lengthB, &debB, &nbitsB );
1042 gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
1045 ////////////////////////////////////////////////////////
1046 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1051 ////////////////////////////////////////////////
1052 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1053 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1058 memset( LutRGBA, 0, 1024 );
1061 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1063 // when LUT item size is different than pixel size
1064 mult = 2; // high byte must be = low byte
1068 // See PS 3.3-2003 C.11.1.1.2 p 619
1072 // if we get a black image, let's just remove the '+1'
1073 // from 'i*mult+1' and check again
1074 // if it works, we shall have to check the 3 Palettes
1075 // to see which byte is ==0 (first one, or second one)
1077 // We give up the checking to avoid some (useless ?) overhead
1078 // (optimistic asumption)
1080 uint8_t* a = LutRGBA + 0;
1081 for( i=0; i < lengthR; ++i )
1083 *a = LutRedData[i*mult+1];
1088 for( i=0; i < lengthG; ++i)
1090 *a = LutGreenData[i*mult+1];
1095 for(i=0; i < lengthB; ++i)
1097 *a = LutBlueData[i*mult+1];
1102 for(i=0; i < 256; ++i)
1104 *a = 1; // Alpha component
1110 * \brief Build the RGB image from the Raw imagage and the LUTs.
1112 bool PixelReadConvert::BuildRGBImage()
1116 // The job is already done.
1122 // The job can't be done
1129 // The job can't be done
1135 uint8_t* localRGB = RGB;
1136 for (size_t i = 0; i < RawSize; ++i )
1139 *localRGB++ = LutRGBA[j];
1140 *localRGB++ = LutRGBA[j+1];
1141 *localRGB++ = LutRGBA[j+2];
1147 * \brief Print self.
1148 * @param indent Indentation string to be prepended during printing.
1149 * @param os Stream to print to.
1151 void PixelReadConvert::Print( std::ostream &os, std::string const & indent )
1154 << "--- Pixel information -------------------------"
1157 << "Pixel Data: offset " << PixelOffset
1158 << " x(" << std::hex << PixelOffset << std::dec
1159 << ") length " << PixelDataLength
1160 << " x(" << std::hex << PixelDataLength << std::dec
1161 << ")" << std::endl;
1163 if ( IsRLELossless )
1167 RLEInfo->Print( os, indent );
1171 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1175 if ( IsJPEG2000 || IsJPEGLossless )
1179 JPEGInfo->Print( os, indent );
1183 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1188 } // end namespace gdcm
1190 // NOTES on File internal calls
1192 // ---> GetImageData
1193 // ---> GetImageDataIntoVector
1194 // |---> GetImageDataIntoVectorRaw
1195 // | lut intervention
1197 // ---> GetImageDataRaw
1198 // ---> GetImageDataIntoVectorRaw