1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/26 11:42:02 $
7 Version: $Revision: 1.35 $
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)->GetNumberOfFragments(); k++ )
262 fp->seekg( (*it)->GetOffset(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)->GetLength();
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 gdcmVerboseMacro( "Sorry, JPEG2000 not yet taken into account" );
501 fp->seekg( (*JPEGInfo->Fragments.begin())->GetOffset(), std::ios::beg);
502 // if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
503 gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
509 gdcmVerboseMacro( "Sorry, JPEG-LS not yet taken into account" );
510 fp->seekg( (*JPEGInfo->Fragments.begin())->GetOffset(), std::ios::beg);
511 // if ( ! gdcm_read_JPEGLS_file( fp,Raw ) )
515 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
517 // we have one frame split into several fragments
518 // we will pack those fragments into a single buffer and
520 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
522 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
525 // if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
527 // // we have one frame split into several fragments
528 // // we will pack those fragments into a single buffer and
530 // return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
532 // else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
534 // suppose each fragment is a frame
535 return ReadAndDecompressJPEGFramesFromFile( fp );
539 // // The dicom image contains frames containing fragments of images
540 // // a more complex algorithm :-)
541 // return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
546 * \brief Re-arrange the bits within the bytes.
549 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
551 if ( BitsStored != BitsAllocated )
553 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
554 if ( BitsAllocated == 16 )
556 uint16_t mask = 0xffff;
557 mask = mask >> ( BitsAllocated - BitsStored );
558 uint16_t* deb = (uint16_t*)Raw;
559 for(int i = 0; i<l; i++)
561 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
565 else if ( BitsAllocated == 32 )
567 uint32_t mask = 0xffffffff;
568 mask = mask >> ( BitsAllocated - BitsStored );
569 uint32_t* deb = (uint32_t*)Raw;
570 for(int i = 0; i<l; i++)
572 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
578 gdcmVerboseMacro("Weird image");
579 throw FormatError( "Weird image !?" );
586 * \brief Convert (cY plane, cB plane, cR plane) to RGB pixels
587 * \warning Works on all the frames at a time
589 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
591 uint8_t *localRaw = Raw;
592 uint8_t *copyRaw = new uint8_t[ RawSize ];
593 memmove( copyRaw, localRaw, RawSize );
595 // to see the tricks about YBR_FULL, YBR_FULL_422,
596 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
597 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
598 // and be *very* affraid
600 int l = XSize * YSize;
601 int nbFrames = ZSize;
603 uint8_t *a = copyRaw;
604 uint8_t *b = copyRaw + l;
605 uint8_t *c = copyRaw + l + l;
608 /// \todo : Replace by the 'well known' integer computation
609 /// counterpart. Refer to
610 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
611 /// for code optimisation.
613 for ( int i = 0; i < nbFrames; i++ )
615 for ( int j = 0; j < l; j++ )
617 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
618 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
619 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
621 if (R < 0.0) R = 0.0;
622 if (G < 0.0) G = 0.0;
623 if (B < 0.0) B = 0.0;
624 if (R > 255.0) R = 255.0;
625 if (G > 255.0) G = 255.0;
626 if (B > 255.0) B = 255.0;
628 *(localRaw++) = (uint8_t)R;
629 *(localRaw++) = (uint8_t)G;
630 *(localRaw++) = (uint8_t)B;
640 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
641 * \warning Works on all the frames at a time
643 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
645 uint8_t *localRaw = Raw;
646 uint8_t *copyRaw = new uint8_t[ RawSize ];
647 memmove( copyRaw, localRaw, RawSize );
649 int l = XSize * YSize * ZSize;
651 uint8_t* a = copyRaw;
652 uint8_t* b = copyRaw + l;
653 uint8_t* c = copyRaw + l + l;
655 for (int j = 0; j < l; j++)
657 *(localRaw++) = *(a++);
658 *(localRaw++) = *(b++);
659 *(localRaw++) = *(c++);
664 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
666 // ComputeRawAndRGBSizes is already made by
667 // ::GrabInformationsFromHeader. So, the structure sizes are
671 //////////////////////////////////////////////////
672 //// First stage: get our hands on the Pixel Data.
675 gdcmVerboseMacro( "Unavailable file pointer." );
679 fp->seekg( PixelOffset, std::ios::beg );
680 if( fp->fail() || fp->eof())
682 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
688 //////////////////////////////////////////////////
689 //// Second stage: read from disk dans decompress.
690 if ( BitsAllocated == 12 )
692 ReadAndDecompress12BitsTo16Bits( fp);
696 // This problem can be found when some obvious informations are found
697 // after the field containing the image data. In this case, these
698 // bad data are added to the size of the image (in the PixelDataLength
699 // variable). But RawSize is the right size of the image !
700 if( PixelDataLength != RawSize)
702 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
704 if( PixelDataLength > RawSize)
706 fp->read( (char*)Raw, RawSize);
710 fp->read( (char*)Raw, PixelDataLength);
713 if ( fp->fail() || fp->eof())
715 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
719 else if ( IsRLELossless )
721 if ( ! ReadAndDecompressRLEFile( fp ) )
723 gdcmVerboseMacro( "RLE decompressor failed." );
729 // Default case concerns JPEG family
730 if ( ! ReadAndDecompressJPEGFile( fp ) )
732 gdcmVerboseMacro( "JPEG decompressor failed." );
737 ////////////////////////////////////////////
738 //// Third stage: twigle the bytes and bits.
739 ConvertReorderEndianity();
740 ConvertReArrangeBits();
741 ConvertHandleColor();
746 void PixelReadConvert::ConvertHandleColor()
748 //////////////////////////////////
749 // Deal with the color decoding i.e. handle:
750 // - R, G, B planes (as opposed to RGB pixels)
751 // - YBR (various) encodings.
752 // - LUT[s] (or "PALETTE COLOR").
754 // The classification in the color decoding schema is based on the blending
755 // of two Dicom tags values:
756 // * "Photometric Interpretation" for which we have the cases:
757 // - [Photo A] MONOCHROME[1|2] pictures,
758 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
759 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
760 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
761 // * "Planar Configuration" for which we have the cases:
762 // - [Planar 0] 0 then Pixels are already RGB
763 // - [Planar 1] 1 then we have 3 planes : R, G, B,
764 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
766 // Now in theory, one could expect some coherence when blending the above
767 // cases. For example we should not encounter files belonging at the
768 // time to case [Planar 0] and case [Photo D].
769 // Alas, this was only theory ! Because in practice some odd (read ill
770 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
771 // - "Planar Configuration" = 0,
772 // - "Photometric Interpretation" = "PALETTE COLOR".
773 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
774 // towards Dicom-non-conformance files:
775 // << whatever the "Planar Configuration" value might be, a
776 // "Photometric Interpretation" set to "PALETTE COLOR" forces
777 // a LUT intervention >>
779 // Now we are left with the following handling of the cases:
780 // - [Planar 0] OR [Photo A] no color decoding (since respectively
781 // Pixels are already RGB and monochrome pictures have no color :),
782 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
783 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
784 // - [Planar 2] OR [Photo D] requires LUT intervention.
788 // [Planar 2] OR [Photo D]: LUT intervention done outside
792 if ( PlanarConfiguration == 1 )
796 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
797 ConvertYcBcRPlanesToRGBPixels();
801 // [Planar 1] AND [Photo C]
802 ConvertRGBPlanesToRGBPixels();
807 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
808 // pixels need to be RGB-fied anyway
811 ConvertRGBPlanesToRGBPixels();
813 // In *normal *case, when planarConf is 0, pixels are already in RGB
817 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
818 * \note See comments of \ref ConvertHandleColor
820 bool PixelReadConvert::IsRawRGB()
823 || PlanarConfiguration == 2
831 void PixelReadConvert::ComputeRawAndRGBSizes()
833 int bitsAllocated = BitsAllocated;
834 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
835 // in this case we will expand the image to 16 bits (see
836 // \ref ReadAndDecompress12BitsTo16Bits() )
837 if ( BitsAllocated == 12 )
842 RawSize = XSize * YSize * ZSize
843 * ( bitsAllocated / 8 )
847 RGBSize = 3 * RawSize;
855 void PixelReadConvert::GrabInformationsFromHeader( File *header )
857 // Number of Bits Allocated for storing a Pixel is defaulted to 16
858 // when absent from the header.
859 BitsAllocated = header->GetBitsAllocated();
860 if ( BitsAllocated == 0 )
865 // Number of "Bits Stored", defaulted to number of "Bits Allocated"
866 // when absent from the header.
867 BitsStored = header->GetBitsStored();
868 if ( BitsStored == 0 )
870 BitsStored = BitsAllocated;
873 // High Bit Position, defaulted to "Bits Allocated" - 1
874 HighBitPosition = header->GetHighBitPosition();
875 if ( HighBitPosition == 0 )
877 HighBitPosition = BitsAllocated - 1;
880 XSize = header->GetXSize();
881 YSize = header->GetYSize();
882 ZSize = header->GetZSize();
883 SamplesPerPixel = header->GetSamplesPerPixel();
884 PixelSize = header->GetPixelSize();
885 PixelSign = header->IsSignedPixelData();
886 SwapCode = header->GetSwapCode();
887 std::string ts = header->GetTransferSyntax();
889 ( ! header->IsDicomV3() )
890 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
891 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
892 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
893 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
894 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
896 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
897 IsJPEGLS = Global::GetTS()->IsJPEGLS(ts);
898 IsJPEGLossy = Global::GetTS()->IsJPEGLossy(ts);
899 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
900 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
902 PixelOffset = header->GetPixelOffset();
903 PixelDataLength = header->GetPixelAreaLength();
904 RLEInfo = header->GetRLEInfo();
905 JPEGInfo = header->GetJPEGInfo();
907 PlanarConfiguration = header->GetPlanarConfiguration();
908 IsMonochrome = header->IsMonochrome();
909 IsPaletteColor = header->IsPaletteColor();
910 IsYBRFull = header->IsYBRFull();
912 /////////////////////////////////////////////////////////////////
914 HasLUT = header->HasLUT();
917 // Just in case some access to a File element requires disk access.
918 LutRedDescriptor = header->GetEntryValue( 0x0028, 0x1101 );
919 LutGreenDescriptor = header->GetEntryValue( 0x0028, 0x1102 );
920 LutBlueDescriptor = header->GetEntryValue( 0x0028, 0x1103 );
922 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
923 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
924 // Document::Document() ], the loading of the value (content) of a
925 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
926 // loaded). Hence, we first try to obtain the LUTs data from the file
927 // and when this fails we read the LUTs data directly from disk.
928 /// \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
929 /// We should NOT bypass the [Bin|Val]Entry class. Instead
930 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
931 /// (e.g. BinEntry::GetBinArea()) should force disk access from
932 /// within the [Bin|Val]Entry class itself. The only problem
933 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
934 /// parsed from. Fix that. FIXME.
937 header->LoadEntryBinArea(0x0028, 0x1201);
938 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
941 gdcmVerboseMacro( "Unable to read Red LUT data" );
945 header->LoadEntryBinArea(0x0028, 0x1202);
946 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
949 gdcmVerboseMacro( "Unable to read Green LUT data" );
953 header->LoadEntryBinArea(0x0028, 0x1203);
954 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
957 gdcmVerboseMacro( "Unable to read Blue LUT data" );
961 ComputeRawAndRGBSizes();
965 * \brief Build Red/Green/Blue/Alpha LUT from File
966 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
967 * and (0028,1101),(0028,1102),(0028,1102)
968 * - xxx Palette Color Lookup Table Descriptor - are found
969 * and (0028,1201),(0028,1202),(0028,1202)
970 * - xxx Palette Color Lookup Table Data - are found
971 * \warning does NOT deal with :
972 * 0028 1100 Gray Lookup Table Descriptor (Retired)
973 * 0028 1221 Segmented Red Palette Color Lookup Table Data
974 * 0028 1222 Segmented Green Palette Color Lookup Table Data
975 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
976 * no known Dicom reader deals with them :-(
977 * @return a RGBA Lookup Table
979 void PixelReadConvert::BuildLUTRGBA()
986 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
988 if ( ! IsPaletteColor )
993 if ( LutRedDescriptor == GDCM_UNFOUND
994 || LutGreenDescriptor == GDCM_UNFOUND
995 || LutBlueDescriptor == GDCM_UNFOUND )
1000 ////////////////////////////////////////////
1001 // Extract the info from the LUT descriptors
1002 int lengthR; // Red LUT length in Bytes
1003 int debR; // Subscript of the first Lut Value
1004 int nbitsR; // Lut item size (in Bits)
1005 int nbRead = sscanf( LutRedDescriptor.c_str(),
1007 &lengthR, &debR, &nbitsR );
1010 gdcmVerboseMacro( "Wrong Red LUT descriptor" );
1013 int lengthG; // Green LUT length in Bytes
1014 int debG; // Subscript of the first Lut Value
1015 int nbitsG; // Lut item size (in Bits)
1016 nbRead = sscanf( LutGreenDescriptor.c_str(),
1018 &lengthG, &debG, &nbitsG );
1021 gdcmVerboseMacro( "Wrong Green LUT descriptor" );
1024 int lengthB; // Blue LUT length in Bytes
1025 int debB; // Subscript of the first Lut Value
1026 int nbitsB; // Lut item size (in Bits)
1027 nbRead = sscanf( LutRedDescriptor.c_str(),
1029 &lengthB, &debB, &nbitsB );
1032 gdcmVerboseMacro( "Wrong Blue LUT descriptor" );
1035 ////////////////////////////////////////////////////////
1036 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1041 ////////////////////////////////////////////////
1042 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1043 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1048 memset( LutRGBA, 0, 1024 );
1051 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1053 // when LUT item size is different than pixel size
1054 mult = 2; // high byte must be = low byte
1058 // See PS 3.3-2003 C.11.1.1.2 p 619
1062 // if we get a black image, let's just remove the '+1'
1063 // from 'i*mult+1' and check again
1064 // if it works, we shall have to check the 3 Palettes
1065 // to see which byte is ==0 (first one, or second one)
1067 // We give up the checking to avoid some (useless ?) overhead
1068 // (optimistic asumption)
1070 uint8_t* a = LutRGBA + 0;
1071 for( i=0; i < lengthR; ++i )
1073 *a = LutRedData[i*mult+1];
1078 for( i=0; i < lengthG; ++i)
1080 *a = LutGreenData[i*mult+1];
1085 for(i=0; i < lengthB; ++i)
1087 *a = LutBlueData[i*mult+1];
1092 for(i=0; i < 256; ++i)
1094 *a = 1; // Alpha component
1100 * \brief Build the RGB image from the Raw imagage and the LUTs.
1102 bool PixelReadConvert::BuildRGBImage()
1106 // The job is already done.
1112 // The job can't be done
1119 // The job can't be done
1125 uint8_t* localRGB = RGB;
1126 for (size_t i = 0; i < RawSize; ++i )
1129 *localRGB++ = LutRGBA[j];
1130 *localRGB++ = LutRGBA[j+1];
1131 *localRGB++ = LutRGBA[j+2];
1137 * \brief Print self.
1138 * @param indent Indentation string to be prepended during printing.
1139 * @param os Stream to print to.
1141 void PixelReadConvert::Print( std::ostream &os, std::string const & indent )
1144 << "--- Pixel information -------------------------"
1147 << "Pixel Data: offset " << PixelOffset
1148 << " x(" << std::hex << PixelOffset << std::dec
1149 << ") length " << PixelDataLength
1150 << " x(" << std::hex << PixelDataLength << std::dec
1151 << ")" << std::endl;
1153 if ( IsRLELossless )
1157 RLEInfo->Print( os, indent );
1161 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1165 if ( IsJPEG2000 || IsJPEGLossless || IsJPEGLossy || IsJPEGLS )
1169 JPEGInfo->Print( os, indent );
1173 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1178 } // end namespace gdcm
1180 // NOTES on File internal calls
1182 // ---> GetImageData
1183 // ---> GetImageDataIntoVector
1184 // |---> GetImageDataIntoVectorRaw
1185 // | lut intervention
1187 // ---> GetImageDataRaw
1188 // ---> GetImageDataIntoVectorRaw