1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/11/17 19:49:13 $
7 Version: $Revision: 1.31 $
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 PIXELCONVERT everywhere and clean up !
25 #include "gdcmDebug.h"
26 #include "gdcmPixelConvert.h"
32 #define str2num(str, typeNum) *((typeNum *)(str))
34 // For JPEG 2000, body in file gdcmJpeg2000.cxx
35 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
37 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
38 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
40 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
41 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
43 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
44 // Beware this is misleading there is no 16bits DCT algorithm, only
45 // jpeg lossless compression exist in 16bits.
46 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
49 //-----------------------------------------------------------------------------
50 // Constructor / Destructor
51 PixelConvert::PixelConvert()
63 void PixelConvert::Squeeze()
73 delete [] Decompressed;
84 PixelConvert::~PixelConvert()
89 void PixelConvert::AllocateRGB()
94 RGB = new uint8_t[ RGBSize ];
97 void PixelConvert::AllocateDecompressed()
100 delete [] Decompressed;
102 Decompressed = new uint8_t[ DecompressedSize ];
106 * \brief Read from file a 12 bits per pixel image and decompress it
107 * into a 16 bits per pixel image.
109 void PixelConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
110 throw ( FormatError )
112 int nbPixels = XSize * YSize;
113 uint16_t* localDecompres = (uint16_t*)Decompressed;
115 for( int p = 0; p < nbPixels; p += 2 )
119 fp->read( (char*)&b0, 1);
120 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
122 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
123 "Unfound first block" );
126 fp->read( (char*)&b1, 1 );
127 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
129 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
130 "Unfound second block" );
133 fp->read( (char*)&b2, 1 );
134 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
136 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
137 "Unfound second block" );
140 // Two steps are necessary to please VC++
142 // 2 pixels 12bit = [0xABCDEF]
143 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
145 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
147 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
149 /// \todo JPR Troubles expected on Big-Endian processors ?
154 * \brief Try to deal with RLE 16 Bits.
155 * We assume the RLE has allready been parsed and loaded in
156 * Decompressed (through \ref ReadAndDecompressJPEGFile ).
157 * We here need to make 16 Bits Pixels from Low Byte and
158 * High Byte 'Planes'...(for what it may mean)
161 bool PixelConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
163 size_t PixelNumber = XSize * YSize;
164 size_t decompressedSize = XSize * YSize * NumberOfFrames;
166 // We assumed Decompressed contains the decoded RLE pixels but as
167 // 8 bits per pixel. In order to convert those pixels to 16 bits
168 // per pixel we cannot work in place within Decompressed and hence
169 // we copy it in a safe place, say copyDecompressed.
171 uint8_t* copyDecompressed = new uint8_t[ decompressedSize * 2 ];
172 memmove( copyDecompressed, Decompressed, decompressedSize * 2 );
174 uint8_t* x = Decompressed;
175 uint8_t* a = copyDecompressed;
176 uint8_t* b = a + PixelNumber;
178 for ( int i = 0; i < NumberOfFrames; i++ )
180 for ( unsigned int j = 0; j < PixelNumber; j++ )
187 delete[] copyDecompressed;
189 /// \todo check that operator new []didn't fail, and sometimes return false
194 * \brief Implementation of the RLE decoding algorithm for decompressing
195 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
196 * @param subDecompressed Sub region of \ref Decompressed where the de
197 * decoded fragment should be placed.
198 * @param fragmentSize The length of the binary fragment as found on the disk.
199 * @param decompressedSegmentSize The expected length of the fragment ONCE
201 * @param fp File Pointer: on entry the position should be the one of
202 * the fragment to be decoded.
204 bool PixelConvert::ReadAndDecompressRLEFragment( uint8_t* subDecompressed,
206 long decompressedSegmentSize,
210 long numberOfOutputBytes = 0;
211 long numberOfReadBytes = 0;
213 while( numberOfOutputBytes < decompressedSegmentSize )
215 fp->read( (char*)&count, 1 );
216 numberOfReadBytes += 1;
218 // Note: count <= 127 comparison is always true due to limited range
219 // of data type int8_t [since the maximum of an exact width
220 // signed integer of width N is 2^(N-1) - 1, which for int8_t
223 fp->read( (char*)subDecompressed, count + 1);
224 numberOfReadBytes += count + 1;
225 subDecompressed += count + 1;
226 numberOfOutputBytes += count + 1;
230 if ( ( count <= -1 ) && ( count >= -127 ) )
233 fp->read( (char*)&newByte, 1);
234 numberOfReadBytes += 1;
235 for( int i = 0; i < -count + 1; i++ )
237 subDecompressed[i] = newByte;
239 subDecompressed += -count + 1;
240 numberOfOutputBytes += -count + 1;
243 // if count = 128 output nothing
245 if ( numberOfReadBytes > fragmentSize )
247 dbg.Verbose(0, "PixelConvert::ReadAndDecompressRLEFragment: we "
248 "read more bytes than the segment size.");
256 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
257 * Dicom encapsulated file and decompress it.
258 * @param fp already open File Pointer
259 * at which the pixel data should be copied
262 bool PixelConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
264 uint8_t* subDecompressed = Decompressed;
265 long decompressedSegmentSize = XSize * YSize;
267 // Loop on the frame[s]
268 for( RLEFramesInfo::RLEFrameList::iterator
269 it = RLEInfo->Frames.begin();
270 it != RLEInfo->Frames.end();
273 // Loop on the fragments
274 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
276 fp->seekg( (*it)->Offset[k] , std::ios_base::beg );
277 (void)ReadAndDecompressRLEFragment( subDecompressed,
279 decompressedSegmentSize,
281 subDecompressed += decompressedSegmentSize;
285 if ( BitsAllocated == 16 )
287 // Try to deal with RLE 16 Bits
288 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
295 * \brief Swap the bytes, according to \ref SwapCode.
297 void PixelConvert::ConvertSwapZone()
301 if( BitsAllocated == 16 )
303 uint16_t* im16 = (uint16_t*)Decompressed;
314 for( i = 0; i < DecompressedSize / 2; i++ )
316 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
320 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
321 "(16 bits) not allowed." );
324 else if( BitsAllocated == 32 )
329 uint32_t* im32 = (uint32_t*)Decompressed;
336 for( i = 0; i < DecompressedSize / 4; i++ )
338 low = im32[i] & 0x0000ffff; // 4321
339 high = im32[i] >> 16;
340 high = ( high >> 8 ) | ( high << 8 );
341 low = ( low >> 8 ) | ( low << 8 );
343 im32[i] = ( s32 << 16 ) | high;
347 for( i = 0; i < DecompressedSize / 4; i++ )
349 low = im32[i] & 0x0000ffff; // 2143
350 high = im32[i] >> 16;
351 high = ( high >> 8 ) | ( high << 8 );
352 low = ( low >> 8 ) | ( low << 8 );
354 im32[i] = ( s32 << 16 ) | low;
358 for( i = 0; i < DecompressedSize / 4; i++ )
360 low = im32[i] & 0x0000ffff; // 3412
361 high = im32[i] >> 16;
363 im32[i] = ( s32 << 16 ) | high;
367 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
368 "(32 bits) not allowed." );
374 * \brief Deal with endianity i.e. re-arange bytes inside the integer
376 void PixelConvert::ConvertReorderEndianity()
378 if ( BitsAllocated != 8 )
383 // Special kludge in order to deal with xmedcon broken images:
384 if ( ( BitsAllocated == 16 )
385 && ( BitsStored < BitsAllocated )
388 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
389 uint16_t *deb = (uint16_t *)Decompressed;
390 for(int i = 0; i<l; i++)
402 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
403 & file and decompress it.
404 * @param fp File Pointer
407 bool PixelConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
409 uint8_t* localDecompressed = Decompressed;
410 // Loop on the fragment[s]
411 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
412 it = JPEGInfo->Fragments.begin();
413 it != JPEGInfo->Fragments.end();
416 fp->seekg( (*it)->Offset, std::ios_base::beg);
420 if ( ! gdcm_read_JPEG2000_file( fp,localDecompressed ) )
425 else if ( BitsStored == 8)
427 // JPEG Lossy : call to IJG 6b
428 if ( ! gdcm_read_JPEG_file8( fp, localDecompressed ) )
433 else if ( BitsStored <= 12)
435 // Reading Fragment pixels
436 if ( ! gdcm_read_JPEG_file12 ( fp, localDecompressed ) )
441 else if ( BitsStored <= 16)
443 // Reading Fragment pixels
444 if ( ! gdcm_read_JPEG_file16 ( fp, localDecompressed ) )
448 //assert( IsJPEGLossless );
452 // other JPEG lossy not supported
453 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
454 "jpeg lossy compression ");
458 // Advance to next free location in Decompressed
459 // for next fragment decompression (if any)
460 int length = XSize * YSize * SamplesPerPixel;
461 int numberBytes = BitsAllocated / 8;
463 localDecompressed += length * numberBytes;
469 * \brief Re-arrange the bits within the bytes.
472 bool PixelConvert::ConvertReArrangeBits() throw ( FormatError )
474 if ( BitsStored != BitsAllocated )
476 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
477 if ( BitsAllocated == 16 )
479 uint16_t mask = 0xffff;
480 mask = mask >> ( BitsAllocated - BitsStored );
481 uint16_t* deb = (uint16_t*)Decompressed;
482 for(int i = 0; i<l; i++)
484 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
488 else if ( BitsAllocated == 32 )
490 uint32_t mask = 0xffffffff;
491 mask = mask >> ( BitsAllocated - BitsStored );
492 uint32_t* deb = (uint32_t*)Decompressed;
493 for(int i = 0; i<l; i++)
495 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
501 dbg.Verbose(0, "PixelConvert::ConvertReArrangeBits: weird image");
502 throw FormatError( "PixelConvert::ConvertReArrangeBits()",
510 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
511 * \warning Works on all the frames at a time
513 void PixelConvert::ConvertYcBcRPlanesToRGBPixels()
515 uint8_t* localDecompressed = Decompressed;
516 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
517 memmove( copyDecompressed, localDecompressed, DecompressedSize );
519 // to see the tricks about YBR_FULL, YBR_FULL_422,
520 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
521 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
522 // and be *very* affraid
524 int l = XSize * YSize;
525 int nbFrames = ZSize;
527 uint8_t* a = copyDecompressed;
528 uint8_t* b = copyDecompressed + l;
529 uint8_t* c = copyDecompressed + l + l;
532 /// \todo : Replace by the 'well known' integer computation
533 /// counterpart. Refer to
534 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
535 /// for code optimisation.
537 for ( int i = 0; i < nbFrames; i++ )
539 for ( int j = 0; j < l; j++ )
541 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
542 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
543 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
545 if (R < 0.0) R = 0.0;
546 if (G < 0.0) G = 0.0;
547 if (B < 0.0) B = 0.0;
548 if (R > 255.0) R = 255.0;
549 if (G > 255.0) G = 255.0;
550 if (B > 255.0) B = 255.0;
552 *(localDecompressed++) = (uint8_t)R;
553 *(localDecompressed++) = (uint8_t)G;
554 *(localDecompressed++) = (uint8_t)B;
560 delete[] copyDecompressed;
564 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
565 * \warning Works on all the frames at a time
567 void PixelConvert::ConvertRGBPlanesToRGBPixels()
569 uint8_t* localDecompressed = Decompressed;
570 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
571 memmove( copyDecompressed, localDecompressed, DecompressedSize );
573 int l = XSize * YSize * ZSize;
575 uint8_t* a = copyDecompressed;
576 uint8_t* b = copyDecompressed + l;
577 uint8_t* c = copyDecompressed + l + l;
579 for (int j = 0; j < l; j++)
581 *(localDecompressed++) = *(a++);
582 *(localDecompressed++) = *(b++);
583 *(localDecompressed++) = *(c++);
585 delete[] copyDecompressed;
588 bool PixelConvert::ReadAndDecompressPixelData( std::ifstream* fp )
590 ComputeDecompressedAndRGBSizes();
591 AllocateDecompressed();
592 //////////////////////////////////////////////////
593 //// First stage: get our hands on the Pixel Data.
596 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
597 "unavailable file pointer." );
601 fp->seekg( PixelOffset, std::ios_base::beg );
602 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
604 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
605 "unable to find PixelOffset in file." );
609 //////////////////////////////////////////////////
610 //// Second stage: read from disk dans decompress.
611 if ( BitsAllocated == 12 )
613 ReadAndDecompress12BitsTo16Bits( fp);
615 else if ( IsDecompressed )
617 // This problem can be found when some obvious informations are found
618 // after the field containing the image datas. In this case, these
619 // bad datas are added to the size of the image (in the PixelDataLength
620 // variable). But DecompressedSize is the right size of the image !
621 if( PixelDataLength != DecompressedSize)
623 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
624 "Mismatch between PixelConvert and DecompressedSize." );
626 if( PixelDataLength > DecompressedSize)
628 fp->read( (char*)Decompressed, DecompressedSize);
632 fp->read( (char*)Decompressed, PixelDataLength);
635 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
637 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
638 "reading of decompressed pixel data failed." );
642 else if ( IsRLELossless )
644 if ( ! ReadAndDecompressRLEFile( fp ) )
646 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
647 "RLE decompressor failed." );
653 // Default case concerns JPEG family
654 if ( ! ReadAndDecompressJPEGFile( fp ) )
656 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
657 "JPEG decompressor failed." );
662 ////////////////////////////////////////////
663 //// Third stage: twigle the bytes and bits.
664 ConvertReorderEndianity();
665 ConvertReArrangeBits();
666 ConvertHandleColor();
671 void PixelConvert::ConvertHandleColor()
673 //////////////////////////////////
674 // Deal with the color decoding i.e. handle:
675 // - R, G, B planes (as opposed to RGB pixels)
676 // - YBR (various) encodings.
677 // - LUT[s] (or "PALETTE COLOR").
679 // The classification in the color decoding schema is based on the blending
680 // of two Dicom tags values:
681 // * "Photometric Interpretation" for which we have the cases:
682 // - [Photo A] MONOCHROME[1|2] pictures,
683 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
684 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
685 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
686 // * "Planar Configuration" for which we have the cases:
687 // - [Planar 0] 0 then Pixels are already RGB
688 // - [Planar 1] 1 then we have 3 planes : R, G, B,
689 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
691 // Now in theory, one could expect some coherence when blending the above
692 // cases. For example we should not encounter files belonging at the
693 // time to case [Planar 0] and case [Photo D].
694 // Alas, this was only theory ! Because in practice some odd (read ill
695 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
696 // - "Planar Configuration" = 0,
697 // - "Photometric Interpretation" = "PALETTE COLOR".
698 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
699 // towards Dicom-non-conformance files:
700 // << whatever the "Planar Configuration" value might be, a
701 // "Photometric Interpretation" set to "PALETTE COLOR" forces
702 // a LUT intervention >>
704 // Now we are left with the following handling of the cases:
705 // - [Planar 0] OR [Photo A] no color decoding (since respectively
706 // Pixels are already RGB and monochrome pictures have no color :),
707 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
708 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
709 // - [Planar 2] OR [Photo D] requires LUT intervention.
711 if ( ! IsDecompressedRGB() )
713 // [Planar 2] OR [Photo D]: LUT intervention done outside
717 if ( PlanarConfiguration == 1 )
721 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
722 ConvertYcBcRPlanesToRGBPixels();
726 // [Planar 1] AND [Photo C]
727 ConvertRGBPlanesToRGBPixels();
732 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
733 // pixels need to be RGB-fied anyway
736 ConvertRGBPlanesToRGBPixels();
738 // In *normal *case, when planarConf is 0, pixels are already in RGB
742 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
743 * \note See comments of \ref ConvertHandleColor
745 bool PixelConvert::IsDecompressedRGB()
748 || PlanarConfiguration == 2
756 void PixelConvert::ComputeDecompressedAndRGBSizes()
758 int bitsAllocated = BitsAllocated;
759 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
760 // in this case we will expand the image to 16 bits (see
761 // \ref ReadAndDecompress12BitsTo16Bits() )
762 if ( BitsAllocated == 12 )
767 DecompressedSize = XSize * YSize * ZSize
768 * ( bitsAllocated / 8 )
772 RGBSize = 3 * DecompressedSize;
777 void PixelConvert::GrabInformationsFromHeader( Header* header )
779 // Just in case some access to a Header element requires disk access.
780 // Note: gdcmDocument::Fp is leaved open after OpenFile.
781 std::ifstream* fp = header->OpenFile();
782 // Number of Bits Allocated for storing a Pixel is defaulted to 16
783 // when absent from the header.
784 BitsAllocated = header->GetBitsAllocated();
785 if ( BitsAllocated == 0 )
790 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
791 // when absent from the header.
792 BitsStored = header->GetBitsStored();
793 if ( BitsStored == 0 )
795 BitsStored = BitsAllocated;
799 HighBitPosition = header->GetHighBitPosition();
800 if ( HighBitPosition == 0 )
802 HighBitPosition = BitsAllocated - 1;
805 XSize = header->GetXSize();
806 YSize = header->GetYSize();
807 ZSize = header->GetZSize();
808 SamplesPerPixel = header->GetSamplesPerPixel();
809 PixelSize = header->GetPixelSize();
810 PixelSign = header->IsSignedPixelData();
811 SwapCode = header->GetSwapCode();
812 TransferSyntaxType ts = header->GetTransferSyntax();
814 ( ! header->IsDicomV3() )
815 || ts == ImplicitVRLittleEndian
816 || ts == ImplicitVRLittleEndianDLXGE
817 || ts == ExplicitVRLittleEndian
818 || ts == ExplicitVRBigEndian
819 || ts == DeflatedExplicitVRLittleEndian;
820 IsJPEG2000 = header->IsJPEG2000();
821 IsJPEGLossless = header->IsJPEGLossless();
822 IsRLELossless = ( ts == RLELossless );
823 PixelOffset = header->GetPixelOffset();
824 PixelDataLength = header->GetPixelAreaLength();
825 RLEInfo = header->GetRLEInfo();
826 JPEGInfo = header->GetJPEGInfo();
828 PlanarConfiguration = header->GetPlanarConfiguration();
829 IsMonochrome = header->IsMonochrome();
830 IsPaletteColor = header->IsPaletteColor();
831 IsYBRFull = header->IsYBRFull();
833 /////////////////////////////////////////////////////////////////
835 HasLUT = header->HasLUT();
838 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
839 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
840 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
842 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
843 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
844 // Document::Document() ], the loading of the value (content) of a
845 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
846 // loaded). Hence, we first try to obtain the LUTs data from the header
847 // and when this fails we read the LUTs data directely from disk.
848 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
849 /// We should NOT bypass the [Bin|Val]Entry class. Instead
850 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
851 /// (e.g. BinEntry::GetBinArea()) should force disk access from
852 /// within the [Bin|Val]Entry class itself. The only problem
853 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
854 /// parsed from. Fix that. FIXME.
857 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
860 // Read the Lut Data from disk
861 DocEntry* lutRedDataEntry = header->GetDocEntryByNumber( 0x0028,
863 LutRedData = new uint8_t[ lutRedDataEntry->GetLength() ];
864 fp->seekg( lutRedDataEntry->GetOffset() ,std::ios_base::beg );
865 fp->read( (char*)LutRedData, (size_t)lutRedDataEntry->GetLength());
866 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
868 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
869 "unable to read red LUT data" );
875 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
878 // Read the Lut Data from disk
879 DocEntry* lutGreenDataEntry = header->GetDocEntryByNumber( 0x0028,
881 LutGreenData = new uint8_t[ lutGreenDataEntry->GetLength() ];
882 fp->seekg( lutGreenDataEntry->GetOffset() , std::ios_base::beg );
883 fp->read( (char*)LutGreenData, (size_t)lutGreenDataEntry->GetLength() );
884 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
886 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
887 "unable to read green LUT data" );
893 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
896 // Read the Lut Data from disk
897 DocEntry* lutBlueDataEntry = header->GetDocEntryByNumber( 0x0028,
899 LutBlueData = new uint8_t[ lutBlueDataEntry->GetLength() ];
900 fp->seekg( lutBlueDataEntry->GetOffset() , std::ios_base::beg );
901 fp->read( (char*)LutBlueData, (size_t)lutBlueDataEntry->GetLength() );
902 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
904 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
905 "unable to read blue LUT data" );
911 if(fp) header->CloseFile();
915 * \brief Build Red/Green/Blue/Alpha LUT from Header
916 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
917 * and (0028,1101),(0028,1102),(0028,1102)
918 * - xxx Palette Color Lookup Table Descriptor - are found
919 * and (0028,1201),(0028,1202),(0028,1202)
920 * - xxx Palette Color Lookup Table Data - are found
921 * \warning does NOT deal with :
922 * 0028 1100 Gray Lookup Table Descriptor (Retired)
923 * 0028 1221 Segmented Red Palette Color Lookup Table Data
924 * 0028 1222 Segmented Green Palette Color Lookup Table Data
925 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
926 * no known Dicom reader deals with them :-(
927 * @return a RGBA Lookup Table
929 void PixelConvert::BuildLUTRGBA()
936 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
938 if ( ! IsPaletteColor )
943 if ( LutRedDescriptor == GDCM_UNFOUND
944 || LutGreenDescriptor == GDCM_UNFOUND
945 || LutBlueDescriptor == GDCM_UNFOUND )
950 ////////////////////////////////////////////
951 // Extract the info from the LUT descriptors
952 int lengthR; // Red LUT length in Bytes
953 int debR; // Subscript of the first Lut Value
954 int nbitsR; // Lut item size (in Bits)
955 int nbRead = sscanf( LutRedDescriptor.c_str(),
957 &lengthR, &debR, &nbitsR );
960 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong red LUT descriptor");
963 int lengthG; // Green LUT length in Bytes
964 int debG; // Subscript of the first Lut Value
965 int nbitsG; // Lut item size (in Bits)
966 nbRead = sscanf( LutGreenDescriptor.c_str(),
968 &lengthG, &debG, &nbitsG );
971 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong green LUT descriptor");
974 int lengthB; // Blue LUT length in Bytes
975 int debB; // Subscript of the first Lut Value
976 int nbitsB; // Lut item size (in Bits)
977 nbRead = sscanf( LutRedDescriptor.c_str(),
979 &lengthB, &debB, &nbitsB );
982 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong blue LUT descriptor");
985 ////////////////////////////////////////////////////////
986 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
991 ////////////////////////////////////////////////
992 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
993 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
998 memset( LutRGBA, 0, 1024 );
1001 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1003 // when LUT item size is different than pixel size
1004 mult = 2; // high byte must be = low byte
1008 // See PS 3.3-2003 C.11.1.1.2 p 619
1012 // if we get a black image, let's just remove the '+1'
1013 // from 'i*mult+1' and check again
1014 // if it works, we shall have to check the 3 Palettes
1015 // to see which byte is ==0 (first one, or second one)
1017 // We give up the checking to avoid some (useless ?)overhead
1018 // (optimistic asumption)
1020 uint8_t* a = LutRGBA + 0;
1021 for( i=0; i < lengthR; ++i )
1023 *a = LutRedData[i*mult+1];
1028 for( i=0; i < lengthG; ++i)
1030 *a = LutGreenData[i*mult+1];
1035 for(i=0; i < lengthB; ++i)
1037 *a = LutBlueData[i*mult+1];
1042 for(i=0; i < 256; ++i)
1044 *a = 1; // Alpha component
1050 * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1052 bool PixelConvert::BuildRGBImage()
1056 // The job is already done.
1060 if ( ! Decompressed )
1062 // The job can't be done
1069 // The job can't be done
1075 uint8_t* localRGB = RGB;
1076 for (size_t i = 0; i < DecompressedSize; ++i )
1078 int j = Decompressed[i] * 4;
1079 *localRGB++ = LutRGBA[j];
1080 *localRGB++ = LutRGBA[j+1];
1081 *localRGB++ = LutRGBA[j+2];
1087 * \brief Print self.
1088 * @param indent Indentation string to be prepended during printing.
1089 * @param os Stream to print to.
1091 void PixelConvert::Print( std::string indent, std::ostream &os )
1094 << "--- Pixel information -------------------------"
1097 << "Pixel Data: offset " << PixelOffset
1098 << " x" << std::hex << PixelOffset << std::dec
1099 << " length " << PixelDataLength
1100 << " x" << std::hex << PixelDataLength << std::dec
1103 if ( IsRLELossless )
1107 RLEInfo->Print( indent, os );
1111 dbg.Verbose(0, "PixelConvert::Print: set as RLE file "
1112 "but NO RLEinfo present.");
1116 if ( IsJPEG2000 || IsJPEGLossless )
1120 JPEGInfo->Print( indent, os );
1124 dbg.Verbose(0, "PixelConvert::Print: set as JPEG file "
1125 "but NO JPEGinfo present.");
1130 } // end namespace gdcm
1132 // NOTES on File internal calls
1134 // ---> GetImageData
1135 // ---> GetImageDataIntoVector
1136 // |---> GetImageDataIntoVectorRaw
1137 // | lut intervention
1139 // ---> GetImageDataRaw
1140 // ---> GetImageDataIntoVectorRaw