1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2004/12/03 20:16:58 $
7 Version: $Revision: 1.2 $
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 "gdcmPixelReadConvert.h"
28 #include "gdcmDocEntry.h"
29 #include "gdcmRLEFramesInfo.h"
30 #include "gdcmJPEGFragmentsInfo.h"
36 #define str2num(str, typeNum) *((typeNum *)(str))
38 // For JPEG 2000, body in file gdcmJpeg2000.cxx
39 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
41 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
42 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
44 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
45 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
47 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
48 // Beware this is misleading there is no 16bits DCT algorithm, only
49 // jpeg lossless compression exist in 16bits.
50 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
53 //-----------------------------------------------------------------------------
54 // Constructor / Destructor
55 PixelReadConvert::PixelReadConvert()
67 void PixelReadConvert::Squeeze()
77 delete [] Decompressed;
88 PixelReadConvert::~PixelReadConvert()
93 void PixelReadConvert::AllocateRGB()
98 RGB = new uint8_t[ RGBSize ];
101 void PixelReadConvert::AllocateDecompressed()
103 if ( Decompressed ) {
104 delete [] Decompressed;
106 Decompressed = new uint8_t[ DecompressedSize ];
110 * \brief Read from file a 12 bits per pixel image and decompress it
111 * into a 16 bits per pixel image.
113 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
114 throw ( FormatError )
116 int nbPixels = XSize * YSize;
117 uint16_t* localDecompres = (uint16_t*)Decompressed;
119 for( int p = 0; p < nbPixels; p += 2 )
123 fp->read( (char*)&b0, 1);
124 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
126 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
127 "Unfound first block" );
130 fp->read( (char*)&b1, 1 );
131 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
133 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
134 "Unfound second block" );
137 fp->read( (char*)&b2, 1 );
138 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
140 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
141 "Unfound second block" );
144 // Two steps are necessary to please VC++
146 // 2 pixels 12bit = [0xABCDEF]
147 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
149 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
151 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
153 /// \todo JPR Troubles expected on Big-Endian processors ?
158 * \brief Try to deal with RLE 16 Bits.
159 * We assume the RLE has allready been parsed and loaded in
160 * Decompressed (through \ref ReadAndDecompressJPEGFile ).
161 * We here need to make 16 Bits Pixels from Low Byte and
162 * High Byte 'Planes'...(for what it may mean)
165 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
167 size_t PixelNumber = XSize * YSize;
168 size_t decompressedSize = XSize * YSize * NumberOfFrames;
170 // We assumed Decompressed contains the decoded RLE pixels but as
171 // 8 bits per pixel. In order to convert those pixels to 16 bits
172 // per pixel we cannot work in place within Decompressed and hence
173 // we copy it in a safe place, say copyDecompressed.
175 uint8_t* copyDecompressed = new uint8_t[ decompressedSize * 2 ];
176 memmove( copyDecompressed, Decompressed, decompressedSize * 2 );
178 uint8_t* x = Decompressed;
179 uint8_t* a = copyDecompressed;
180 uint8_t* b = a + PixelNumber;
182 for ( int i = 0; i < NumberOfFrames; i++ )
184 for ( unsigned int j = 0; j < PixelNumber; j++ )
191 delete[] copyDecompressed;
193 /// \todo check that operator new []didn't fail, and sometimes return false
198 * \brief Implementation of the RLE decoding algorithm for decompressing
199 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
200 * @param subDecompressed Sub region of \ref Decompressed where the de
201 * decoded fragment should be placed.
202 * @param fragmentSize The length of the binary fragment as found on the disk.
203 * @param decompressedSegmentSize The expected length of the fragment ONCE
205 * @param fp File Pointer: on entry the position should be the one of
206 * the fragment to be decoded.
208 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t* subDecompressed,
210 long decompressedSegmentSize,
214 long numberOfOutputBytes = 0;
215 long numberOfReadBytes = 0;
217 while( numberOfOutputBytes < decompressedSegmentSize )
219 fp->read( (char*)&count, 1 );
220 numberOfReadBytes += 1;
222 // Note: count <= 127 comparison is always true due to limited range
223 // of data type int8_t [since the maximum of an exact width
224 // signed integer of width N is 2^(N-1) - 1, which for int8_t
227 fp->read( (char*)subDecompressed, count + 1);
228 numberOfReadBytes += count + 1;
229 subDecompressed += count + 1;
230 numberOfOutputBytes += count + 1;
234 if ( ( count <= -1 ) && ( count >= -127 ) )
237 fp->read( (char*)&newByte, 1);
238 numberOfReadBytes += 1;
239 for( int i = 0; i < -count + 1; i++ )
241 subDecompressed[i] = newByte;
243 subDecompressed += -count + 1;
244 numberOfOutputBytes += -count + 1;
247 // if count = 128 output nothing
249 if ( numberOfReadBytes > fragmentSize )
251 dbg.Verbose(0, "PixelReadConvert::ReadAndDecompressRLEFragment: we "
252 "read more bytes than the segment size.");
260 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
261 * Dicom encapsulated file and decompress it.
262 * @param fp already open File Pointer
263 * at which the pixel data should be copied
266 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
268 uint8_t* subDecompressed = Decompressed;
269 long decompressedSegmentSize = XSize * YSize;
271 // Loop on the frame[s]
272 for( RLEFramesInfo::RLEFrameList::iterator
273 it = RLEInfo->Frames.begin();
274 it != RLEInfo->Frames.end();
277 // Loop on the fragments
278 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
280 fp->seekg( (*it)->Offset[k] , std::ios::beg );
281 (void)ReadAndDecompressRLEFragment( subDecompressed,
283 decompressedSegmentSize,
285 subDecompressed += decompressedSegmentSize;
289 if ( BitsAllocated == 16 )
291 // Try to deal with RLE 16 Bits
292 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
299 * \brief Swap the bytes, according to \ref SwapCode.
301 void PixelReadConvert::ConvertSwapZone()
305 if( BitsAllocated == 16 )
307 uint16_t* im16 = (uint16_t*)Decompressed;
318 for( i = 0; i < DecompressedSize / 2; i++ )
320 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
324 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
325 "(16 bits) not allowed." );
328 else if( BitsAllocated == 32 )
333 uint32_t* im32 = (uint32_t*)Decompressed;
340 for( i = 0; i < DecompressedSize / 4; i++ )
342 low = im32[i] & 0x0000ffff; // 4321
343 high = im32[i] >> 16;
344 high = ( high >> 8 ) | ( high << 8 );
345 low = ( low >> 8 ) | ( low << 8 );
347 im32[i] = ( s32 << 16 ) | high;
351 for( i = 0; i < DecompressedSize / 4; i++ )
353 low = im32[i] & 0x0000ffff; // 2143
354 high = im32[i] >> 16;
355 high = ( high >> 8 ) | ( high << 8 );
356 low = ( low >> 8 ) | ( low << 8 );
358 im32[i] = ( s32 << 16 ) | low;
362 for( i = 0; i < DecompressedSize / 4; i++ )
364 low = im32[i] & 0x0000ffff; // 3412
365 high = im32[i] >> 16;
367 im32[i] = ( s32 << 16 ) | high;
371 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
372 "(32 bits) not allowed." );
378 * \brief Deal with endianity i.e. re-arange bytes inside the integer
380 void PixelReadConvert::ConvertReorderEndianity()
382 if ( BitsAllocated != 8 )
387 // Special kludge in order to deal with xmedcon broken images:
388 if ( ( BitsAllocated == 16 )
389 && ( BitsStored < BitsAllocated )
392 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
393 uint16_t *deb = (uint16_t *)Decompressed;
394 for(int i = 0; i<l; i++)
406 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
407 & file and decompress it.
408 * @param fp File Pointer
411 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
413 uint8_t* localDecompressed = Decompressed;
414 // Loop on the fragment[s]
415 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
416 it = JPEGInfo->Fragments.begin();
417 it != JPEGInfo->Fragments.end();
420 fp->seekg( (*it)->Offset, std::ios::beg);
424 if ( ! gdcm_read_JPEG2000_file( fp,localDecompressed ) )
429 else if ( BitsStored == 8)
431 // JPEG Lossy : call to IJG 6b
432 if ( ! gdcm_read_JPEG_file8( fp, localDecompressed ) )
437 else if ( BitsStored <= 12)
439 // Reading Fragment pixels
440 if ( ! gdcm_read_JPEG_file12 ( fp, localDecompressed ) )
445 else if ( BitsStored <= 16)
447 // Reading Fragment pixels
448 if ( ! gdcm_read_JPEG_file16 ( fp, localDecompressed ) )
452 //assert( IsJPEGLossless );
456 // other JPEG lossy not supported
457 dbg.Error("PixelReadConvert::ReadAndDecompressJPEGFile: unknown "
458 "jpeg lossy compression ");
462 // Advance to next free location in Decompressed
463 // for next fragment decompression (if any)
464 int length = XSize * YSize * SamplesPerPixel;
465 int numberBytes = BitsAllocated / 8;
467 localDecompressed += length * numberBytes;
473 * \brief Re-arrange the bits within the bytes.
476 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
478 if ( BitsStored != BitsAllocated )
480 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
481 if ( BitsAllocated == 16 )
483 uint16_t mask = 0xffff;
484 mask = mask >> ( BitsAllocated - BitsStored );
485 uint16_t* deb = (uint16_t*)Decompressed;
486 for(int i = 0; i<l; i++)
488 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
492 else if ( BitsAllocated == 32 )
494 uint32_t mask = 0xffffffff;
495 mask = mask >> ( BitsAllocated - BitsStored );
496 uint32_t* deb = (uint32_t*)Decompressed;
497 for(int i = 0; i<l; i++)
499 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
505 dbg.Verbose(0, "PixelReadConvert::ConvertReArrangeBits: weird image");
506 throw FormatError( "PixelReadConvert::ConvertReArrangeBits()",
514 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
515 * \warning Works on all the frames at a time
517 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
519 uint8_t* localDecompressed = Decompressed;
520 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
521 memmove( copyDecompressed, localDecompressed, DecompressedSize );
523 // to see the tricks about YBR_FULL, YBR_FULL_422,
524 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
525 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
526 // and be *very* affraid
528 int l = XSize * YSize;
529 int nbFrames = ZSize;
531 uint8_t* a = copyDecompressed;
532 uint8_t* b = copyDecompressed + l;
533 uint8_t* c = copyDecompressed + l + l;
536 /// \todo : Replace by the 'well known' integer computation
537 /// counterpart. Refer to
538 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
539 /// for code optimisation.
541 for ( int i = 0; i < nbFrames; i++ )
543 for ( int j = 0; j < l; j++ )
545 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
546 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
547 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
549 if (R < 0.0) R = 0.0;
550 if (G < 0.0) G = 0.0;
551 if (B < 0.0) B = 0.0;
552 if (R > 255.0) R = 255.0;
553 if (G > 255.0) G = 255.0;
554 if (B > 255.0) B = 255.0;
556 *(localDecompressed++) = (uint8_t)R;
557 *(localDecompressed++) = (uint8_t)G;
558 *(localDecompressed++) = (uint8_t)B;
564 delete[] copyDecompressed;
568 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
569 * \warning Works on all the frames at a time
571 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
573 uint8_t* localDecompressed = Decompressed;
574 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
575 memmove( copyDecompressed, localDecompressed, DecompressedSize );
577 int l = XSize * YSize * ZSize;
579 uint8_t* a = copyDecompressed;
580 uint8_t* b = copyDecompressed + l;
581 uint8_t* c = copyDecompressed + l + l;
583 for (int j = 0; j < l; j++)
585 *(localDecompressed++) = *(a++);
586 *(localDecompressed++) = *(b++);
587 *(localDecompressed++) = *(c++);
589 delete[] copyDecompressed;
592 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream* fp )
594 // ComputeDecompressedAndRGBSizes is already made by
595 // ::GrabInformationsFromHeader. So, the structure sizes are
599 //////////////////////////////////////////////////
600 //// First stage: get our hands on the Pixel Data.
603 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
604 "unavailable file pointer." );
608 fp->seekg( PixelOffset, std::ios::beg );
609 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
611 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
612 "unable to find PixelOffset in file." );
616 AllocateDecompressed();
618 //////////////////////////////////////////////////
619 //// Second stage: read from disk dans decompress.
620 if ( BitsAllocated == 12 )
622 ReadAndDecompress12BitsTo16Bits( fp);
624 else if ( IsDecompressed )
626 // This problem can be found when some obvious informations are found
627 // after the field containing the image datas. In this case, these
628 // bad datas are added to the size of the image (in the PixelDataLength
629 // variable). But DecompressedSize is the right size of the image !
630 if( PixelDataLength != DecompressedSize)
632 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
633 "Mismatch between PixelReadConvert and DecompressedSize." );
635 if( PixelDataLength > DecompressedSize)
637 fp->read( (char*)Decompressed, DecompressedSize);
641 fp->read( (char*)Decompressed, PixelDataLength);
644 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
646 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
647 "reading of decompressed pixel data failed." );
651 else if ( IsRLELossless )
653 if ( ! ReadAndDecompressRLEFile( fp ) )
655 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
656 "RLE decompressor failed." );
662 // Default case concerns JPEG family
663 if ( ! ReadAndDecompressJPEGFile( fp ) )
665 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
666 "JPEG decompressor failed." );
671 ////////////////////////////////////////////
672 //// Third stage: twigle the bytes and bits.
673 ConvertReorderEndianity();
674 ConvertReArrangeBits();
675 ConvertHandleColor();
680 void PixelReadConvert::ConvertHandleColor()
682 //////////////////////////////////
683 // Deal with the color decoding i.e. handle:
684 // - R, G, B planes (as opposed to RGB pixels)
685 // - YBR (various) encodings.
686 // - LUT[s] (or "PALETTE COLOR").
688 // The classification in the color decoding schema is based on the blending
689 // of two Dicom tags values:
690 // * "Photometric Interpretation" for which we have the cases:
691 // - [Photo A] MONOCHROME[1|2] pictures,
692 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
693 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
694 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
695 // * "Planar Configuration" for which we have the cases:
696 // - [Planar 0] 0 then Pixels are already RGB
697 // - [Planar 1] 1 then we have 3 planes : R, G, B,
698 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
700 // Now in theory, one could expect some coherence when blending the above
701 // cases. For example we should not encounter files belonging at the
702 // time to case [Planar 0] and case [Photo D].
703 // Alas, this was only theory ! Because in practice some odd (read ill
704 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
705 // - "Planar Configuration" = 0,
706 // - "Photometric Interpretation" = "PALETTE COLOR".
707 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
708 // towards Dicom-non-conformance files:
709 // << whatever the "Planar Configuration" value might be, a
710 // "Photometric Interpretation" set to "PALETTE COLOR" forces
711 // a LUT intervention >>
713 // Now we are left with the following handling of the cases:
714 // - [Planar 0] OR [Photo A] no color decoding (since respectively
715 // Pixels are already RGB and monochrome pictures have no color :),
716 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
717 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
718 // - [Planar 2] OR [Photo D] requires LUT intervention.
720 if ( ! IsDecompressedRGB() )
722 // [Planar 2] OR [Photo D]: LUT intervention done outside
726 if ( PlanarConfiguration == 1 )
730 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
731 ConvertYcBcRPlanesToRGBPixels();
735 // [Planar 1] AND [Photo C]
736 ConvertRGBPlanesToRGBPixels();
741 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
742 // pixels need to be RGB-fied anyway
745 ConvertRGBPlanesToRGBPixels();
747 // In *normal *case, when planarConf is 0, pixels are already in RGB
751 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
752 * \note See comments of \ref ConvertHandleColor
754 bool PixelReadConvert::IsDecompressedRGB()
757 || PlanarConfiguration == 2
765 void PixelReadConvert::ComputeDecompressedAndRGBSizes()
767 int bitsAllocated = BitsAllocated;
768 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
769 // in this case we will expand the image to 16 bits (see
770 // \ref ReadAndDecompress12BitsTo16Bits() )
771 if ( BitsAllocated == 12 )
776 DecompressedSize = XSize * YSize * ZSize
777 * ( bitsAllocated / 8 )
781 RGBSize = 3 * DecompressedSize;
785 RGBSize = DecompressedSize;
789 void PixelReadConvert::GrabInformationsFromHeader( Header* header )
791 // Just in case some access to a Header element requires disk access.
792 // Note: gdcmDocument::Fp is leaved open after OpenFile.
793 std::ifstream* fp = header->OpenFile();
794 // Number of Bits Allocated for storing a Pixel is defaulted to 16
795 // when absent from the header.
796 BitsAllocated = header->GetBitsAllocated();
797 if ( BitsAllocated == 0 )
802 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
803 // when absent from the header.
804 BitsStored = header->GetBitsStored();
805 if ( BitsStored == 0 )
807 BitsStored = BitsAllocated;
811 HighBitPosition = header->GetHighBitPosition();
812 if ( HighBitPosition == 0 )
814 HighBitPosition = BitsAllocated - 1;
817 XSize = header->GetXSize();
818 YSize = header->GetYSize();
819 ZSize = header->GetZSize();
820 SamplesPerPixel = header->GetSamplesPerPixel();
821 PixelSize = header->GetPixelSize();
822 PixelSign = header->IsSignedPixelData();
823 SwapCode = header->GetSwapCode();
824 TransferSyntaxType ts = header->GetTransferSyntax();
826 ( ! header->IsDicomV3() )
827 || ts == ImplicitVRLittleEndian
828 || ts == ImplicitVRLittleEndianDLXGE
829 || ts == ExplicitVRLittleEndian
830 || ts == ExplicitVRBigEndian
831 || ts == DeflatedExplicitVRLittleEndian;
832 IsJPEG2000 = header->IsJPEG2000();
833 IsJPEGLossless = header->IsJPEGLossless();
834 IsRLELossless = ( ts == RLELossless );
835 PixelOffset = header->GetPixelOffset();
836 PixelDataLength = header->GetPixelAreaLength();
837 RLEInfo = header->GetRLEInfo();
838 JPEGInfo = header->GetJPEGInfo();
840 PlanarConfiguration = header->GetPlanarConfiguration();
841 IsMonochrome = header->IsMonochrome();
842 IsPaletteColor = header->IsPaletteColor();
843 IsYBRFull = header->IsYBRFull();
845 /////////////////////////////////////////////////////////////////
847 HasLUT = header->HasLUT();
850 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
851 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
852 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
854 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
855 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
856 // Document::Document() ], the loading of the value (content) of a
857 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
858 // loaded). Hence, we first try to obtain the LUTs data from the header
859 // and when this fails we read the LUTs data directely from disk.
860 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
861 /// We should NOT bypass the [Bin|Val]Entry class. Instead
862 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
863 /// (e.g. BinEntry::GetBinArea()) should force disk access from
864 /// within the [Bin|Val]Entry class itself. The only problem
865 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
866 /// parsed from. Fix that. FIXME.
869 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
872 // Read the Lut Data from disk
873 DocEntry* lutRedDataEntry = header->GetDocEntryByNumber( 0x0028,
875 LutRedData = new uint8_t[ lutRedDataEntry->GetLength() ];
876 fp->seekg( lutRedDataEntry->GetOffset() ,std::ios::beg );
877 fp->read( (char*)LutRedData, (size_t)lutRedDataEntry->GetLength());
878 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
880 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
881 "unable to read red LUT data" );
886 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
889 // Read the Lut Data from disk
890 DocEntry* lutGreenDataEntry = header->GetDocEntryByNumber( 0x0028,
892 LutGreenData = new uint8_t[ lutGreenDataEntry->GetLength() ];
893 fp->seekg( lutGreenDataEntry->GetOffset() , std::ios::beg );
894 fp->read( (char*)LutGreenData, (size_t)lutGreenDataEntry->GetLength() );
895 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
897 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
898 "unable to read green LUT data" );
903 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
906 // Read the Lut Data from disk
907 DocEntry* lutBlueDataEntry = header->GetDocEntryByNumber( 0x0028,
909 LutBlueData = new uint8_t[ lutBlueDataEntry->GetLength() ];
910 fp->seekg( lutBlueDataEntry->GetOffset() , std::ios::beg );
911 fp->read( (char*)LutBlueData, (size_t)lutBlueDataEntry->GetLength() );
912 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
914 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
915 "unable to read blue LUT data" );
920 ComputeDecompressedAndRGBSizes();
929 * \brief Build Red/Green/Blue/Alpha LUT from Header
930 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
931 * and (0028,1101),(0028,1102),(0028,1102)
932 * - xxx Palette Color Lookup Table Descriptor - are found
933 * and (0028,1201),(0028,1202),(0028,1202)
934 * - xxx Palette Color Lookup Table Data - are found
935 * \warning does NOT deal with :
936 * 0028 1100 Gray Lookup Table Descriptor (Retired)
937 * 0028 1221 Segmented Red Palette Color Lookup Table Data
938 * 0028 1222 Segmented Green Palette Color Lookup Table Data
939 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
940 * no known Dicom reader deals with them :-(
941 * @return a RGBA Lookup Table
943 void PixelReadConvert::BuildLUTRGBA()
950 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
952 if ( ! IsPaletteColor )
957 if ( LutRedDescriptor == GDCM_UNFOUND
958 || LutGreenDescriptor == GDCM_UNFOUND
959 || LutBlueDescriptor == GDCM_UNFOUND )
964 ////////////////////////////////////////////
965 // Extract the info from the LUT descriptors
966 int lengthR; // Red LUT length in Bytes
967 int debR; // Subscript of the first Lut Value
968 int nbitsR; // Lut item size (in Bits)
969 int nbRead = sscanf( LutRedDescriptor.c_str(),
971 &lengthR, &debR, &nbitsR );
974 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong red LUT descriptor");
977 int lengthG; // Green LUT length in Bytes
978 int debG; // Subscript of the first Lut Value
979 int nbitsG; // Lut item size (in Bits)
980 nbRead = sscanf( LutGreenDescriptor.c_str(),
982 &lengthG, &debG, &nbitsG );
985 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong green LUT descriptor");
988 int lengthB; // Blue LUT length in Bytes
989 int debB; // Subscript of the first Lut Value
990 int nbitsB; // Lut item size (in Bits)
991 nbRead = sscanf( LutRedDescriptor.c_str(),
993 &lengthB, &debB, &nbitsB );
996 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong blue LUT descriptor");
999 ////////////////////////////////////////////////////////
1000 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1005 ////////////////////////////////////////////////
1006 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1007 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1012 memset( LutRGBA, 0, 1024 );
1015 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1017 // when LUT item size is different than pixel size
1018 mult = 2; // high byte must be = low byte
1022 // See PS 3.3-2003 C.11.1.1.2 p 619
1026 // if we get a black image, let's just remove the '+1'
1027 // from 'i*mult+1' and check again
1028 // if it works, we shall have to check the 3 Palettes
1029 // to see which byte is ==0 (first one, or second one)
1031 // We give up the checking to avoid some (useless ?)overhead
1032 // (optimistic asumption)
1034 uint8_t* a = LutRGBA + 0;
1035 for( i=0; i < lengthR; ++i )
1037 *a = LutRedData[i*mult+1];
1042 for( i=0; i < lengthG; ++i)
1044 *a = LutGreenData[i*mult+1];
1049 for(i=0; i < lengthB; ++i)
1051 *a = LutBlueData[i*mult+1];
1056 for(i=0; i < 256; ++i)
1058 *a = 1; // Alpha component
1064 * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1066 bool PixelReadConvert::BuildRGBImage()
1070 // The job is already done.
1074 if ( ! Decompressed )
1076 // The job can't be done
1083 // The job can't be done
1089 uint8_t* localRGB = RGB;
1090 for (size_t i = 0; i < DecompressedSize; ++i )
1092 int j = Decompressed[i] * 4;
1093 *localRGB++ = LutRGBA[j];
1094 *localRGB++ = LutRGBA[j+1];
1095 *localRGB++ = LutRGBA[j+2];
1101 * \brief Print self.
1102 * @param indent Indentation string to be prepended during printing.
1103 * @param os Stream to print to.
1105 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1108 << "--- Pixel information -------------------------"
1111 << "Pixel Data: offset " << PixelOffset
1112 << " x" << std::hex << PixelOffset << std::dec
1113 << " length " << PixelDataLength
1114 << " x" << std::hex << PixelDataLength << std::dec
1117 if ( IsRLELossless )
1121 RLEInfo->Print( indent, os );
1125 dbg.Verbose(0, "PixelReadConvert::Print: set as RLE file "
1126 "but NO RLEinfo present.");
1130 if ( IsJPEG2000 || IsJPEGLossless )
1134 JPEGInfo->Print( indent, os );
1138 dbg.Verbose(0, "PixelReadConvert::Print: set as JPEG file "
1139 "but NO JPEGinfo present.");
1144 } // end namespace gdcm
1146 // NOTES on File internal calls
1148 // ---> GetImageData
1149 // ---> GetImageDataIntoVector
1150 // |---> GetImageDataIntoVectorRaw
1151 // | lut intervention
1153 // ---> GetImageDataRaw
1154 // ---> GetImageDataIntoVectorRaw