1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/07 22:19:48 $
7 Version: $Revision: 1.19 $
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 gdcmVerboseMacro( "Read more bytes than the segment size.");
270 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
271 * Dicom encapsulated file and decompress it.
272 * @param fp already open File Pointer
273 * at which the pixel data should be copied
276 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream *fp )
278 uint8_t *subRaw = Raw;
279 long RawSegmentSize = XSize * YSize;
281 // Loop on the frame[s]
282 for( RLEFramesInfo::RLEFrameList::iterator
283 it = RLEInfo->Frames.begin();
284 it != RLEInfo->Frames.end();
287 // Loop on the fragments
288 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
290 fp->seekg( (*it)->Offset[k] , std::ios::beg );
291 (void)ReadAndDecompressRLEFragment( subRaw,
295 subRaw += RawSegmentSize;
299 if ( BitsAllocated == 16 )
301 // Try to deal with RLE 16 Bits
302 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
309 * \brief Swap the bytes, according to \ref SwapCode.
311 void PixelReadConvert::ConvertSwapZone()
315 if( BitsAllocated == 16 )
317 uint16_t *im16 = (uint16_t*)Raw;
328 for( i = 0; i < RawSize / 2; i++ )
330 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
334 gdcmVerboseMacro("SwapCode value (16 bits) not allowed.");
337 else if( BitsAllocated == 32 )
342 uint32_t* im32 = (uint32_t*)Raw;
349 for( i = 0; i < RawSize / 4; i++ )
351 low = im32[i] & 0x0000ffff; // 4321
352 high = im32[i] >> 16;
353 high = ( high >> 8 ) | ( high << 8 );
354 low = ( low >> 8 ) | ( low << 8 );
356 im32[i] = ( s32 << 16 ) | high;
360 for( i = 0; i < RawSize / 4; i++ )
362 low = im32[i] & 0x0000ffff; // 2143
363 high = im32[i] >> 16;
364 high = ( high >> 8 ) | ( high << 8 );
365 low = ( low >> 8 ) | ( low << 8 );
367 im32[i] = ( s32 << 16 ) | low;
371 for( i = 0; i < RawSize / 4; i++ )
373 low = im32[i] & 0x0000ffff; // 3412
374 high = im32[i] >> 16;
376 im32[i] = ( s32 << 16 ) | high;
380 gdcmVerboseMacro("SwapCode value (32 bits) not allowed." );
386 * \brief Deal with endianity i.e. re-arange bytes inside the integer
388 void PixelReadConvert::ConvertReorderEndianity()
390 if ( BitsAllocated != 8 )
395 // Special kludge in order to deal with xmedcon broken images:
396 if ( ( BitsAllocated == 16 )
397 && ( BitsStored < BitsAllocated )
400 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
401 uint16_t *deb = (uint16_t *)Raw;
402 for(int i = 0; i<l; i++)
415 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
416 * file and decompress it. This funciton assumes that each
417 * jpeg fragment contains a whole frame (jpeg file).
418 * @param fp File Pointer
421 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream *fp )
423 uint8_t *localRaw = Raw;
424 // Loop on the fragment[s]
425 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
426 it = JPEGInfo->Fragments.begin();
427 it != JPEGInfo->Fragments.end();
430 fp->seekg( (*it)->Offset, std::ios::beg);
432 if ( BitsStored == 8)
434 // JPEG Lossy : call to IJG 6b
435 if ( ! gdcm_read_JPEG_file8( fp, localRaw ) )
440 else if ( BitsStored <= 12)
442 // Reading Fragment pixels
443 if ( ! gdcm_read_JPEG_file12 ( fp, localRaw ) )
448 else if ( BitsStored <= 16)
450 // Reading Fragment pixels
451 if ( ! gdcm_read_JPEG_file16 ( fp, localRaw ) )
455 //gdcmAssertMacro( IsJPEGLossless );
459 // other JPEG lossy not supported
460 gdcmErrorMacro( "Unknown jpeg lossy compression ");
464 // Advance to next free location in Raw
465 // for next fragment decompression (if any)
466 int length = XSize * YSize * SamplesPerPixel;
467 int numberBytes = BitsAllocated / 8;
469 localRaw += length * numberBytes;
475 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
476 * file and decompress it. This function assumes that the dicom
477 * image is a single frame split into several JPEG fragments.
478 * Those fragments will be glued together into a memory buffer
480 * @param fp File Pointer
483 bool PixelReadConvert::
484 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
486 // Loop on the fragment[s] to get total length
487 size_t totalLength = 0;
488 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
489 for( it = JPEGInfo->Fragments.begin();
490 it != JPEGInfo->Fragments.end();
493 totalLength += (*it)->Length;
496 // Concatenate the jpeg fragments into a local buffer
497 JOCTET *buffer = new JOCTET [totalLength];
500 // Loop on the fragment[s]
501 for( it = JPEGInfo->Fragments.begin();
502 it != JPEGInfo->Fragments.end();
505 fp->seekg( (*it)->Offset, std::ios::beg);
506 size_t len = (*it)->Length;
507 fp->read((char *)p,len);
511 size_t howManyRead = 0;
512 size_t howManyWritten = 0;
514 if ( BitsStored == 8)
516 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
517 &howManyRead, &howManyWritten ) )
519 gdcmErrorMacro( "Failed to read jpeg8 ");
524 else if ( BitsStored <= 12)
526 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
527 &howManyRead, &howManyWritten ) )
529 gdcmErrorMacro( "Failed to read jpeg12 ");
534 else if ( BitsStored <= 16)
537 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
538 &howManyRead, &howManyWritten ) )
540 gdcmErrorMacro( "Failed to read jpeg16 ");
547 // other JPEG lossy not supported
548 gdcmErrorMacro( "Unknown jpeg lossy compression ");
560 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
561 * file and decompress it. This function handles the generic
562 * and complex case where the DICOM contains several frames,
563 * and some of the frames are possibly split into several JPEG
565 * @param fp File Pointer
568 bool PixelReadConvert::
569 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
571 // Loop on the fragment[s] to get total length
572 size_t totalLength = 0;
573 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
574 for( it = JPEGInfo->Fragments.begin();
575 it != JPEGInfo->Fragments.end();
578 totalLength += (*it)->Length;
581 // Concatenate the jpeg fragments into a local buffer
582 JOCTET *buffer = new JOCTET [totalLength];
585 // Loop on the fragment[s]
586 for( it = JPEGInfo->Fragments.begin();
587 it != JPEGInfo->Fragments.end();
590 fp->seekg( (*it)->Offset, std::ios::beg);
591 size_t len = (*it)->Length;
592 fp->read((char *)p,len);
596 size_t howManyRead = 0;
597 size_t howManyWritten = 0;
598 size_t fragmentLength = 0;
600 for( it = JPEGInfo->Fragments.begin() ;
601 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
604 fragmentLength += (*it)->Length;
606 if (howManyRead > fragmentLength) continue;
608 if ( BitsStored == 8)
610 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
612 &howManyRead, &howManyWritten ) )
614 gdcmErrorMacro( "Failed to read jpeg8");
619 else if ( BitsStored <= 12)
622 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
624 &howManyRead, &howManyWritten ) )
626 gdcmErrorMacro( "Failed to read jpeg12");
631 else if ( BitsStored <= 16)
634 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
636 &howManyRead, &howManyWritten ) )
638 gdcmErrorMacro( "Failed to read jpeg16 ");
645 // other JPEG lossy not supported
646 gdcmErrorMacro( "Unknown jpeg lossy compression ");
651 if (howManyRead < fragmentLength)
652 howManyRead = fragmentLength;
662 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
663 * file and decompress it.
664 * @param fp File Pointer
667 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
671 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
672 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
676 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
678 // we have one frame split into several fragments
679 // we will pack those fragments into a single buffer and
681 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
683 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
685 // suppose each fragment is a frame
686 return ReadAndDecompressJPEGFramesFromFile( fp );
690 // The dicom image contains frames containing fragments of images
691 // a more complex algorithm :-)
692 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
697 * \brief Re-arrange the bits within the bytes.
700 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
702 if ( BitsStored != BitsAllocated )
704 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
705 if ( BitsAllocated == 16 )
707 uint16_t mask = 0xffff;
708 mask = mask >> ( BitsAllocated - BitsStored );
709 uint16_t* deb = (uint16_t*)Raw;
710 for(int i = 0; i<l; i++)
712 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
716 else if ( BitsAllocated == 32 )
718 uint32_t mask = 0xffffffff;
719 mask = mask >> ( BitsAllocated - BitsStored );
720 uint32_t* deb = (uint32_t*)Raw;
721 for(int i = 0; i<l; i++)
723 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
729 gdcmVerboseMacro("Weird image");
730 throw FormatError( "Weird image !?" );
737 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
738 * \warning Works on all the frames at a time
740 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
742 uint8_t *localRaw = Raw;
743 uint8_t *copyRaw = new uint8_t[ RawSize ];
744 memmove( copyRaw, localRaw, RawSize );
746 // to see the tricks about YBR_FULL, YBR_FULL_422,
747 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
748 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
749 // and be *very* affraid
751 int l = XSize * YSize;
752 int nbFrames = ZSize;
754 uint8_t *a = copyRaw;
755 uint8_t *b = copyRaw + l;
756 uint8_t *c = copyRaw + l + l;
759 /// \todo : Replace by the 'well known' integer computation
760 /// counterpart. Refer to
761 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
762 /// for code optimisation.
764 for ( int i = 0; i < nbFrames; i++ )
766 for ( int j = 0; j < l; j++ )
768 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
769 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
770 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
772 if (R < 0.0) R = 0.0;
773 if (G < 0.0) G = 0.0;
774 if (B < 0.0) B = 0.0;
775 if (R > 255.0) R = 255.0;
776 if (G > 255.0) G = 255.0;
777 if (B > 255.0) B = 255.0;
779 *(localRaw++) = (uint8_t)R;
780 *(localRaw++) = (uint8_t)G;
781 *(localRaw++) = (uint8_t)B;
791 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
792 * \warning Works on all the frames at a time
794 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
796 uint8_t *localRaw = Raw;
797 uint8_t *copyRaw = new uint8_t[ RawSize ];
798 memmove( copyRaw, localRaw, RawSize );
800 int l = XSize * YSize * ZSize;
802 uint8_t* a = copyRaw;
803 uint8_t* b = copyRaw + l;
804 uint8_t* c = copyRaw + l + l;
806 for (int j = 0; j < l; j++)
808 *(localRaw++) = *(a++);
809 *(localRaw++) = *(b++);
810 *(localRaw++) = *(c++);
815 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
817 // ComputeRawAndRGBSizes is already made by
818 // ::GrabInformationsFromHeader. So, the structure sizes are
822 //////////////////////////////////////////////////
823 //// First stage: get our hands on the Pixel Data.
826 gdcmVerboseMacro( "Unavailable file pointer." );
830 fp->seekg( PixelOffset, std::ios::beg );
831 if( fp->fail() || fp->eof())
833 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
839 //////////////////////////////////////////////////
840 //// Second stage: read from disk dans decompress.
841 if ( BitsAllocated == 12 )
843 ReadAndDecompress12BitsTo16Bits( fp);
847 // This problem can be found when some obvious informations are found
848 // after the field containing the image datas. In this case, these
849 // bad datas are added to the size of the image (in the PixelDataLength
850 // variable). But RawSize is the right size of the image !
851 if( PixelDataLength != RawSize)
853 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
855 if( PixelDataLength > RawSize)
857 fp->read( (char*)Raw, RawSize);
861 fp->read( (char*)Raw, PixelDataLength);
864 if ( fp->fail() || fp->eof())
866 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
870 else if ( IsRLELossless )
872 if ( ! ReadAndDecompressRLEFile( fp ) )
874 gdcmVerboseMacro( "RLE decompressor failed." );
880 // Default case concerns JPEG family
881 if ( ! ReadAndDecompressJPEGFile( fp ) )
883 gdcmVerboseMacro( "JPEG decompressor failed." );
888 ////////////////////////////////////////////
889 //// Third stage: twigle the bytes and bits.
890 ConvertReorderEndianity();
891 ConvertReArrangeBits();
892 ConvertHandleColor();
897 void PixelReadConvert::ConvertHandleColor()
899 //////////////////////////////////
900 // Deal with the color decoding i.e. handle:
901 // - R, G, B planes (as opposed to RGB pixels)
902 // - YBR (various) encodings.
903 // - LUT[s] (or "PALETTE COLOR").
905 // The classification in the color decoding schema is based on the blending
906 // of two Dicom tags values:
907 // * "Photometric Interpretation" for which we have the cases:
908 // - [Photo A] MONOCHROME[1|2] pictures,
909 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
910 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
911 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
912 // * "Planar Configuration" for which we have the cases:
913 // - [Planar 0] 0 then Pixels are already RGB
914 // - [Planar 1] 1 then we have 3 planes : R, G, B,
915 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
917 // Now in theory, one could expect some coherence when blending the above
918 // cases. For example we should not encounter files belonging at the
919 // time to case [Planar 0] and case [Photo D].
920 // Alas, this was only theory ! Because in practice some odd (read ill
921 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
922 // - "Planar Configuration" = 0,
923 // - "Photometric Interpretation" = "PALETTE COLOR".
924 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
925 // towards Dicom-non-conformance files:
926 // << whatever the "Planar Configuration" value might be, a
927 // "Photometric Interpretation" set to "PALETTE COLOR" forces
928 // a LUT intervention >>
930 // Now we are left with the following handling of the cases:
931 // - [Planar 0] OR [Photo A] no color decoding (since respectively
932 // Pixels are already RGB and monochrome pictures have no color :),
933 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
934 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
935 // - [Planar 2] OR [Photo D] requires LUT intervention.
939 // [Planar 2] OR [Photo D]: LUT intervention done outside
943 if ( PlanarConfiguration == 1 )
947 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
948 ConvertYcBcRPlanesToRGBPixels();
952 // [Planar 1] AND [Photo C]
953 ConvertRGBPlanesToRGBPixels();
958 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
959 // pixels need to be RGB-fied anyway
962 ConvertRGBPlanesToRGBPixels();
964 // In *normal *case, when planarConf is 0, pixels are already in RGB
968 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
969 * \note See comments of \ref ConvertHandleColor
971 bool PixelReadConvert::IsRawRGB()
974 || PlanarConfiguration == 2
982 void PixelReadConvert::ComputeRawAndRGBSizes()
984 int bitsAllocated = BitsAllocated;
985 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
986 // in this case we will expand the image to 16 bits (see
987 // \ref ReadAndDecompress12BitsTo16Bits() )
988 if ( BitsAllocated == 12 )
993 RawSize = XSize * YSize * ZSize
994 * ( bitsAllocated / 8 )
998 RGBSize = 3 * RawSize;
1006 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
1008 // Number of Bits Allocated for storing a Pixel is defaulted to 16
1009 // when absent from the header.
1010 BitsAllocated = header->GetBitsAllocated();
1011 if ( BitsAllocated == 0 )
1016 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1017 // when absent from the header.
1018 BitsStored = header->GetBitsStored();
1019 if ( BitsStored == 0 )
1021 BitsStored = BitsAllocated;
1024 // High Bit Position
1025 HighBitPosition = header->GetHighBitPosition();
1026 if ( HighBitPosition == 0 )
1028 HighBitPosition = BitsAllocated - 1;
1031 XSize = header->GetXSize();
1032 YSize = header->GetYSize();
1033 ZSize = header->GetZSize();
1034 SamplesPerPixel = header->GetSamplesPerPixel();
1035 PixelSize = header->GetPixelSize();
1036 PixelSign = header->IsSignedPixelData();
1037 SwapCode = header->GetSwapCode();
1038 TransferSyntaxType ts = header->GetTransferSyntax();
1040 ( ! header->IsDicomV3() )
1041 || ts == ImplicitVRLittleEndian
1042 || ts == ImplicitVRLittleEndianDLXGE
1043 || ts == ExplicitVRLittleEndian
1044 || ts == ExplicitVRBigEndian
1045 || ts == DeflatedExplicitVRLittleEndian;
1046 IsJPEG2000 = header->IsJPEG2000();
1047 IsJPEGLossless = header->IsJPEGLossless();
1048 IsRLELossless = ( ts == RLELossless );
1049 PixelOffset = header->GetPixelOffset();
1050 PixelDataLength = header->GetPixelAreaLength();
1051 RLEInfo = header->GetRLEInfo();
1052 JPEGInfo = header->GetJPEGInfo();
1054 PlanarConfiguration = header->GetPlanarConfiguration();
1055 IsMonochrome = header->IsMonochrome();
1056 IsPaletteColor = header->IsPaletteColor();
1057 IsYBRFull = header->IsYBRFull();
1059 /////////////////////////////////////////////////////////////////
1061 HasLUT = header->HasLUT();
1064 // Just in case some access to a Header element requires disk access.
1065 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
1066 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
1067 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
1069 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1070 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1071 // Document::Document() ], the loading of the value (content) of a
1072 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1073 // loaded). Hence, we first try to obtain the LUTs data from the header
1074 // and when this fails we read the LUTs data directely from disk.
1075 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1076 /// We should NOT bypass the [Bin|Val]Entry class. Instead
1077 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
1078 /// (e.g. BinEntry::GetBinArea()) should force disk access from
1079 /// within the [Bin|Val]Entry class itself. The only problem
1080 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
1081 /// parsed from. Fix that. FIXME.
1084 header->LoadEntryBinArea(0x0028, 0x1201);
1085 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
1088 gdcmVerboseMacro( "Unable to read red LUT data" );
1092 header->LoadEntryBinArea(0x0028, 0x1202);
1093 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
1094 if ( ! LutGreenData)
1096 gdcmVerboseMacro( "Unable to read green LUT data" );
1100 header->LoadEntryBinArea(0x0028, 0x1203);
1101 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
1102 if ( ! LutBlueData )
1104 gdcmVerboseMacro( "Unable to read blue LUT data" );
1108 ComputeRawAndRGBSizes();
1112 * \brief Build Red/Green/Blue/Alpha LUT from Header
1113 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1114 * and (0028,1101),(0028,1102),(0028,1102)
1115 * - xxx Palette Color Lookup Table Descriptor - are found
1116 * and (0028,1201),(0028,1202),(0028,1202)
1117 * - xxx Palette Color Lookup Table Data - are found
1118 * \warning does NOT deal with :
1119 * 0028 1100 Gray Lookup Table Descriptor (Retired)
1120 * 0028 1221 Segmented Red Palette Color Lookup Table Data
1121 * 0028 1222 Segmented Green Palette Color Lookup Table Data
1122 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
1123 * no known Dicom reader deals with them :-(
1124 * @return a RGBA Lookup Table
1126 void PixelReadConvert::BuildLUTRGBA()
1132 // Not so easy : see
1133 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1135 if ( ! IsPaletteColor )
1140 if ( LutRedDescriptor == GDCM_UNFOUND
1141 || LutGreenDescriptor == GDCM_UNFOUND
1142 || LutBlueDescriptor == GDCM_UNFOUND )
1147 ////////////////////////////////////////////
1148 // Extract the info from the LUT descriptors
1149 int lengthR; // Red LUT length in Bytes
1150 int debR; // Subscript of the first Lut Value
1151 int nbitsR; // Lut item size (in Bits)
1152 int nbRead = sscanf( LutRedDescriptor.c_str(),
1154 &lengthR, &debR, &nbitsR );
1157 gdcmVerboseMacro( "Wrong red LUT descriptor" );
1160 int lengthG; // Green LUT length in Bytes
1161 int debG; // Subscript of the first Lut Value
1162 int nbitsG; // Lut item size (in Bits)
1163 nbRead = sscanf( LutGreenDescriptor.c_str(),
1165 &lengthG, &debG, &nbitsG );
1168 gdcmVerboseMacro( "Wrong green LUT descriptor" );
1171 int lengthB; // Blue LUT length in Bytes
1172 int debB; // Subscript of the first Lut Value
1173 int nbitsB; // Lut item size (in Bits)
1174 nbRead = sscanf( LutRedDescriptor.c_str(),
1176 &lengthB, &debB, &nbitsB );
1179 gdcmVerboseMacro( "Wrong blue LUT descriptor" );
1182 ////////////////////////////////////////////////////////
1183 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1188 ////////////////////////////////////////////////
1189 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1190 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1195 memset( LutRGBA, 0, 1024 );
1198 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1200 // when LUT item size is different than pixel size
1201 mult = 2; // high byte must be = low byte
1205 // See PS 3.3-2003 C.11.1.1.2 p 619
1209 // if we get a black image, let's just remove the '+1'
1210 // from 'i*mult+1' and check again
1211 // if it works, we shall have to check the 3 Palettes
1212 // to see which byte is ==0 (first one, or second one)
1214 // We give up the checking to avoid some (useless ?)overhead
1215 // (optimistic asumption)
1217 uint8_t* a = LutRGBA + 0;
1218 for( i=0; i < lengthR; ++i )
1220 *a = LutRedData[i*mult+1];
1225 for( i=0; i < lengthG; ++i)
1227 *a = LutGreenData[i*mult+1];
1232 for(i=0; i < lengthB; ++i)
1234 *a = LutBlueData[i*mult+1];
1239 for(i=0; i < 256; ++i)
1241 *a = 1; // Alpha component
1247 * \brief Build the RGB image from the Raw imagage and the LUTs.
1249 bool PixelReadConvert::BuildRGBImage()
1253 // The job is already done.
1259 // The job can't be done
1266 // The job can't be done
1272 uint8_t* localRGB = RGB;
1273 for (size_t i = 0; i < RawSize; ++i )
1276 *localRGB++ = LutRGBA[j];
1277 *localRGB++ = LutRGBA[j+1];
1278 *localRGB++ = LutRGBA[j+2];
1284 * \brief Print self.
1285 * @param os Stream to print to.
1287 void PixelReadConvert::Print( std::ostream &os )
1293 * \brief Print self.
1294 * @param indent Indentation string to be prepended during printing.
1295 * @param os Stream to print to.
1297 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1300 << "--- Pixel information -------------------------"
1303 << "Pixel Data: offset " << PixelOffset
1304 << " x(" << std::hex << PixelOffset << std::dec
1305 << ") length " << PixelDataLength
1306 << " x(" << std::hex << PixelDataLength << std::dec
1307 << ")" << std::endl;
1309 if ( IsRLELossless )
1313 RLEInfo->Print( indent, os );
1317 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1321 if ( IsJPEG2000 || IsJPEGLossless )
1325 JPEGInfo->Print( indent, os );
1329 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1334 } // end namespace gdcm
1336 // NOTES on File internal calls
1338 // ---> GetImageData
1339 // ---> GetImageDataIntoVector
1340 // |---> GetImageDataIntoVectorRaw
1341 // | lut intervention
1343 // ---> GetImageDataRaw
1344 // ---> GetImageDataIntoVectorRaw