1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2004/12/16 11:37:03 $
7 Version: $Revision: 1.12 $
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"
33 #include <stdio.h> //for sscanf
37 #define str2num(str, typeNum) *((typeNum *)(str))
39 // For JPEG 2000, body in file gdcmJpeg2000.cxx
40 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
42 #define JOCTET uint8_t
43 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
44 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
45 bool gdcm_read_JPEG_memory8 (const JOCTET* buffer, const size_t buflen,
47 size_t *howManyRead, size_t *howManyWritten);
49 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
50 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
51 bool gdcm_read_JPEG_memory12 (const JOCTET *buffer, const size_t buflen,
53 size_t *howManyRead, size_t *howManyWritten);
55 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
56 // Beware this is misleading there is no 16bits DCT algorithm, only
57 // jpeg lossless compression exist in 16bits.
58 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
59 bool gdcm_read_JPEG_memory16 (const JOCTET *buffer, const size_t buflen,
61 size_t *howManyRead, size_t *howManyWritten);
64 //-----------------------------------------------------------------------------
65 // Constructor / Destructor
66 PixelReadConvert::PixelReadConvert()
78 void PixelReadConvert::Squeeze()
99 PixelReadConvert::~PixelReadConvert()
104 void PixelReadConvert::AllocateRGB()
109 RGB = new uint8_t[ RGBSize ];
112 void PixelReadConvert::AllocateRaw()
117 Raw = new uint8_t[ RawSize ];
121 * \brief Read from file a 12 bits per pixel image and decompress it
122 * into a 16 bits per pixel image.
124 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
125 throw ( FormatError )
127 int nbPixels = XSize * YSize;
128 uint16_t* localDecompres = (uint16_t*)Raw;
130 for( int p = 0; p < nbPixels; p += 2 )
134 fp->read( (char*)&b0, 1);
135 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
137 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
138 "Unfound first block" );
141 fp->read( (char*)&b1, 1 );
142 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
144 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
145 "Unfound second block" );
148 fp->read( (char*)&b2, 1 );
149 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
151 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
152 "Unfound second block" );
155 // Two steps are necessary to please VC++
157 // 2 pixels 12bit = [0xABCDEF]
158 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
160 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
162 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
164 /// \todo JPR Troubles expected on Big-Endian processors ?
169 * \brief Try to deal with RLE 16 Bits.
170 * We assume the RLE has allready been parsed and loaded in
171 * Raw (through \ref ReadAndDecompressJPEGFile ).
172 * We here need to make 16 Bits Pixels from Low Byte and
173 * High Byte 'Planes'...(for what it may mean)
176 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
178 size_t pixelNumber = XSize * YSize;
179 size_t rawSize = XSize * YSize * NumberOfFrames;
181 // We assumed Raw contains the decoded RLE pixels but as
182 // 8 bits per pixel. In order to convert those pixels to 16 bits
183 // per pixel we cannot work in place within Raw and hence
184 // we copy it in a safe place, say copyRaw.
186 uint8_t* copyRaw = new uint8_t[ rawSize * 2 ];
187 memmove( copyRaw, Raw, rawSize * 2 );
190 uint8_t* a = copyRaw;
191 uint8_t* b = a + pixelNumber;
193 for ( int i = 0; i < NumberOfFrames; i++ )
195 for ( unsigned int j = 0; j < pixelNumber; j++ )
204 /// \todo check that operator new []didn't fail, and sometimes return false
209 * \brief Implementation of the RLE decoding algorithm for decompressing
210 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
211 * @param subRaw Sub region of \ref Raw where the de
212 * decoded fragment should be placed.
213 * @param fragmentSize The length of the binary fragment as found on the disk.
214 * @param RawSegmentSize The expected length of the fragment ONCE
216 * @param fp File Pointer: on entry the position should be the one of
217 * the fragment to be decoded.
219 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t* subRaw,
225 long numberOfOutputBytes = 0;
226 long numberOfReadBytes = 0;
228 while( numberOfOutputBytes < RawSegmentSize )
230 fp->read( (char*)&count, 1 );
231 numberOfReadBytes += 1;
233 // Note: count <= 127 comparison is always true due to limited range
234 // of data type int8_t [since the maximum of an exact width
235 // signed integer of width N is 2^(N-1) - 1, which for int8_t
238 fp->read( (char*)subRaw, count + 1);
239 numberOfReadBytes += count + 1;
241 numberOfOutputBytes += count + 1;
245 if ( ( count <= -1 ) && ( count >= -127 ) )
248 fp->read( (char*)&newByte, 1);
249 numberOfReadBytes += 1;
250 for( int i = 0; i < -count + 1; i++ )
254 subRaw += -count + 1;
255 numberOfOutputBytes += -count + 1;
258 // if count = 128 output nothing
260 if ( numberOfReadBytes > fragmentSize )
262 dbg.Verbose(0, "PixelReadConvert::ReadAndDecompressRLEFragment: we "
263 "read more bytes than the segment size.");
271 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
272 * Dicom encapsulated file and decompress it.
273 * @param fp already open File Pointer
274 * at which the pixel data should be copied
277 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
279 uint8_t* subRaw = Raw;
280 long RawSegmentSize = XSize * YSize;
282 // Loop on the frame[s]
283 for( RLEFramesInfo::RLEFrameList::iterator
284 it = RLEInfo->Frames.begin();
285 it != RLEInfo->Frames.end();
288 // Loop on the fragments
289 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
291 fp->seekg( (*it)->Offset[k] , std::ios::beg );
292 (void)ReadAndDecompressRLEFragment( subRaw,
296 subRaw += RawSegmentSize;
300 if ( BitsAllocated == 16 )
302 // Try to deal with RLE 16 Bits
303 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
310 * \brief Swap the bytes, according to \ref SwapCode.
312 void PixelReadConvert::ConvertSwapZone()
316 if( BitsAllocated == 16 )
318 uint16_t* im16 = (uint16_t*)Raw;
329 for( i = 0; i < RawSize / 2; i++ )
331 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
335 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
336 "(16 bits) not allowed." );
339 else if( BitsAllocated == 32 )
344 uint32_t* im32 = (uint32_t*)Raw;
351 for( i = 0; i < RawSize / 4; i++ )
353 low = im32[i] & 0x0000ffff; // 4321
354 high = im32[i] >> 16;
355 high = ( high >> 8 ) | ( high << 8 );
356 low = ( low >> 8 ) | ( low << 8 );
358 im32[i] = ( s32 << 16 ) | high;
362 for( i = 0; i < RawSize / 4; i++ )
364 low = im32[i] & 0x0000ffff; // 2143
365 high = im32[i] >> 16;
366 high = ( high >> 8 ) | ( high << 8 );
367 low = ( low >> 8 ) | ( low << 8 );
369 im32[i] = ( s32 << 16 ) | low;
373 for( i = 0; i < RawSize / 4; i++ )
375 low = im32[i] & 0x0000ffff; // 3412
376 high = im32[i] >> 16;
378 im32[i] = ( s32 << 16 ) | high;
382 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
383 "(32 bits) not allowed." );
389 * \brief Deal with endianity i.e. re-arange bytes inside the integer
391 void PixelReadConvert::ConvertReorderEndianity()
393 if ( BitsAllocated != 8 )
398 // Special kludge in order to deal with xmedcon broken images:
399 if ( ( BitsAllocated == 16 )
400 && ( BitsStored < BitsAllocated )
403 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
404 uint16_t *deb = (uint16_t *)Raw;
405 for(int i = 0; i<l; i++)
418 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
419 * file and decompress it. This funciton assumes that each
420 * jpeg fragment contains a whole frame (jpeg file).
421 * @param fp File Pointer
424 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream* fp )
426 uint8_t* localRaw = Raw;
427 // Loop on the fragment[s]
428 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
429 it = JPEGInfo->Fragments.begin();
430 it != JPEGInfo->Fragments.end();
433 fp->seekg( (*it)->Offset, std::ios::beg);
435 if ( BitsStored == 8)
437 // JPEG Lossy : call to IJG 6b
438 if ( ! gdcm_read_JPEG_file8( fp, localRaw ) )
443 else if ( BitsStored <= 12)
445 // Reading Fragment pixels
446 if ( ! gdcm_read_JPEG_file12 ( fp, localRaw ) )
451 else if ( BitsStored <= 16)
453 // Reading Fragment pixels
454 if ( ! gdcm_read_JPEG_file16 ( fp, localRaw ) )
458 //assert( IsJPEGLossless );
462 // other JPEG lossy not supported
463 dbg.Error("PixelReadConvert::ReadAndDecompressJPEGFile: unknown "
464 "jpeg lossy compression ");
468 // Advance to next free location in Raw
469 // for next fragment decompression (if any)
470 int length = XSize * YSize * SamplesPerPixel;
471 int numberBytes = BitsAllocated / 8;
473 localRaw += length * numberBytes;
479 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
480 * file and decompress it. This function assumes that the dicom
481 * image is a single frame split into several JPEG fragments.
482 * Those fragments will be glued together into a memory buffer
484 * @param fp File Pointer
487 bool PixelReadConvert::
488 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream* fp )
490 // Loop on the fragment[s] to get total length
491 size_t totalLength = 0;
492 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
493 for( it = JPEGInfo->Fragments.begin();
494 it != JPEGInfo->Fragments.end();
497 totalLength += (*it)->Length;
500 // Concatenate the jpeg fragments into a local buffer
501 JOCTET *buffer = new JOCTET [totalLength];
504 // Loop on the fragment[s]
505 for( it = JPEGInfo->Fragments.begin();
506 it != JPEGInfo->Fragments.end();
509 fp->seekg( (*it)->Offset, std::ios::beg);
510 size_t len = (*it)->Length;
511 fp->read((char *)p,len);
515 size_t howManyRead = 0;
516 size_t howManyWritten = 0;
518 if ( BitsStored == 8)
520 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
521 &howManyRead, &howManyWritten ) )
524 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 "
530 else if ( BitsStored <= 12)
532 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
533 &howManyRead, &howManyWritten ) )
536 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 "
542 else if ( BitsStored <= 16)
545 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
546 &howManyRead, &howManyWritten ) )
549 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 "
557 // other JPEG lossy not supported
558 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
559 "jpeg lossy compression ");
571 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
572 * file and decompress it. This function handles the generic
573 * and complex case where the DICOM contains several frames,
574 * and some of the frames are possibly split into several JPEG
576 * @param fp File Pointer
579 bool PixelReadConvert::
580 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream* fp )
582 // Loop on the fragment[s] to get total length
583 size_t totalLength = 0;
584 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
585 for( it = JPEGInfo->Fragments.begin();
586 it != JPEGInfo->Fragments.end();
589 totalLength += (*it)->Length;
592 // Concatenate the jpeg fragments into a local buffer
593 JOCTET *buffer = new JOCTET [totalLength];
596 // Loop on the fragment[s]
597 for( it = JPEGInfo->Fragments.begin();
598 it != JPEGInfo->Fragments.end();
601 fp->seekg( (*it)->Offset, std::ios::beg);
602 size_t len = (*it)->Length;
603 fp->read((char *)p,len);
607 size_t howManyRead = 0;
608 size_t howManyWritten = 0;
609 size_t fragmentLength = 0;
611 for( it = JPEGInfo->Fragments.begin() ;
612 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
615 fragmentLength += (*it)->Length;
617 if (howManyRead > fragmentLength) continue;
619 if ( BitsStored == 8)
621 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
623 &howManyRead, &howManyWritten ) )
625 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 ");
630 else if ( BitsStored <= 12)
633 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
635 &howManyRead, &howManyWritten ) )
637 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 ");
642 else if ( BitsStored <= 16)
645 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
647 &howManyRead, &howManyWritten ) )
649 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 ");
656 // other JPEG lossy not supported
657 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
658 "jpeg lossy compression ");
663 if (howManyRead < fragmentLength)
664 howManyRead = fragmentLength;
674 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
675 * file and decompress it.
676 * @param fp File Pointer
679 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
683 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
684 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
688 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
690 // we have one frame split into several fragments
691 // we will pack those fragments into a single buffer and
693 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
695 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
697 // suppose each fragment is a frame
698 return ReadAndDecompressJPEGFramesFromFile( fp );
702 // The dicom image contains frames containing fragments of images
703 // a more complex algorithm :-)
704 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
709 * \brief Re-arrange the bits within the bytes.
712 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
714 if ( BitsStored != BitsAllocated )
716 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
717 if ( BitsAllocated == 16 )
719 uint16_t mask = 0xffff;
720 mask = mask >> ( BitsAllocated - BitsStored );
721 uint16_t* deb = (uint16_t*)Raw;
722 for(int i = 0; i<l; i++)
724 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
728 else if ( BitsAllocated == 32 )
730 uint32_t mask = 0xffffffff;
731 mask = mask >> ( BitsAllocated - BitsStored );
732 uint32_t* deb = (uint32_t*)Raw;
733 for(int i = 0; i<l; i++)
735 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
741 dbg.Verbose(0, "PixelReadConvert::ConvertReArrangeBits: weird image");
742 throw FormatError( "PixelReadConvert::ConvertReArrangeBits()",
750 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
751 * \warning Works on all the frames at a time
753 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
755 uint8_t* localRaw = Raw;
756 uint8_t* copyRaw = new uint8_t[ RawSize ];
757 memmove( copyRaw, localRaw, RawSize );
759 // to see the tricks about YBR_FULL, YBR_FULL_422,
760 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
761 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
762 // and be *very* affraid
764 int l = XSize * YSize;
765 int nbFrames = ZSize;
767 uint8_t* a = copyRaw;
768 uint8_t* b = copyRaw + l;
769 uint8_t* c = copyRaw + l + l;
772 /// \todo : Replace by the 'well known' integer computation
773 /// counterpart. Refer to
774 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
775 /// for code optimisation.
777 for ( int i = 0; i < nbFrames; i++ )
779 for ( int j = 0; j < l; j++ )
781 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
782 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
783 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
785 if (R < 0.0) R = 0.0;
786 if (G < 0.0) G = 0.0;
787 if (B < 0.0) B = 0.0;
788 if (R > 255.0) R = 255.0;
789 if (G > 255.0) G = 255.0;
790 if (B > 255.0) B = 255.0;
792 *(localRaw++) = (uint8_t)R;
793 *(localRaw++) = (uint8_t)G;
794 *(localRaw++) = (uint8_t)B;
804 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
805 * \warning Works on all the frames at a time
807 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
809 uint8_t* localRaw = Raw;
810 uint8_t* copyRaw = new uint8_t[ RawSize ];
811 memmove( copyRaw, localRaw, RawSize );
813 int l = XSize * YSize * ZSize;
815 uint8_t* a = copyRaw;
816 uint8_t* b = copyRaw + l;
817 uint8_t* c = copyRaw + l + l;
819 for (int j = 0; j < l; j++)
821 *(localRaw++) = *(a++);
822 *(localRaw++) = *(b++);
823 *(localRaw++) = *(c++);
828 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream* fp )
830 // ComputeRawAndRGBSizes is already made by
831 // ::GrabInformationsFromHeader. So, the structure sizes are
835 //////////////////////////////////////////////////
836 //// First stage: get our hands on the Pixel Data.
839 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
840 "unavailable file pointer." );
844 fp->seekg( PixelOffset, std::ios::beg );
845 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
847 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
848 "unable to find PixelOffset in file." );
854 //////////////////////////////////////////////////
855 //// Second stage: read from disk dans decompress.
856 if ( BitsAllocated == 12 )
858 ReadAndDecompress12BitsTo16Bits( fp);
862 // This problem can be found when some obvious informations are found
863 // after the field containing the image datas. In this case, these
864 // bad datas are added to the size of the image (in the PixelDataLength
865 // variable). But RawSize is the right size of the image !
866 if( PixelDataLength != RawSize)
868 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
869 "Mismatch between PixelReadConvert and RawSize." );
871 if( PixelDataLength > RawSize)
873 fp->read( (char*)Raw, RawSize);
877 fp->read( (char*)Raw, PixelDataLength);
880 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
882 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
883 "reading of Raw pixel data failed." );
887 else if ( IsRLELossless )
889 if ( ! ReadAndDecompressRLEFile( fp ) )
891 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
892 "RLE decompressor failed." );
898 // Default case concerns JPEG family
899 if ( ! ReadAndDecompressJPEGFile( fp ) )
901 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
902 "JPEG decompressor failed." );
907 ////////////////////////////////////////////
908 //// Third stage: twigle the bytes and bits.
909 ConvertReorderEndianity();
910 ConvertReArrangeBits();
911 ConvertHandleColor();
916 void PixelReadConvert::ConvertHandleColor()
918 //////////////////////////////////
919 // Deal with the color decoding i.e. handle:
920 // - R, G, B planes (as opposed to RGB pixels)
921 // - YBR (various) encodings.
922 // - LUT[s] (or "PALETTE COLOR").
924 // The classification in the color decoding schema is based on the blending
925 // of two Dicom tags values:
926 // * "Photometric Interpretation" for which we have the cases:
927 // - [Photo A] MONOCHROME[1|2] pictures,
928 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
929 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
930 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
931 // * "Planar Configuration" for which we have the cases:
932 // - [Planar 0] 0 then Pixels are already RGB
933 // - [Planar 1] 1 then we have 3 planes : R, G, B,
934 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
936 // Now in theory, one could expect some coherence when blending the above
937 // cases. For example we should not encounter files belonging at the
938 // time to case [Planar 0] and case [Photo D].
939 // Alas, this was only theory ! Because in practice some odd (read ill
940 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
941 // - "Planar Configuration" = 0,
942 // - "Photometric Interpretation" = "PALETTE COLOR".
943 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
944 // towards Dicom-non-conformance files:
945 // << whatever the "Planar Configuration" value might be, a
946 // "Photometric Interpretation" set to "PALETTE COLOR" forces
947 // a LUT intervention >>
949 // Now we are left with the following handling of the cases:
950 // - [Planar 0] OR [Photo A] no color decoding (since respectively
951 // Pixels are already RGB and monochrome pictures have no color :),
952 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
953 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
954 // - [Planar 2] OR [Photo D] requires LUT intervention.
958 // [Planar 2] OR [Photo D]: LUT intervention done outside
962 if ( PlanarConfiguration == 1 )
966 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
967 ConvertYcBcRPlanesToRGBPixels();
971 // [Planar 1] AND [Photo C]
972 ConvertRGBPlanesToRGBPixels();
977 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
978 // pixels need to be RGB-fied anyway
981 ConvertRGBPlanesToRGBPixels();
983 // In *normal *case, when planarConf is 0, pixels are already in RGB
987 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
988 * \note See comments of \ref ConvertHandleColor
990 bool PixelReadConvert::IsRawRGB()
993 || PlanarConfiguration == 2
1001 void PixelReadConvert::ComputeRawAndRGBSizes()
1003 int bitsAllocated = BitsAllocated;
1004 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
1005 // in this case we will expand the image to 16 bits (see
1006 // \ref ReadAndDecompress12BitsTo16Bits() )
1007 if ( BitsAllocated == 12 )
1012 RawSize = XSize * YSize * ZSize
1013 * ( bitsAllocated / 8 )
1017 RGBSize = 3 * RawSize;
1025 void PixelReadConvert::GrabInformationsFromHeader( Header* header )
1027 // Number of Bits Allocated for storing a Pixel is defaulted to 16
1028 // when absent from the header.
1029 BitsAllocated = header->GetBitsAllocated();
1030 if ( BitsAllocated == 0 )
1035 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1036 // when absent from the header.
1037 BitsStored = header->GetBitsStored();
1038 if ( BitsStored == 0 )
1040 BitsStored = BitsAllocated;
1043 // High Bit Position
1044 HighBitPosition = header->GetHighBitPosition();
1045 if ( HighBitPosition == 0 )
1047 HighBitPosition = BitsAllocated - 1;
1050 XSize = header->GetXSize();
1051 YSize = header->GetYSize();
1052 ZSize = header->GetZSize();
1053 SamplesPerPixel = header->GetSamplesPerPixel();
1054 PixelSize = header->GetPixelSize();
1055 PixelSign = header->IsSignedPixelData();
1056 SwapCode = header->GetSwapCode();
1057 TransferSyntaxType ts = header->GetTransferSyntax();
1059 ( ! header->IsDicomV3() )
1060 || ts == ImplicitVRLittleEndian
1061 || ts == ImplicitVRLittleEndianDLXGE
1062 || ts == ExplicitVRLittleEndian
1063 || ts == ExplicitVRBigEndian
1064 || ts == DeflatedExplicitVRLittleEndian;
1065 IsJPEG2000 = header->IsJPEG2000();
1066 IsJPEGLossless = header->IsJPEGLossless();
1067 IsRLELossless = ( ts == RLELossless );
1068 PixelOffset = header->GetPixelOffset();
1069 PixelDataLength = header->GetPixelAreaLength();
1070 RLEInfo = header->GetRLEInfo();
1071 JPEGInfo = header->GetJPEGInfo();
1073 PlanarConfiguration = header->GetPlanarConfiguration();
1074 IsMonochrome = header->IsMonochrome();
1075 IsPaletteColor = header->IsPaletteColor();
1076 IsYBRFull = header->IsYBRFull();
1078 /////////////////////////////////////////////////////////////////
1080 HasLUT = header->HasLUT();
1083 // Just in case some access to a Header element requires disk access.
1084 // Note: gdcmDocument::Fp is leaved open after OpenFile.
1085 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
1086 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
1087 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
1089 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1090 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1091 // Document::Document() ], the loading of the value (content) of a
1092 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1093 // loaded). Hence, we first try to obtain the LUTs data from the header
1094 // and when this fails we read the LUTs data directely from disk.
1095 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1096 /// We should NOT bypass the [Bin|Val]Entry class. Instead
1097 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
1098 /// (e.g. BinEntry::GetBinArea()) should force disk access from
1099 /// within the [Bin|Val]Entry class itself. The only problem
1100 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
1101 /// parsed from. Fix that. FIXME.
1104 header->LoadEntryBinArea(0x0028, 0x1201);
1105 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
1108 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1109 "unable to read red LUT data" );
1113 header->LoadEntryBinArea(0x0028, 0x1202);
1114 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
1115 if ( ! LutGreenData)
1117 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1118 "unable to read green LUT data" );
1122 header->LoadEntryBinArea(0x0028, 0x1203);
1123 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
1124 if ( ! LutBlueData )
1126 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1127 "unable to read blue LUT data" );
1131 ComputeRawAndRGBSizes();
1135 * \brief Build Red/Green/Blue/Alpha LUT from Header
1136 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1137 * and (0028,1101),(0028,1102),(0028,1102)
1138 * - xxx Palette Color Lookup Table Descriptor - are found
1139 * and (0028,1201),(0028,1202),(0028,1202)
1140 * - xxx Palette Color Lookup Table Data - are found
1141 * \warning does NOT deal with :
1142 * 0028 1100 Gray Lookup Table Descriptor (Retired)
1143 * 0028 1221 Segmented Red Palette Color Lookup Table Data
1144 * 0028 1222 Segmented Green Palette Color Lookup Table Data
1145 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
1146 * no known Dicom reader deals with them :-(
1147 * @return a RGBA Lookup Table
1149 void PixelReadConvert::BuildLUTRGBA()
1155 // Not so easy : see
1156 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1158 if ( ! IsPaletteColor )
1163 if ( LutRedDescriptor == GDCM_UNFOUND
1164 || LutGreenDescriptor == GDCM_UNFOUND
1165 || LutBlueDescriptor == GDCM_UNFOUND )
1170 ////////////////////////////////////////////
1171 // Extract the info from the LUT descriptors
1172 int lengthR; // Red LUT length in Bytes
1173 int debR; // Subscript of the first Lut Value
1174 int nbitsR; // Lut item size (in Bits)
1175 int nbRead = sscanf( LutRedDescriptor.c_str(),
1177 &lengthR, &debR, &nbitsR );
1180 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong red LUT descriptor");
1183 int lengthG; // Green LUT length in Bytes
1184 int debG; // Subscript of the first Lut Value
1185 int nbitsG; // Lut item size (in Bits)
1186 nbRead = sscanf( LutGreenDescriptor.c_str(),
1188 &lengthG, &debG, &nbitsG );
1191 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong green LUT descriptor");
1194 int lengthB; // Blue LUT length in Bytes
1195 int debB; // Subscript of the first Lut Value
1196 int nbitsB; // Lut item size (in Bits)
1197 nbRead = sscanf( LutRedDescriptor.c_str(),
1199 &lengthB, &debB, &nbitsB );
1202 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong blue LUT descriptor");
1205 ////////////////////////////////////////////////////////
1206 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1211 ////////////////////////////////////////////////
1212 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1213 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1218 memset( LutRGBA, 0, 1024 );
1221 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1223 // when LUT item size is different than pixel size
1224 mult = 2; // high byte must be = low byte
1228 // See PS 3.3-2003 C.11.1.1.2 p 619
1232 // if we get a black image, let's just remove the '+1'
1233 // from 'i*mult+1' and check again
1234 // if it works, we shall have to check the 3 Palettes
1235 // to see which byte is ==0 (first one, or second one)
1237 // We give up the checking to avoid some (useless ?)overhead
1238 // (optimistic asumption)
1240 uint8_t* a = LutRGBA + 0;
1241 for( i=0; i < lengthR; ++i )
1243 *a = LutRedData[i*mult+1];
1248 for( i=0; i < lengthG; ++i)
1250 *a = LutGreenData[i*mult+1];
1255 for(i=0; i < lengthB; ++i)
1257 *a = LutBlueData[i*mult+1];
1262 for(i=0; i < 256; ++i)
1264 *a = 1; // Alpha component
1270 * \brief Build the RGB image from the Raw imagage and the LUTs.
1272 bool PixelReadConvert::BuildRGBImage()
1276 // The job is already done.
1282 // The job can't be done
1289 // The job can't be done
1295 uint8_t* localRGB = RGB;
1296 for (size_t i = 0; i < RawSize; ++i )
1299 *localRGB++ = LutRGBA[j];
1300 *localRGB++ = LutRGBA[j+1];
1301 *localRGB++ = LutRGBA[j+2];
1307 * \brief Print self.
1308 * @param os Stream to print to.
1310 void PixelReadConvert::Print( std::ostream &os )
1316 * \brief Print self.
1317 * @param indent Indentation string to be prepended during printing.
1318 * @param os Stream to print to.
1320 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1323 << "--- Pixel information -------------------------"
1326 << "Pixel Data: offset " << PixelOffset
1327 << " x(" << std::hex << PixelOffset << std::dec
1328 << ") length " << PixelDataLength
1329 << " x(" << std::hex << PixelDataLength << std::dec
1330 << ")" << std::endl;
1332 if ( IsRLELossless )
1336 RLEInfo->Print( indent, os );
1340 dbg.Verbose(0, "PixelReadConvert::Print: set as RLE file "
1341 "but NO RLEinfo present.");
1345 if ( IsJPEG2000 || IsJPEGLossless )
1349 JPEGInfo->Print( indent, os );
1353 dbg.Verbose(0, "PixelReadConvert::Print: set as JPEG file "
1354 "but NO JPEGinfo present.");
1359 } // end namespace gdcm
1361 // NOTES on File internal calls
1363 // ---> GetImageData
1364 // ---> GetImageDataIntoVector
1365 // |---> GetImageDataIntoVectorRaw
1366 // | lut intervention
1368 // ---> GetImageDataRaw
1369 // ---> GetImageDataIntoVectorRaw