1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2004/12/13 14:58:41 $
7 Version: $Revision: 1.9 $
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 uint8_t* localRaw = Raw;
505 // Loop on the fragment[s]
506 for( it = JPEGInfo->Fragments.begin();
507 it != JPEGInfo->Fragments.end();
510 fp->seekg( (*it)->Offset, std::ios::beg);
511 size_t len = (*it)->Length;
512 fp->read((char *)p,len);
516 size_t howManyRead = 0;
517 size_t howManyWritten = 0;
518 size_t fragmentLength = 0;
520 if ( BitsStored == 8)
522 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
523 &howManyRead, &howManyWritten ) )
526 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 "
532 else if ( BitsStored <= 12)
534 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
535 &howManyRead, &howManyWritten ) )
538 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 "
544 else if ( BitsStored <= 16)
547 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
548 &howManyRead, &howManyWritten ) )
551 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 "
559 // other JPEG lossy not supported
560 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
561 "jpeg lossy compression ");
573 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
574 * file and decompress it. This function handles the generic
575 * and complex case where the DICOM contains several frames,
576 * and some of the frames are possibly split into several JPEG
578 * @param fp File Pointer
581 bool PixelReadConvert::
582 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream* fp )
584 // Loop on the fragment[s] to get total length
585 size_t totalLength = 0;
586 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
587 it = JPEGInfo->Fragments.begin();
588 it != JPEGInfo->Fragments.end();
591 totalLength += (*it)->Length;
594 // Concatenate the jpeg fragments into a local buffer
595 JOCTET *buffer = new JOCTET [totalLength];
598 uint8_t* localRaw = Raw;
599 // Loop on the fragment[s]
600 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
601 it = JPEGInfo->Fragments.begin();
602 it != JPEGInfo->Fragments.end();
605 fp->seekg( (*it)->Offset, std::ios::beg);
606 size_t len = (*it)->Length;
607 fp->read((char *)p,len);
611 size_t howManyRead = 0;
612 size_t howManyWritten = 0;
613 size_t fragmentLength = 0;
615 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
616 it = JPEGInfo->Fragments.begin() ;
617 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
620 fragmentLength += (*it)->Length;
622 if (howManyRead > fragmentLength) continue;
624 if ( BitsStored == 8)
626 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
628 &howManyRead, &howManyWritten ) )
630 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 ");
635 else if ( BitsStored <= 12)
638 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
640 &howManyRead, &howManyWritten ) )
642 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 ");
647 else if ( BitsStored <= 16)
650 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
652 &howManyRead, &howManyWritten ) )
654 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 ");
661 // other JPEG lossy not supported
662 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
663 "jpeg lossy compression ");
668 if (howManyRead < fragmentLength)
669 howManyRead = fragmentLength;
679 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
680 * file and decompress it.
681 * @param fp File Pointer
684 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
688 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
689 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
693 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
695 // we have one frame split into several fragments
696 // we will pack those fragments into a single buffer and
698 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
700 else if (JPEGInfo->Fragments.size() == ZSize)
702 // suppose each fragment is a frame
703 return ReadAndDecompressJPEGFramesFromFile( fp );
707 // The dicom image contains frames containing fragments of images
708 // a more complex algorithm :-)
709 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
714 * \brief Re-arrange the bits within the bytes.
717 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
719 if ( BitsStored != BitsAllocated )
721 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
722 if ( BitsAllocated == 16 )
724 uint16_t mask = 0xffff;
725 mask = mask >> ( BitsAllocated - BitsStored );
726 uint16_t* deb = (uint16_t*)Raw;
727 for(int i = 0; i<l; i++)
729 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
733 else if ( BitsAllocated == 32 )
735 uint32_t mask = 0xffffffff;
736 mask = mask >> ( BitsAllocated - BitsStored );
737 uint32_t* deb = (uint32_t*)Raw;
738 for(int i = 0; i<l; i++)
740 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
746 dbg.Verbose(0, "PixelReadConvert::ConvertReArrangeBits: weird image");
747 throw FormatError( "PixelReadConvert::ConvertReArrangeBits()",
755 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
756 * \warning Works on all the frames at a time
758 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
760 uint8_t* localRaw = Raw;
761 uint8_t* copyRaw = new uint8_t[ RawSize ];
762 memmove( copyRaw, localRaw, RawSize );
764 // to see the tricks about YBR_FULL, YBR_FULL_422,
765 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
766 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
767 // and be *very* affraid
769 int l = XSize * YSize;
770 int nbFrames = ZSize;
772 uint8_t* a = copyRaw;
773 uint8_t* b = copyRaw + l;
774 uint8_t* c = copyRaw + l + l;
777 /// \todo : Replace by the 'well known' integer computation
778 /// counterpart. Refer to
779 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
780 /// for code optimisation.
782 for ( int i = 0; i < nbFrames; i++ )
784 for ( int j = 0; j < l; j++ )
786 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
787 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
788 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
790 if (R < 0.0) R = 0.0;
791 if (G < 0.0) G = 0.0;
792 if (B < 0.0) B = 0.0;
793 if (R > 255.0) R = 255.0;
794 if (G > 255.0) G = 255.0;
795 if (B > 255.0) B = 255.0;
797 *(localRaw++) = (uint8_t)R;
798 *(localRaw++) = (uint8_t)G;
799 *(localRaw++) = (uint8_t)B;
809 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
810 * \warning Works on all the frames at a time
812 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
814 uint8_t* localRaw = Raw;
815 uint8_t* copyRaw = new uint8_t[ RawSize ];
816 memmove( copyRaw, localRaw, RawSize );
818 int l = XSize * YSize * ZSize;
820 uint8_t* a = copyRaw;
821 uint8_t* b = copyRaw + l;
822 uint8_t* c = copyRaw + l + l;
824 for (int j = 0; j < l; j++)
826 *(localRaw++) = *(a++);
827 *(localRaw++) = *(b++);
828 *(localRaw++) = *(c++);
833 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream* fp )
835 // ComputeRawAndRGBSizes is already made by
836 // ::GrabInformationsFromHeader. So, the structure sizes are
840 //////////////////////////////////////////////////
841 //// First stage: get our hands on the Pixel Data.
844 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
845 "unavailable file pointer." );
849 fp->seekg( PixelOffset, std::ios::beg );
850 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
852 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
853 "unable to find PixelOffset in file." );
859 //////////////////////////////////////////////////
860 //// Second stage: read from disk dans decompress.
861 if ( BitsAllocated == 12 )
863 ReadAndDecompress12BitsTo16Bits( fp);
867 // This problem can be found when some obvious informations are found
868 // after the field containing the image datas. In this case, these
869 // bad datas are added to the size of the image (in the PixelDataLength
870 // variable). But RawSize is the right size of the image !
871 if( PixelDataLength != RawSize)
873 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
874 "Mismatch between PixelReadConvert and RawSize." );
876 if( PixelDataLength > RawSize)
878 fp->read( (char*)Raw, RawSize);
882 fp->read( (char*)Raw, PixelDataLength);
885 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
887 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
888 "reading of Raw pixel data failed." );
892 else if ( IsRLELossless )
894 if ( ! ReadAndDecompressRLEFile( fp ) )
896 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
897 "RLE decompressor failed." );
903 // Default case concerns JPEG family
904 if ( ! ReadAndDecompressJPEGFile( fp ) )
906 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
907 "JPEG decompressor failed." );
912 ////////////////////////////////////////////
913 //// Third stage: twigle the bytes and bits.
914 ConvertReorderEndianity();
915 ConvertReArrangeBits();
916 ConvertHandleColor();
921 void PixelReadConvert::ConvertHandleColor()
923 //////////////////////////////////
924 // Deal with the color decoding i.e. handle:
925 // - R, G, B planes (as opposed to RGB pixels)
926 // - YBR (various) encodings.
927 // - LUT[s] (or "PALETTE COLOR").
929 // The classification in the color decoding schema is based on the blending
930 // of two Dicom tags values:
931 // * "Photometric Interpretation" for which we have the cases:
932 // - [Photo A] MONOCHROME[1|2] pictures,
933 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
934 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
935 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
936 // * "Planar Configuration" for which we have the cases:
937 // - [Planar 0] 0 then Pixels are already RGB
938 // - [Planar 1] 1 then we have 3 planes : R, G, B,
939 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
941 // Now in theory, one could expect some coherence when blending the above
942 // cases. For example we should not encounter files belonging at the
943 // time to case [Planar 0] and case [Photo D].
944 // Alas, this was only theory ! Because in practice some odd (read ill
945 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
946 // - "Planar Configuration" = 0,
947 // - "Photometric Interpretation" = "PALETTE COLOR".
948 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
949 // towards Dicom-non-conformance files:
950 // << whatever the "Planar Configuration" value might be, a
951 // "Photometric Interpretation" set to "PALETTE COLOR" forces
952 // a LUT intervention >>
954 // Now we are left with the following handling of the cases:
955 // - [Planar 0] OR [Photo A] no color decoding (since respectively
956 // Pixels are already RGB and monochrome pictures have no color :),
957 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
958 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
959 // - [Planar 2] OR [Photo D] requires LUT intervention.
963 // [Planar 2] OR [Photo D]: LUT intervention done outside
967 if ( PlanarConfiguration == 1 )
971 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
972 ConvertYcBcRPlanesToRGBPixels();
976 // [Planar 1] AND [Photo C]
977 ConvertRGBPlanesToRGBPixels();
982 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
983 // pixels need to be RGB-fied anyway
986 ConvertRGBPlanesToRGBPixels();
988 // In *normal *case, when planarConf is 0, pixels are already in RGB
992 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
993 * \note See comments of \ref ConvertHandleColor
995 bool PixelReadConvert::IsRawRGB()
998 || PlanarConfiguration == 2
1006 void PixelReadConvert::ComputeRawAndRGBSizes()
1008 int bitsAllocated = BitsAllocated;
1009 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
1010 // in this case we will expand the image to 16 bits (see
1011 // \ref ReadAndDecompress12BitsTo16Bits() )
1012 if ( BitsAllocated == 12 )
1017 RawSize = XSize * YSize * ZSize
1018 * ( bitsAllocated / 8 )
1022 RGBSize = 3 * RawSize;
1030 void PixelReadConvert::GrabInformationsFromHeader( Header* header )
1032 // Number of Bits Allocated for storing a Pixel is defaulted to 16
1033 // when absent from the header.
1034 BitsAllocated = header->GetBitsAllocated();
1035 if ( BitsAllocated == 0 )
1040 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1041 // when absent from the header.
1042 BitsStored = header->GetBitsStored();
1043 if ( BitsStored == 0 )
1045 BitsStored = BitsAllocated;
1048 // High Bit Position
1049 HighBitPosition = header->GetHighBitPosition();
1050 if ( HighBitPosition == 0 )
1052 HighBitPosition = BitsAllocated - 1;
1055 XSize = header->GetXSize();
1056 YSize = header->GetYSize();
1057 ZSize = header->GetZSize();
1058 SamplesPerPixel = header->GetSamplesPerPixel();
1059 PixelSize = header->GetPixelSize();
1060 PixelSign = header->IsSignedPixelData();
1061 SwapCode = header->GetSwapCode();
1062 TransferSyntaxType ts = header->GetTransferSyntax();
1064 ( ! header->IsDicomV3() )
1065 || ts == ImplicitVRLittleEndian
1066 || ts == ImplicitVRLittleEndianDLXGE
1067 || ts == ExplicitVRLittleEndian
1068 || ts == ExplicitVRBigEndian
1069 || ts == DeflatedExplicitVRLittleEndian;
1070 IsJPEG2000 = header->IsJPEG2000();
1071 IsJPEGLossless = header->IsJPEGLossless();
1072 IsRLELossless = ( ts == RLELossless );
1073 PixelOffset = header->GetPixelOffset();
1074 PixelDataLength = header->GetPixelAreaLength();
1075 RLEInfo = header->GetRLEInfo();
1076 JPEGInfo = header->GetJPEGInfo();
1078 PlanarConfiguration = header->GetPlanarConfiguration();
1079 IsMonochrome = header->IsMonochrome();
1080 IsPaletteColor = header->IsPaletteColor();
1081 IsYBRFull = header->IsYBRFull();
1083 /////////////////////////////////////////////////////////////////
1085 HasLUT = header->HasLUT();
1088 // Just in case some access to a Header element requires disk access.
1089 // Note: gdcmDocument::Fp is leaved open after OpenFile.
1090 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
1091 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
1092 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
1094 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1095 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1096 // Document::Document() ], the loading of the value (content) of a
1097 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1098 // loaded). Hence, we first try to obtain the LUTs data from the header
1099 // and when this fails we read the LUTs data directely from disk.
1100 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1101 /// We should NOT bypass the [Bin|Val]Entry class. Instead
1102 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
1103 /// (e.g. BinEntry::GetBinArea()) should force disk access from
1104 /// within the [Bin|Val]Entry class itself. The only problem
1105 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
1106 /// parsed from. Fix that. FIXME.
1109 header->LoadEntryBinArea(0x0028, 0x1201);
1110 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
1113 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1114 "unable to read red LUT data" );
1118 header->LoadEntryBinArea(0x0028, 0x1202);
1119 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
1120 if ( ! LutGreenData)
1122 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1123 "unable to read green LUT data" );
1127 header->LoadEntryBinArea(0x0028, 0x1203);
1128 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
1129 if ( ! LutBlueData )
1131 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
1132 "unable to read blue LUT data" );
1136 ComputeRawAndRGBSizes();
1140 * \brief Build Red/Green/Blue/Alpha LUT from Header
1141 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1142 * and (0028,1101),(0028,1102),(0028,1102)
1143 * - xxx Palette Color Lookup Table Descriptor - are found
1144 * and (0028,1201),(0028,1202),(0028,1202)
1145 * - xxx Palette Color Lookup Table Data - are found
1146 * \warning does NOT deal with :
1147 * 0028 1100 Gray Lookup Table Descriptor (Retired)
1148 * 0028 1221 Segmented Red Palette Color Lookup Table Data
1149 * 0028 1222 Segmented Green Palette Color Lookup Table Data
1150 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
1151 * no known Dicom reader deals with them :-(
1152 * @return a RGBA Lookup Table
1154 void PixelReadConvert::BuildLUTRGBA()
1160 // Not so easy : see
1161 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1163 if ( ! IsPaletteColor )
1168 if ( LutRedDescriptor == GDCM_UNFOUND
1169 || LutGreenDescriptor == GDCM_UNFOUND
1170 || LutBlueDescriptor == GDCM_UNFOUND )
1175 ////////////////////////////////////////////
1176 // Extract the info from the LUT descriptors
1177 int lengthR; // Red LUT length in Bytes
1178 int debR; // Subscript of the first Lut Value
1179 int nbitsR; // Lut item size (in Bits)
1180 int nbRead = sscanf( LutRedDescriptor.c_str(),
1182 &lengthR, &debR, &nbitsR );
1185 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong red LUT descriptor");
1188 int lengthG; // Green LUT length in Bytes
1189 int debG; // Subscript of the first Lut Value
1190 int nbitsG; // Lut item size (in Bits)
1191 nbRead = sscanf( LutGreenDescriptor.c_str(),
1193 &lengthG, &debG, &nbitsG );
1196 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong green LUT descriptor");
1199 int lengthB; // Blue LUT length in Bytes
1200 int debB; // Subscript of the first Lut Value
1201 int nbitsB; // Lut item size (in Bits)
1202 nbRead = sscanf( LutRedDescriptor.c_str(),
1204 &lengthB, &debB, &nbitsB );
1207 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong blue LUT descriptor");
1210 ////////////////////////////////////////////////////////
1211 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1216 ////////////////////////////////////////////////
1217 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1218 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1223 memset( LutRGBA, 0, 1024 );
1226 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1228 // when LUT item size is different than pixel size
1229 mult = 2; // high byte must be = low byte
1233 // See PS 3.3-2003 C.11.1.1.2 p 619
1237 // if we get a black image, let's just remove the '+1'
1238 // from 'i*mult+1' and check again
1239 // if it works, we shall have to check the 3 Palettes
1240 // to see which byte is ==0 (first one, or second one)
1242 // We give up the checking to avoid some (useless ?)overhead
1243 // (optimistic asumption)
1245 uint8_t* a = LutRGBA + 0;
1246 for( i=0; i < lengthR; ++i )
1248 *a = LutRedData[i*mult+1];
1253 for( i=0; i < lengthG; ++i)
1255 *a = LutGreenData[i*mult+1];
1260 for(i=0; i < lengthB; ++i)
1262 *a = LutBlueData[i*mult+1];
1267 for(i=0; i < 256; ++i)
1269 *a = 1; // Alpha component
1275 * \brief Build the RGB image from the Raw imagage and the LUTs.
1277 bool PixelReadConvert::BuildRGBImage()
1281 // The job is already done.
1287 // The job can't be done
1294 // The job can't be done
1300 uint8_t* localRGB = RGB;
1301 for (size_t i = 0; i < RawSize; ++i )
1304 *localRGB++ = LutRGBA[j];
1305 *localRGB++ = LutRGBA[j+1];
1306 *localRGB++ = LutRGBA[j+2];
1312 * \brief Print self.
1313 * @param indent Indentation string to be prepended during printing.
1314 * @param os Stream to print to.
1316 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1319 << "--- Pixel information -------------------------"
1322 << "Pixel Data: offset " << PixelOffset
1323 << " x" << std::hex << PixelOffset << std::dec
1324 << " length " << PixelDataLength
1325 << " x" << std::hex << PixelDataLength << std::dec
1328 if ( IsRLELossless )
1332 RLEInfo->Print( indent, os );
1336 dbg.Verbose(0, "PixelReadConvert::Print: set as RLE file "
1337 "but NO RLEinfo present.");
1341 if ( IsJPEG2000 || IsJPEGLossless )
1345 JPEGInfo->Print( indent, os );
1349 dbg.Verbose(0, "PixelReadConvert::Print: set as JPEG file "
1350 "but NO JPEGinfo present.");
1355 } // end namespace gdcm
1357 // NOTES on File internal calls
1359 // ---> GetImageData
1360 // ---> GetImageDataIntoVector
1361 // |---> GetImageDataIntoVectorRaw
1362 // | lut intervention
1364 // ---> GetImageDataRaw
1365 // ---> GetImageDataIntoVectorRaw