1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/11/25 10:24:34 $
7 Version: $Revision: 1.33 $
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 is already made by
591 // ::GrabInformationsFromHeader. So, the structure sizes are
595 //////////////////////////////////////////////////
596 //// First stage: get our hands on the Pixel Data.
599 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
600 "unavailable file pointer." );
604 fp->seekg( PixelOffset, std::ios_base::beg );
605 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
607 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
608 "unable to find PixelOffset in file." );
612 AllocateDecompressed();
614 //////////////////////////////////////////////////
615 //// Second stage: read from disk dans decompress.
616 if ( BitsAllocated == 12 )
618 ReadAndDecompress12BitsTo16Bits( fp);
620 else if ( IsDecompressed )
622 // This problem can be found when some obvious informations are found
623 // after the field containing the image datas. In this case, these
624 // bad datas are added to the size of the image (in the PixelDataLength
625 // variable). But DecompressedSize is the right size of the image !
626 if( PixelDataLength != DecompressedSize)
628 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
629 "Mismatch between PixelConvert and DecompressedSize." );
631 if( PixelDataLength > DecompressedSize)
633 fp->read( (char*)Decompressed, DecompressedSize);
637 fp->read( (char*)Decompressed, PixelDataLength);
640 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
642 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
643 "reading of decompressed pixel data failed." );
647 else if ( IsRLELossless )
649 if ( ! ReadAndDecompressRLEFile( fp ) )
651 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
652 "RLE decompressor failed." );
658 // Default case concerns JPEG family
659 if ( ! ReadAndDecompressJPEGFile( fp ) )
661 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
662 "JPEG decompressor failed." );
667 ////////////////////////////////////////////
668 //// Third stage: twigle the bytes and bits.
669 ConvertReorderEndianity();
670 ConvertReArrangeBits();
671 ConvertHandleColor();
676 void PixelConvert::ConvertHandleColor()
678 //////////////////////////////////
679 // Deal with the color decoding i.e. handle:
680 // - R, G, B planes (as opposed to RGB pixels)
681 // - YBR (various) encodings.
682 // - LUT[s] (or "PALETTE COLOR").
684 // The classification in the color decoding schema is based on the blending
685 // of two Dicom tags values:
686 // * "Photometric Interpretation" for which we have the cases:
687 // - [Photo A] MONOCHROME[1|2] pictures,
688 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
689 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
690 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
691 // * "Planar Configuration" for which we have the cases:
692 // - [Planar 0] 0 then Pixels are already RGB
693 // - [Planar 1] 1 then we have 3 planes : R, G, B,
694 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
696 // Now in theory, one could expect some coherence when blending the above
697 // cases. For example we should not encounter files belonging at the
698 // time to case [Planar 0] and case [Photo D].
699 // Alas, this was only theory ! Because in practice some odd (read ill
700 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
701 // - "Planar Configuration" = 0,
702 // - "Photometric Interpretation" = "PALETTE COLOR".
703 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
704 // towards Dicom-non-conformance files:
705 // << whatever the "Planar Configuration" value might be, a
706 // "Photometric Interpretation" set to "PALETTE COLOR" forces
707 // a LUT intervention >>
709 // Now we are left with the following handling of the cases:
710 // - [Planar 0] OR [Photo A] no color decoding (since respectively
711 // Pixels are already RGB and monochrome pictures have no color :),
712 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
713 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
714 // - [Planar 2] OR [Photo D] requires LUT intervention.
716 if ( ! IsDecompressedRGB() )
718 // [Planar 2] OR [Photo D]: LUT intervention done outside
722 if ( PlanarConfiguration == 1 )
726 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
727 ConvertYcBcRPlanesToRGBPixels();
731 // [Planar 1] AND [Photo C]
732 ConvertRGBPlanesToRGBPixels();
737 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
738 // pixels need to be RGB-fied anyway
741 ConvertRGBPlanesToRGBPixels();
743 // In *normal *case, when planarConf is 0, pixels are already in RGB
747 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
748 * \note See comments of \ref ConvertHandleColor
750 bool PixelConvert::IsDecompressedRGB()
753 || PlanarConfiguration == 2
761 void PixelConvert::ComputeDecompressedAndRGBSizes()
763 int bitsAllocated = BitsAllocated;
764 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
765 // in this case we will expand the image to 16 bits (see
766 // \ref ReadAndDecompress12BitsTo16Bits() )
767 if ( BitsAllocated == 12 )
772 DecompressedSize = XSize * YSize * ZSize
773 * ( bitsAllocated / 8 )
777 RGBSize = 3 * DecompressedSize;
781 RGBSize = DecompressedSize;
785 void PixelConvert::GrabInformationsFromHeader( Header* header )
787 // Just in case some access to a Header element requires disk access.
788 // Note: gdcmDocument::Fp is leaved open after OpenFile.
789 std::ifstream* fp = header->OpenFile();
790 // Number of Bits Allocated for storing a Pixel is defaulted to 16
791 // when absent from the header.
792 BitsAllocated = header->GetBitsAllocated();
793 if ( BitsAllocated == 0 )
798 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
799 // when absent from the header.
800 BitsStored = header->GetBitsStored();
801 if ( BitsStored == 0 )
803 BitsStored = BitsAllocated;
807 HighBitPosition = header->GetHighBitPosition();
808 if ( HighBitPosition == 0 )
810 HighBitPosition = BitsAllocated - 1;
813 XSize = header->GetXSize();
814 YSize = header->GetYSize();
815 ZSize = header->GetZSize();
816 SamplesPerPixel = header->GetSamplesPerPixel();
817 PixelSize = header->GetPixelSize();
818 PixelSign = header->IsSignedPixelData();
819 SwapCode = header->GetSwapCode();
820 TransferSyntaxType ts = header->GetTransferSyntax();
822 ( ! header->IsDicomV3() )
823 || ts == ImplicitVRLittleEndian
824 || ts == ImplicitVRLittleEndianDLXGE
825 || ts == ExplicitVRLittleEndian
826 || ts == ExplicitVRBigEndian
827 || ts == DeflatedExplicitVRLittleEndian;
828 IsJPEG2000 = header->IsJPEG2000();
829 IsJPEGLossless = header->IsJPEGLossless();
830 IsRLELossless = ( ts == RLELossless );
831 PixelOffset = header->GetPixelOffset();
832 PixelDataLength = header->GetPixelAreaLength();
833 RLEInfo = header->GetRLEInfo();
834 JPEGInfo = header->GetJPEGInfo();
836 PlanarConfiguration = header->GetPlanarConfiguration();
837 IsMonochrome = header->IsMonochrome();
838 IsPaletteColor = header->IsPaletteColor();
839 IsYBRFull = header->IsYBRFull();
841 /////////////////////////////////////////////////////////////////
843 HasLUT = header->HasLUT();
846 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
847 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
848 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
850 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
851 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
852 // Document::Document() ], the loading of the value (content) of a
853 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
854 // loaded). Hence, we first try to obtain the LUTs data from the header
855 // and when this fails we read the LUTs data directely from disk.
856 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
857 /// We should NOT bypass the [Bin|Val]Entry class. Instead
858 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
859 /// (e.g. BinEntry::GetBinArea()) should force disk access from
860 /// within the [Bin|Val]Entry class itself. The only problem
861 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
862 /// parsed from. Fix that. FIXME.
865 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
868 // Read the Lut Data from disk
869 DocEntry* lutRedDataEntry = header->GetDocEntryByNumber( 0x0028,
871 LutRedData = new uint8_t[ lutRedDataEntry->GetLength() ];
872 fp->seekg( lutRedDataEntry->GetOffset() ,std::ios_base::beg );
873 fp->read( (char*)LutRedData, (size_t)lutRedDataEntry->GetLength());
874 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
876 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
877 "unable to read red LUT data" );
882 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
885 // Read the Lut Data from disk
886 DocEntry* lutGreenDataEntry = header->GetDocEntryByNumber( 0x0028,
888 LutGreenData = new uint8_t[ lutGreenDataEntry->GetLength() ];
889 fp->seekg( lutGreenDataEntry->GetOffset() , std::ios_base::beg );
890 fp->read( (char*)LutGreenData, (size_t)lutGreenDataEntry->GetLength() );
891 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
893 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
894 "unable to read green LUT data" );
899 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
902 // Read the Lut Data from disk
903 DocEntry* lutBlueDataEntry = header->GetDocEntryByNumber( 0x0028,
905 LutBlueData = new uint8_t[ lutBlueDataEntry->GetLength() ];
906 fp->seekg( lutBlueDataEntry->GetOffset() , std::ios_base::beg );
907 fp->read( (char*)LutBlueData, (size_t)lutBlueDataEntry->GetLength() );
908 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
910 dbg.Verbose(0, "PixelConvert::GrabInformationsFromHeader: "
911 "unable to read blue LUT data" );
916 ComputeDecompressedAndRGBSizes();
925 * \brief Build Red/Green/Blue/Alpha LUT from Header
926 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
927 * and (0028,1101),(0028,1102),(0028,1102)
928 * - xxx Palette Color Lookup Table Descriptor - are found
929 * and (0028,1201),(0028,1202),(0028,1202)
930 * - xxx Palette Color Lookup Table Data - are found
931 * \warning does NOT deal with :
932 * 0028 1100 Gray Lookup Table Descriptor (Retired)
933 * 0028 1221 Segmented Red Palette Color Lookup Table Data
934 * 0028 1222 Segmented Green Palette Color Lookup Table Data
935 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
936 * no known Dicom reader deals with them :-(
937 * @return a RGBA Lookup Table
939 void PixelConvert::BuildLUTRGBA()
946 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
948 if ( ! IsPaletteColor )
953 if ( LutRedDescriptor == GDCM_UNFOUND
954 || LutGreenDescriptor == GDCM_UNFOUND
955 || LutBlueDescriptor == GDCM_UNFOUND )
960 ////////////////////////////////////////////
961 // Extract the info from the LUT descriptors
962 int lengthR; // Red LUT length in Bytes
963 int debR; // Subscript of the first Lut Value
964 int nbitsR; // Lut item size (in Bits)
965 int nbRead = sscanf( LutRedDescriptor.c_str(),
967 &lengthR, &debR, &nbitsR );
970 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong red LUT descriptor");
973 int lengthG; // Green LUT length in Bytes
974 int debG; // Subscript of the first Lut Value
975 int nbitsG; // Lut item size (in Bits)
976 nbRead = sscanf( LutGreenDescriptor.c_str(),
978 &lengthG, &debG, &nbitsG );
981 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong green LUT descriptor");
984 int lengthB; // Blue LUT length in Bytes
985 int debB; // Subscript of the first Lut Value
986 int nbitsB; // Lut item size (in Bits)
987 nbRead = sscanf( LutRedDescriptor.c_str(),
989 &lengthB, &debB, &nbitsB );
992 dbg.Verbose(0, "PixelConvert::BuildLUTRGBA: wrong blue LUT descriptor");
995 ////////////////////////////////////////////////////////
996 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1001 ////////////////////////////////////////////////
1002 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1003 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1008 memset( LutRGBA, 0, 1024 );
1011 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1013 // when LUT item size is different than pixel size
1014 mult = 2; // high byte must be = low byte
1018 // See PS 3.3-2003 C.11.1.1.2 p 619
1022 // if we get a black image, let's just remove the '+1'
1023 // from 'i*mult+1' and check again
1024 // if it works, we shall have to check the 3 Palettes
1025 // to see which byte is ==0 (first one, or second one)
1027 // We give up the checking to avoid some (useless ?)overhead
1028 // (optimistic asumption)
1030 uint8_t* a = LutRGBA + 0;
1031 for( i=0; i < lengthR; ++i )
1033 *a = LutRedData[i*mult+1];
1038 for( i=0; i < lengthG; ++i)
1040 *a = LutGreenData[i*mult+1];
1045 for(i=0; i < lengthB; ++i)
1047 *a = LutBlueData[i*mult+1];
1052 for(i=0; i < 256; ++i)
1054 *a = 1; // Alpha component
1060 * \brief Build the RGB image from the Decompressed imagage and the LUTs.
1062 bool PixelConvert::BuildRGBImage()
1066 // The job is already done.
1070 if ( ! Decompressed )
1072 // The job can't be done
1079 // The job can't be done
1085 uint8_t* localRGB = RGB;
1086 for (size_t i = 0; i < DecompressedSize; ++i )
1088 int j = Decompressed[i] * 4;
1089 *localRGB++ = LutRGBA[j];
1090 *localRGB++ = LutRGBA[j+1];
1091 *localRGB++ = LutRGBA[j+2];
1097 * \brief Print self.
1098 * @param indent Indentation string to be prepended during printing.
1099 * @param os Stream to print to.
1101 void PixelConvert::Print( std::string indent, std::ostream &os )
1104 << "--- Pixel information -------------------------"
1107 << "Pixel Data: offset " << PixelOffset
1108 << " x" << std::hex << PixelOffset << std::dec
1109 << " length " << PixelDataLength
1110 << " x" << std::hex << PixelDataLength << std::dec
1113 if ( IsRLELossless )
1117 RLEInfo->Print( indent, os );
1121 dbg.Verbose(0, "PixelConvert::Print: set as RLE file "
1122 "but NO RLEinfo present.");
1126 if ( IsJPEG2000 || IsJPEGLossless )
1130 JPEGInfo->Print( indent, os );
1134 dbg.Verbose(0, "PixelConvert::Print: set as JPEG file "
1135 "but NO JPEGinfo present.");
1140 } // end namespace gdcm
1142 // NOTES on File internal calls
1144 // ---> GetImageData
1145 // ---> GetImageDataIntoVector
1146 // |---> GetImageDataIntoVectorRaw
1147 // | lut intervention
1149 // ---> GetImageDataRaw
1150 // ---> GetImageDataIntoVectorRaw