1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/11 16:44:43 $
7 Version: $Revision: 1.21 $
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 "gdcmGlobal.h"
29 #include "gdcmPixelReadConvert.h"
30 #include "gdcmDocEntry.h"
31 #include "gdcmRLEFramesInfo.h"
32 #include "gdcmJPEGFragmentsInfo.h"
35 #include <stdio.h> //for sscanf
39 #define str2num(str, typeNum) *((typeNum *)(str))
41 // For JPEG 2000, body in file gdcmJpeg2000.cxx
42 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
44 #define JOCTET uint8_t
45 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
46 bool gdcm_read_JPEG_file8 (std::ifstream *fp, void *image_buffer);
47 bool gdcm_read_JPEG_memory8 (const JOCTET *buffer, const size_t buflen,
49 size_t *howManyRead, size_t *howManyWritten);
51 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
52 bool gdcm_read_JPEG_file12 (std::ifstream *fp, void *image_buffer);
53 bool gdcm_read_JPEG_memory12 (const JOCTET *buffer, const size_t buflen,
55 size_t *howManyRead, size_t *howManyWritten);
57 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
58 // Beware this is misleading there is no 16bits DCT algorithm, only
59 // jpeg lossless compression exist in 16bits.
60 bool gdcm_read_JPEG_file16 (std::ifstream *fp, void *image_buffer);
61 bool gdcm_read_JPEG_memory16 (const JOCTET *buffer, const size_t buflen,
63 size_t *howManyRead, size_t *howManyWritten);
66 //-----------------------------------------------------------------------------
67 // Constructor / Destructor
68 PixelReadConvert::PixelReadConvert()
80 void PixelReadConvert::Squeeze()
101 PixelReadConvert::~PixelReadConvert()
106 void PixelReadConvert::AllocateRGB()
111 RGB = new uint8_t[ RGBSize ];
114 void PixelReadConvert::AllocateRaw()
119 Raw = new uint8_t[ RawSize ];
123 * \brief Read from file a 12 bits per pixel image and decompress it
124 * into a 16 bits per pixel image.
126 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
127 throw ( FormatError )
129 int nbPixels = XSize * YSize;
130 uint16_t* localDecompres = (uint16_t*)Raw;
132 for( int p = 0; p < nbPixels; p += 2 )
136 fp->read( (char*)&b0, 1);
137 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
139 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
140 "Unfound first block" );
143 fp->read( (char*)&b1, 1 );
144 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
146 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
147 "Unfound second block" );
150 fp->read( (char*)&b2, 1 );
151 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
153 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
154 "Unfound second block" );
157 // Two steps are necessary to please VC++
159 // 2 pixels 12bit = [0xABCDEF]
160 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
162 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
164 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
166 /// \todo JPR Troubles expected on Big-Endian processors ?
171 * \brief Try to deal with RLE 16 Bits.
172 * We assume the RLE has allready been parsed and loaded in
173 * Raw (through \ref ReadAndDecompressJPEGFile ).
174 * We here need to make 16 Bits Pixels from Low Byte and
175 * High Byte 'Planes'...(for what it may mean)
178 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
180 size_t pixelNumber = XSize * YSize;
181 size_t rawSize = XSize * YSize * NumberOfFrames;
183 // We assumed Raw contains the decoded RLE pixels but as
184 // 8 bits per pixel. In order to convert those pixels to 16 bits
185 // per pixel we cannot work in place within Raw and hence
186 // we copy it in a safe place, say copyRaw.
188 uint8_t* copyRaw = new uint8_t[ rawSize * 2 ];
189 memmove( copyRaw, Raw, rawSize * 2 );
192 uint8_t* a = copyRaw;
193 uint8_t* b = a + pixelNumber;
195 for ( int i = 0; i < NumberOfFrames; i++ )
197 for ( unsigned int j = 0; j < pixelNumber; j++ )
206 /// \todo check that operator new []didn't fail, and sometimes return false
211 * \brief Implementation of the RLE decoding algorithm for decompressing
212 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
213 * @param subRaw Sub region of \ref Raw where the de
214 * decoded fragment should be placed.
215 * @param fragmentSize The length of the binary fragment as found on the disk.
216 * @param RawSegmentSize The expected length of the fragment ONCE
218 * @param fp File Pointer: on entry the position should be the one of
219 * the fragment to be decoded.
221 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t *subRaw,
227 long numberOfOutputBytes = 0;
228 long numberOfReadBytes = 0;
230 while( numberOfOutputBytes < RawSegmentSize )
232 fp->read( (char*)&count, 1 );
233 numberOfReadBytes += 1;
235 // Note: count <= 127 comparison is always true due to limited range
236 // of data type int8_t [since the maximum of an exact width
237 // signed integer of width N is 2^(N-1) - 1, which for int8_t
240 fp->read( (char*)subRaw, count + 1);
241 numberOfReadBytes += count + 1;
243 numberOfOutputBytes += count + 1;
247 if ( ( count <= -1 ) && ( count >= -127 ) )
250 fp->read( (char*)&newByte, 1);
251 numberOfReadBytes += 1;
252 for( int i = 0; i < -count + 1; i++ )
256 subRaw += -count + 1;
257 numberOfOutputBytes += -count + 1;
260 // if count = 128 output nothing
262 if ( numberOfReadBytes > fragmentSize )
264 gdcmVerboseMacro( "Read more bytes than the segment size.");
272 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
273 * Dicom encapsulated file and decompress it.
274 * @param fp already open File Pointer
275 * at which the pixel data should be copied
278 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream *fp )
280 uint8_t *subRaw = Raw;
281 long RawSegmentSize = XSize * YSize;
283 // Loop on the frame[s]
284 for( RLEFramesInfo::RLEFrameList::iterator
285 it = RLEInfo->Frames.begin();
286 it != RLEInfo->Frames.end();
289 // Loop on the fragments
290 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
292 fp->seekg( (*it)->Offset[k] , std::ios::beg );
293 (void)ReadAndDecompressRLEFragment( subRaw,
297 subRaw += RawSegmentSize;
301 if ( BitsAllocated == 16 )
303 // Try to deal with RLE 16 Bits
304 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
311 * \brief Swap the bytes, according to \ref SwapCode.
313 void PixelReadConvert::ConvertSwapZone()
317 if( BitsAllocated == 16 )
319 uint16_t *im16 = (uint16_t*)Raw;
330 for( i = 0; i < RawSize / 2; i++ )
332 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
336 gdcmVerboseMacro("SwapCode value (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 gdcmVerboseMacro("SwapCode value (32 bits) not allowed." );
388 * \brief Deal with endianity i.e. re-arange bytes inside the integer
390 void PixelReadConvert::ConvertReorderEndianity()
392 if ( BitsAllocated != 8 )
397 // Special kludge in order to deal with xmedcon broken images:
398 if ( ( BitsAllocated == 16 )
399 && ( BitsStored < BitsAllocated )
402 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
403 uint16_t *deb = (uint16_t *)Raw;
404 for(int i = 0; i<l; i++)
417 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
418 * file and decompress it. This funciton assumes that each
419 * jpeg fragment contains a whole frame (jpeg file).
420 * @param fp File Pointer
423 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream *fp )
425 uint8_t *localRaw = Raw;
426 // Loop on the fragment[s]
427 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
428 it = JPEGInfo->Fragments.begin();
429 it != JPEGInfo->Fragments.end();
432 fp->seekg( (*it)->Offset, std::ios::beg);
434 if ( BitsStored == 8)
436 // JPEG Lossy : call to IJG 6b
437 if ( ! gdcm_read_JPEG_file8( fp, localRaw ) )
442 else if ( BitsStored <= 12)
444 // Reading Fragment pixels
445 if ( ! gdcm_read_JPEG_file12 ( fp, localRaw ) )
450 else if ( BitsStored <= 16)
452 // Reading Fragment pixels
453 if ( ! gdcm_read_JPEG_file16 ( fp, localRaw ) )
457 //gdcmAssertMacro( IsJPEGLossless );
461 // other JPEG lossy not supported
462 gdcmErrorMacro( "Unknown jpeg lossy compression ");
466 // Advance to next free location in Raw
467 // for next fragment decompression (if any)
468 int length = XSize * YSize * SamplesPerPixel;
469 int numberBytes = BitsAllocated / 8;
471 localRaw += length * numberBytes;
477 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
478 * file and decompress it. This function assumes that the dicom
479 * image is a single frame split into several JPEG fragments.
480 * Those fragments will be glued together into a memory buffer
482 * @param fp File Pointer
485 bool PixelReadConvert::
486 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
488 // Loop on the fragment[s] to get total length
489 size_t totalLength = 0;
490 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
491 for( it = JPEGInfo->Fragments.begin();
492 it != JPEGInfo->Fragments.end();
495 totalLength += (*it)->Length;
498 // Concatenate the jpeg fragments into a local buffer
499 JOCTET *buffer = new JOCTET [totalLength];
502 // Loop on the fragment[s]
503 for( it = JPEGInfo->Fragments.begin();
504 it != JPEGInfo->Fragments.end();
507 fp->seekg( (*it)->Offset, std::ios::beg);
508 size_t len = (*it)->Length;
509 fp->read((char *)p,len);
513 size_t howManyRead = 0;
514 size_t howManyWritten = 0;
516 if ( BitsStored == 8)
518 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
519 &howManyRead, &howManyWritten ) )
521 gdcmErrorMacro( "Failed to read jpeg8 ");
526 else if ( BitsStored <= 12)
528 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
529 &howManyRead, &howManyWritten ) )
531 gdcmErrorMacro( "Failed to read jpeg12 ");
536 else if ( BitsStored <= 16)
539 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
540 &howManyRead, &howManyWritten ) )
542 gdcmErrorMacro( "Failed to read jpeg16 ");
549 // other JPEG lossy not supported
550 gdcmErrorMacro( "Unknown jpeg lossy compression ");
562 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
563 * file and decompress it. This function handles the generic
564 * and complex case where the DICOM contains several frames,
565 * and some of the frames are possibly split into several JPEG
567 * @param fp File Pointer
570 bool PixelReadConvert::
571 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
573 // Loop on the fragment[s] to get total length
574 size_t totalLength = 0;
575 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
576 for( it = JPEGInfo->Fragments.begin();
577 it != JPEGInfo->Fragments.end();
580 totalLength += (*it)->Length;
583 // Concatenate the jpeg fragments into a local buffer
584 JOCTET *buffer = new JOCTET [totalLength];
587 // Loop on the fragment[s]
588 for( it = JPEGInfo->Fragments.begin();
589 it != JPEGInfo->Fragments.end();
592 fp->seekg( (*it)->Offset, std::ios::beg);
593 size_t len = (*it)->Length;
594 fp->read((char *)p,len);
598 size_t howManyRead = 0;
599 size_t howManyWritten = 0;
600 size_t fragmentLength = 0;
602 for( it = JPEGInfo->Fragments.begin() ;
603 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
606 fragmentLength += (*it)->Length;
608 if (howManyRead > fragmentLength) continue;
610 if ( BitsStored == 8)
612 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
614 &howManyRead, &howManyWritten ) )
616 gdcmErrorMacro( "Failed to read jpeg8");
621 else if ( BitsStored <= 12)
624 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
626 &howManyRead, &howManyWritten ) )
628 gdcmErrorMacro( "Failed to read jpeg12");
633 else if ( BitsStored <= 16)
636 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
638 &howManyRead, &howManyWritten ) )
640 gdcmErrorMacro( "Failed to read jpeg16 ");
647 // other JPEG lossy not supported
648 gdcmErrorMacro( "Unknown jpeg lossy compression ");
653 if (howManyRead < fragmentLength)
654 howManyRead = fragmentLength;
664 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
665 * file and decompress it.
666 * @param fp File Pointer
669 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
673 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
674 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
678 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
680 // we have one frame split into several fragments
681 // we will pack those fragments into a single buffer and
683 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
685 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
687 // suppose each fragment is a frame
688 return ReadAndDecompressJPEGFramesFromFile( fp );
692 // The dicom image contains frames containing fragments of images
693 // a more complex algorithm :-)
694 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
699 * \brief Re-arrange the bits within the bytes.
702 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
704 if ( BitsStored != BitsAllocated )
706 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
707 if ( BitsAllocated == 16 )
709 uint16_t mask = 0xffff;
710 mask = mask >> ( BitsAllocated - BitsStored );
711 uint16_t* deb = (uint16_t*)Raw;
712 for(int i = 0; i<l; i++)
714 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
718 else if ( BitsAllocated == 32 )
720 uint32_t mask = 0xffffffff;
721 mask = mask >> ( BitsAllocated - BitsStored );
722 uint32_t* deb = (uint32_t*)Raw;
723 for(int i = 0; i<l; i++)
725 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
731 gdcmVerboseMacro("Weird image");
732 throw FormatError( "Weird image !?" );
739 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
740 * \warning Works on all the frames at a time
742 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
744 uint8_t *localRaw = Raw;
745 uint8_t *copyRaw = new uint8_t[ RawSize ];
746 memmove( copyRaw, localRaw, RawSize );
748 // to see the tricks about YBR_FULL, YBR_FULL_422,
749 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
750 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
751 // and be *very* affraid
753 int l = XSize * YSize;
754 int nbFrames = ZSize;
756 uint8_t *a = copyRaw;
757 uint8_t *b = copyRaw + l;
758 uint8_t *c = copyRaw + l + l;
761 /// \todo : Replace by the 'well known' integer computation
762 /// counterpart. Refer to
763 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
764 /// for code optimisation.
766 for ( int i = 0; i < nbFrames; i++ )
768 for ( int j = 0; j < l; j++ )
770 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
771 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
772 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
774 if (R < 0.0) R = 0.0;
775 if (G < 0.0) G = 0.0;
776 if (B < 0.0) B = 0.0;
777 if (R > 255.0) R = 255.0;
778 if (G > 255.0) G = 255.0;
779 if (B > 255.0) B = 255.0;
781 *(localRaw++) = (uint8_t)R;
782 *(localRaw++) = (uint8_t)G;
783 *(localRaw++) = (uint8_t)B;
793 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
794 * \warning Works on all the frames at a time
796 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
798 uint8_t *localRaw = Raw;
799 uint8_t *copyRaw = new uint8_t[ RawSize ];
800 memmove( copyRaw, localRaw, RawSize );
802 int l = XSize * YSize * ZSize;
804 uint8_t* a = copyRaw;
805 uint8_t* b = copyRaw + l;
806 uint8_t* c = copyRaw + l + l;
808 for (int j = 0; j < l; j++)
810 *(localRaw++) = *(a++);
811 *(localRaw++) = *(b++);
812 *(localRaw++) = *(c++);
817 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
819 // ComputeRawAndRGBSizes is already made by
820 // ::GrabInformationsFromHeader. So, the structure sizes are
824 //////////////////////////////////////////////////
825 //// First stage: get our hands on the Pixel Data.
828 gdcmVerboseMacro( "Unavailable file pointer." );
832 fp->seekg( PixelOffset, std::ios::beg );
833 if( fp->fail() || fp->eof())
835 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
841 //////////////////////////////////////////////////
842 //// Second stage: read from disk dans decompress.
843 if ( BitsAllocated == 12 )
845 ReadAndDecompress12BitsTo16Bits( fp);
849 // This problem can be found when some obvious informations are found
850 // after the field containing the image datas. In this case, these
851 // bad datas are added to the size of the image (in the PixelDataLength
852 // variable). But RawSize is the right size of the image !
853 if( PixelDataLength != RawSize)
855 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
857 if( PixelDataLength > RawSize)
859 fp->read( (char*)Raw, RawSize);
863 fp->read( (char*)Raw, PixelDataLength);
866 if ( fp->fail() || fp->eof())
868 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
872 else if ( IsRLELossless )
874 if ( ! ReadAndDecompressRLEFile( fp ) )
876 gdcmVerboseMacro( "RLE decompressor failed." );
882 // Default case concerns JPEG family
883 if ( ! ReadAndDecompressJPEGFile( fp ) )
885 gdcmVerboseMacro( "JPEG decompressor failed." );
890 ////////////////////////////////////////////
891 //// Third stage: twigle the bytes and bits.
892 ConvertReorderEndianity();
893 ConvertReArrangeBits();
894 ConvertHandleColor();
899 void PixelReadConvert::ConvertHandleColor()
901 //////////////////////////////////
902 // Deal with the color decoding i.e. handle:
903 // - R, G, B planes (as opposed to RGB pixels)
904 // - YBR (various) encodings.
905 // - LUT[s] (or "PALETTE COLOR").
907 // The classification in the color decoding schema is based on the blending
908 // of two Dicom tags values:
909 // * "Photometric Interpretation" for which we have the cases:
910 // - [Photo A] MONOCHROME[1|2] pictures,
911 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
912 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
913 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
914 // * "Planar Configuration" for which we have the cases:
915 // - [Planar 0] 0 then Pixels are already RGB
916 // - [Planar 1] 1 then we have 3 planes : R, G, B,
917 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
919 // Now in theory, one could expect some coherence when blending the above
920 // cases. For example we should not encounter files belonging at the
921 // time to case [Planar 0] and case [Photo D].
922 // Alas, this was only theory ! Because in practice some odd (read ill
923 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
924 // - "Planar Configuration" = 0,
925 // - "Photometric Interpretation" = "PALETTE COLOR".
926 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
927 // towards Dicom-non-conformance files:
928 // << whatever the "Planar Configuration" value might be, a
929 // "Photometric Interpretation" set to "PALETTE COLOR" forces
930 // a LUT intervention >>
932 // Now we are left with the following handling of the cases:
933 // - [Planar 0] OR [Photo A] no color decoding (since respectively
934 // Pixels are already RGB and monochrome pictures have no color :),
935 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
936 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
937 // - [Planar 2] OR [Photo D] requires LUT intervention.
941 // [Planar 2] OR [Photo D]: LUT intervention done outside
945 if ( PlanarConfiguration == 1 )
949 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
950 ConvertYcBcRPlanesToRGBPixels();
954 // [Planar 1] AND [Photo C]
955 ConvertRGBPlanesToRGBPixels();
960 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
961 // pixels need to be RGB-fied anyway
964 ConvertRGBPlanesToRGBPixels();
966 // In *normal *case, when planarConf is 0, pixels are already in RGB
970 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
971 * \note See comments of \ref ConvertHandleColor
973 bool PixelReadConvert::IsRawRGB()
976 || PlanarConfiguration == 2
984 void PixelReadConvert::ComputeRawAndRGBSizes()
986 int bitsAllocated = BitsAllocated;
987 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
988 // in this case we will expand the image to 16 bits (see
989 // \ref ReadAndDecompress12BitsTo16Bits() )
990 if ( BitsAllocated == 12 )
995 RawSize = XSize * YSize * ZSize
996 * ( bitsAllocated / 8 )
1000 RGBSize = 3 * RawSize;
1008 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
1010 // Number of Bits Allocated for storing a Pixel is defaulted to 16
1011 // when absent from the header.
1012 BitsAllocated = header->GetBitsAllocated();
1013 if ( BitsAllocated == 0 )
1018 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1019 // when absent from the header.
1020 BitsStored = header->GetBitsStored();
1021 if ( BitsStored == 0 )
1023 BitsStored = BitsAllocated;
1026 // High Bit Position
1027 HighBitPosition = header->GetHighBitPosition();
1028 if ( HighBitPosition == 0 )
1030 HighBitPosition = BitsAllocated - 1;
1033 XSize = header->GetXSize();
1034 YSize = header->GetYSize();
1035 ZSize = header->GetZSize();
1036 SamplesPerPixel = header->GetSamplesPerPixel();
1037 PixelSize = header->GetPixelSize();
1038 PixelSign = header->IsSignedPixelData();
1039 SwapCode = header->GetSwapCode();
1040 std::string ts = header->GetTransferSyntax();
1042 ( ! header->IsDicomV3() )
1043 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
1044 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
1045 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
1046 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
1047 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
1048 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
1049 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
1050 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
1051 PixelOffset = header->GetPixelOffset();
1052 PixelDataLength = header->GetPixelAreaLength();
1053 RLEInfo = header->GetRLEInfo();
1054 JPEGInfo = header->GetJPEGInfo();
1056 PlanarConfiguration = header->GetPlanarConfiguration();
1057 IsMonochrome = header->IsMonochrome();
1058 IsPaletteColor = header->IsPaletteColor();
1059 IsYBRFull = header->IsYBRFull();
1061 /////////////////////////////////////////////////////////////////
1063 HasLUT = header->HasLUT();
1066 // Just in case some access to a Header element requires disk access.
1067 LutRedDescriptor = header->GetEntry( 0x0028, 0x1101 );
1068 LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
1069 LutBlueDescriptor = header->GetEntry( 0x0028, 0x1103 );
1071 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1072 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1073 // Document::Document() ], the loading of the value (content) of a
1074 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1075 // loaded). Hence, we first try to obtain the LUTs data from the header
1076 // and when this fails we read the LUTs data directely from disk.
1077 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1078 /// We should NOT bypass the [Bin|Val]Entry class. Instead
1079 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
1080 /// (e.g. BinEntry::GetBinArea()) should force disk access from
1081 /// within the [Bin|Val]Entry class itself. The only problem
1082 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
1083 /// parsed from. Fix that. FIXME.
1086 header->LoadEntryBinArea(0x0028, 0x1201);
1087 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
1090 gdcmVerboseMacro( "Unable to read red LUT data" );
1094 header->LoadEntryBinArea(0x0028, 0x1202);
1095 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
1096 if ( ! LutGreenData)
1098 gdcmVerboseMacro( "Unable to read green LUT data" );
1102 header->LoadEntryBinArea(0x0028, 0x1203);
1103 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
1104 if ( ! LutBlueData )
1106 gdcmVerboseMacro( "Unable to read blue LUT data" );
1110 ComputeRawAndRGBSizes();
1114 * \brief Build Red/Green/Blue/Alpha LUT from Header
1115 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1116 * and (0028,1101),(0028,1102),(0028,1102)
1117 * - xxx Palette Color Lookup Table Descriptor - are found
1118 * and (0028,1201),(0028,1202),(0028,1202)
1119 * - xxx Palette Color Lookup Table Data - are found
1120 * \warning does NOT deal with :
1121 * 0028 1100 Gray Lookup Table Descriptor (Retired)
1122 * 0028 1221 Segmented Red Palette Color Lookup Table Data
1123 * 0028 1222 Segmented Green Palette Color Lookup Table Data
1124 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
1125 * no known Dicom reader deals with them :-(
1126 * @return a RGBA Lookup Table
1128 void PixelReadConvert::BuildLUTRGBA()
1134 // Not so easy : see
1135 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1137 if ( ! IsPaletteColor )
1142 if ( LutRedDescriptor == GDCM_UNFOUND
1143 || LutGreenDescriptor == GDCM_UNFOUND
1144 || LutBlueDescriptor == GDCM_UNFOUND )
1149 ////////////////////////////////////////////
1150 // Extract the info from the LUT descriptors
1151 int lengthR; // Red LUT length in Bytes
1152 int debR; // Subscript of the first Lut Value
1153 int nbitsR; // Lut item size (in Bits)
1154 int nbRead = sscanf( LutRedDescriptor.c_str(),
1156 &lengthR, &debR, &nbitsR );
1159 gdcmVerboseMacro( "Wrong red LUT descriptor" );
1162 int lengthG; // Green LUT length in Bytes
1163 int debG; // Subscript of the first Lut Value
1164 int nbitsG; // Lut item size (in Bits)
1165 nbRead = sscanf( LutGreenDescriptor.c_str(),
1167 &lengthG, &debG, &nbitsG );
1170 gdcmVerboseMacro( "Wrong green LUT descriptor" );
1173 int lengthB; // Blue LUT length in Bytes
1174 int debB; // Subscript of the first Lut Value
1175 int nbitsB; // Lut item size (in Bits)
1176 nbRead = sscanf( LutRedDescriptor.c_str(),
1178 &lengthB, &debB, &nbitsB );
1181 gdcmVerboseMacro( "Wrong blue LUT descriptor" );
1184 ////////////////////////////////////////////////////////
1185 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1190 ////////////////////////////////////////////////
1191 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1192 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1197 memset( LutRGBA, 0, 1024 );
1200 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1202 // when LUT item size is different than pixel size
1203 mult = 2; // high byte must be = low byte
1207 // See PS 3.3-2003 C.11.1.1.2 p 619
1211 // if we get a black image, let's just remove the '+1'
1212 // from 'i*mult+1' and check again
1213 // if it works, we shall have to check the 3 Palettes
1214 // to see which byte is ==0 (first one, or second one)
1216 // We give up the checking to avoid some (useless ?)overhead
1217 // (optimistic asumption)
1219 uint8_t* a = LutRGBA + 0;
1220 for( i=0; i < lengthR; ++i )
1222 *a = LutRedData[i*mult+1];
1227 for( i=0; i < lengthG; ++i)
1229 *a = LutGreenData[i*mult+1];
1234 for(i=0; i < lengthB; ++i)
1236 *a = LutBlueData[i*mult+1];
1241 for(i=0; i < 256; ++i)
1243 *a = 1; // Alpha component
1249 * \brief Build the RGB image from the Raw imagage and the LUTs.
1251 bool PixelReadConvert::BuildRGBImage()
1255 // The job is already done.
1261 // The job can't be done
1268 // The job can't be done
1274 uint8_t* localRGB = RGB;
1275 for (size_t i = 0; i < RawSize; ++i )
1278 *localRGB++ = LutRGBA[j];
1279 *localRGB++ = LutRGBA[j+1];
1280 *localRGB++ = LutRGBA[j+2];
1286 * \brief Print self.
1287 * @param os Stream to print to.
1289 void PixelReadConvert::Print( std::ostream &os )
1295 * \brief Print self.
1296 * @param indent Indentation string to be prepended during printing.
1297 * @param os Stream to print to.
1299 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1302 << "--- Pixel information -------------------------"
1305 << "Pixel Data: offset " << PixelOffset
1306 << " x(" << std::hex << PixelOffset << std::dec
1307 << ") length " << PixelDataLength
1308 << " x(" << std::hex << PixelDataLength << std::dec
1309 << ")" << std::endl;
1311 if ( IsRLELossless )
1315 RLEInfo->Print( indent, os );
1319 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1323 if ( IsJPEG2000 || IsJPEGLossless )
1327 JPEGInfo->Print( indent, os );
1331 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1336 } // end namespace gdcm
1338 // NOTES on File internal calls
1340 // ---> GetImageData
1341 // ---> GetImageDataIntoVector
1342 // |---> GetImageDataIntoVectorRaw
1343 // | lut intervention
1345 // ---> GetImageDataRaw
1346 // ---> GetImageDataIntoVectorRaw