1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/07 22:03:30 $
7 Version: $Revision: 1.17 $
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 //assert( IsJPEGLossless );
459 // other JPEG lossy not supported
460 gdcmErrorMacro("PixelReadConvert::ReadAndDecompressJPEGFile: unknown "
461 "jpeg lossy compression ");
465 // Advance to next free location in Raw
466 // for next fragment decompression (if any)
467 int length = XSize * YSize * SamplesPerPixel;
468 int numberBytes = BitsAllocated / 8;
470 localRaw += length * numberBytes;
476 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
477 * file and decompress it. This function assumes that the dicom
478 * image is a single frame split into several JPEG fragments.
479 * Those fragments will be glued together into a memory buffer
481 * @param fp File Pointer
484 bool PixelReadConvert::
485 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
487 // Loop on the fragment[s] to get total length
488 size_t totalLength = 0;
489 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
490 for( it = JPEGInfo->Fragments.begin();
491 it != JPEGInfo->Fragments.end();
494 totalLength += (*it)->Length;
497 // Concatenate the jpeg fragments into a local buffer
498 JOCTET *buffer = new JOCTET [totalLength];
501 // Loop on the fragment[s]
502 for( it = JPEGInfo->Fragments.begin();
503 it != JPEGInfo->Fragments.end();
506 fp->seekg( (*it)->Offset, std::ios::beg);
507 size_t len = (*it)->Length;
508 fp->read((char *)p,len);
512 size_t howManyRead = 0;
513 size_t howManyWritten = 0;
515 if ( BitsStored == 8)
517 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
518 &howManyRead, &howManyWritten ) )
521 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 "
527 else if ( BitsStored <= 12)
529 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
530 &howManyRead, &howManyWritten ) )
533 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 "
539 else if ( BitsStored <= 16)
542 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
543 &howManyRead, &howManyWritten ) )
546 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 "
554 // other JPEG lossy not supported
555 gdcmErrorMacro("PixelConvert::ReadAndDecompressJPEGFile: unknown "
556 "jpeg lossy compression ");
568 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
569 * file and decompress it. This function handles the generic
570 * and complex case where the DICOM contains several frames,
571 * and some of the frames are possibly split into several JPEG
573 * @param fp File Pointer
576 bool PixelReadConvert::
577 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
579 // Loop on the fragment[s] to get total length
580 size_t totalLength = 0;
581 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
582 for( it = JPEGInfo->Fragments.begin();
583 it != JPEGInfo->Fragments.end();
586 totalLength += (*it)->Length;
589 // Concatenate the jpeg fragments into a local buffer
590 JOCTET *buffer = new JOCTET [totalLength];
593 // Loop on the fragment[s]
594 for( it = JPEGInfo->Fragments.begin();
595 it != JPEGInfo->Fragments.end();
598 fp->seekg( (*it)->Offset, std::ios::beg);
599 size_t len = (*it)->Length;
600 fp->read((char *)p,len);
604 size_t howManyRead = 0;
605 size_t howManyWritten = 0;
606 size_t fragmentLength = 0;
608 for( it = JPEGInfo->Fragments.begin() ;
609 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
612 fragmentLength += (*it)->Length;
614 if (howManyRead > fragmentLength) continue;
616 if ( BitsStored == 8)
618 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
620 &howManyRead, &howManyWritten ) )
622 gdcmErrorMacro("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 ");
627 else if ( BitsStored <= 12)
630 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
632 &howManyRead, &howManyWritten ) )
634 gdcmErrorMacro("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 ");
639 else if ( BitsStored <= 16)
642 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
644 &howManyRead, &howManyWritten ) )
646 gdcmErrorMacro("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 ");
653 // other JPEG lossy not supported
654 gdcmErrorMacro("PixelConvert::ReadAndDecompressJPEGFile: unknown "
655 "jpeg lossy compression ");
660 if (howManyRead < fragmentLength)
661 howManyRead = fragmentLength;
671 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
672 * file and decompress it.
673 * @param fp File Pointer
676 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
680 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
681 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
685 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
687 // we have one frame split into several fragments
688 // we will pack those fragments into a single buffer and
690 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
692 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
694 // suppose each fragment is a frame
695 return ReadAndDecompressJPEGFramesFromFile( fp );
699 // The dicom image contains frames containing fragments of images
700 // a more complex algorithm :-)
701 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
706 * \brief Re-arrange the bits within the bytes.
709 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
711 if ( BitsStored != BitsAllocated )
713 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
714 if ( BitsAllocated == 16 )
716 uint16_t mask = 0xffff;
717 mask = mask >> ( BitsAllocated - BitsStored );
718 uint16_t* deb = (uint16_t*)Raw;
719 for(int i = 0; i<l; i++)
721 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
725 else if ( BitsAllocated == 32 )
727 uint32_t mask = 0xffffffff;
728 mask = mask >> ( BitsAllocated - BitsStored );
729 uint32_t* deb = (uint32_t*)Raw;
730 for(int i = 0; i<l; i++)
732 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
738 gdcmVerboseMacro("Weird image");
739 throw FormatError( "Weird image !?" );
746 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
747 * \warning Works on all the frames at a time
749 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
751 uint8_t *localRaw = Raw;
752 uint8_t *copyRaw = new uint8_t[ RawSize ];
753 memmove( copyRaw, localRaw, RawSize );
755 // to see the tricks about YBR_FULL, YBR_FULL_422,
756 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
757 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
758 // and be *very* affraid
760 int l = XSize * YSize;
761 int nbFrames = ZSize;
763 uint8_t *a = copyRaw;
764 uint8_t *b = copyRaw + l;
765 uint8_t *c = copyRaw + l + l;
768 /// \todo : Replace by the 'well known' integer computation
769 /// counterpart. Refer to
770 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
771 /// for code optimisation.
773 for ( int i = 0; i < nbFrames; i++ )
775 for ( int j = 0; j < l; j++ )
777 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
778 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
779 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
781 if (R < 0.0) R = 0.0;
782 if (G < 0.0) G = 0.0;
783 if (B < 0.0) B = 0.0;
784 if (R > 255.0) R = 255.0;
785 if (G > 255.0) G = 255.0;
786 if (B > 255.0) B = 255.0;
788 *(localRaw++) = (uint8_t)R;
789 *(localRaw++) = (uint8_t)G;
790 *(localRaw++) = (uint8_t)B;
800 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
801 * \warning Works on all the frames at a time
803 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
805 uint8_t *localRaw = Raw;
806 uint8_t *copyRaw = new uint8_t[ RawSize ];
807 memmove( copyRaw, localRaw, RawSize );
809 int l = XSize * YSize * ZSize;
811 uint8_t* a = copyRaw;
812 uint8_t* b = copyRaw + l;
813 uint8_t* c = copyRaw + l + l;
815 for (int j = 0; j < l; j++)
817 *(localRaw++) = *(a++);
818 *(localRaw++) = *(b++);
819 *(localRaw++) = *(c++);
824 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
826 // ComputeRawAndRGBSizes is already made by
827 // ::GrabInformationsFromHeader. So, the structure sizes are
831 //////////////////////////////////////////////////
832 //// First stage: get our hands on the Pixel Data.
835 gdcmVerboseMacro( "Unavailable file pointer." );
839 fp->seekg( PixelOffset, std::ios::beg );
840 if( fp->fail() || fp->eof())
842 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
848 //////////////////////////////////////////////////
849 //// Second stage: read from disk dans decompress.
850 if ( BitsAllocated == 12 )
852 ReadAndDecompress12BitsTo16Bits( fp);
856 // This problem can be found when some obvious informations are found
857 // after the field containing the image datas. In this case, these
858 // bad datas are added to the size of the image (in the PixelDataLength
859 // variable). But RawSize is the right size of the image !
860 if( PixelDataLength != RawSize)
862 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
864 if( PixelDataLength > RawSize)
866 fp->read( (char*)Raw, RawSize);
870 fp->read( (char*)Raw, PixelDataLength);
873 if ( fp->fail() || fp->eof())
875 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
879 else if ( IsRLELossless )
881 if ( ! ReadAndDecompressRLEFile( fp ) )
883 gdcmVerboseMacro( "RLE decompressor failed." );
889 // Default case concerns JPEG family
890 if ( ! ReadAndDecompressJPEGFile( fp ) )
892 gdcmVerboseMacro( "JPEG decompressor failed." );
897 ////////////////////////////////////////////
898 //// Third stage: twigle the bytes and bits.
899 ConvertReorderEndianity();
900 ConvertReArrangeBits();
901 ConvertHandleColor();
906 void PixelReadConvert::ConvertHandleColor()
908 //////////////////////////////////
909 // Deal with the color decoding i.e. handle:
910 // - R, G, B planes (as opposed to RGB pixels)
911 // - YBR (various) encodings.
912 // - LUT[s] (or "PALETTE COLOR").
914 // The classification in the color decoding schema is based on the blending
915 // of two Dicom tags values:
916 // * "Photometric Interpretation" for which we have the cases:
917 // - [Photo A] MONOCHROME[1|2] pictures,
918 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
919 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
920 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
921 // * "Planar Configuration" for which we have the cases:
922 // - [Planar 0] 0 then Pixels are already RGB
923 // - [Planar 1] 1 then we have 3 planes : R, G, B,
924 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
926 // Now in theory, one could expect some coherence when blending the above
927 // cases. For example we should not encounter files belonging at the
928 // time to case [Planar 0] and case [Photo D].
929 // Alas, this was only theory ! Because in practice some odd (read ill
930 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
931 // - "Planar Configuration" = 0,
932 // - "Photometric Interpretation" = "PALETTE COLOR".
933 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
934 // towards Dicom-non-conformance files:
935 // << whatever the "Planar Configuration" value might be, a
936 // "Photometric Interpretation" set to "PALETTE COLOR" forces
937 // a LUT intervention >>
939 // Now we are left with the following handling of the cases:
940 // - [Planar 0] OR [Photo A] no color decoding (since respectively
941 // Pixels are already RGB and monochrome pictures have no color :),
942 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
943 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
944 // - [Planar 2] OR [Photo D] requires LUT intervention.
948 // [Planar 2] OR [Photo D]: LUT intervention done outside
952 if ( PlanarConfiguration == 1 )
956 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
957 ConvertYcBcRPlanesToRGBPixels();
961 // [Planar 1] AND [Photo C]
962 ConvertRGBPlanesToRGBPixels();
967 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
968 // pixels need to be RGB-fied anyway
971 ConvertRGBPlanesToRGBPixels();
973 // In *normal *case, when planarConf is 0, pixels are already in RGB
977 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
978 * \note See comments of \ref ConvertHandleColor
980 bool PixelReadConvert::IsRawRGB()
983 || PlanarConfiguration == 2
991 void PixelReadConvert::ComputeRawAndRGBSizes()
993 int bitsAllocated = BitsAllocated;
994 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
995 // in this case we will expand the image to 16 bits (see
996 // \ref ReadAndDecompress12BitsTo16Bits() )
997 if ( BitsAllocated == 12 )
1002 RawSize = XSize * YSize * ZSize
1003 * ( bitsAllocated / 8 )
1007 RGBSize = 3 * RawSize;
1015 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
1017 // Number of Bits Allocated for storing a Pixel is defaulted to 16
1018 // when absent from the header.
1019 BitsAllocated = header->GetBitsAllocated();
1020 if ( BitsAllocated == 0 )
1025 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1026 // when absent from the header.
1027 BitsStored = header->GetBitsStored();
1028 if ( BitsStored == 0 )
1030 BitsStored = BitsAllocated;
1033 // High Bit Position
1034 HighBitPosition = header->GetHighBitPosition();
1035 if ( HighBitPosition == 0 )
1037 HighBitPosition = BitsAllocated - 1;
1040 XSize = header->GetXSize();
1041 YSize = header->GetYSize();
1042 ZSize = header->GetZSize();
1043 SamplesPerPixel = header->GetSamplesPerPixel();
1044 PixelSize = header->GetPixelSize();
1045 PixelSign = header->IsSignedPixelData();
1046 SwapCode = header->GetSwapCode();
1047 TransferSyntaxType ts = header->GetTransferSyntax();
1049 ( ! header->IsDicomV3() )
1050 || ts == ImplicitVRLittleEndian
1051 || ts == ImplicitVRLittleEndianDLXGE
1052 || ts == ExplicitVRLittleEndian
1053 || ts == ExplicitVRBigEndian
1054 || ts == DeflatedExplicitVRLittleEndian;
1055 IsJPEG2000 = header->IsJPEG2000();
1056 IsJPEGLossless = header->IsJPEGLossless();
1057 IsRLELossless = ( ts == RLELossless );
1058 PixelOffset = header->GetPixelOffset();
1059 PixelDataLength = header->GetPixelAreaLength();
1060 RLEInfo = header->GetRLEInfo();
1061 JPEGInfo = header->GetJPEGInfo();
1063 PlanarConfiguration = header->GetPlanarConfiguration();
1064 IsMonochrome = header->IsMonochrome();
1065 IsPaletteColor = header->IsPaletteColor();
1066 IsYBRFull = header->IsYBRFull();
1068 /////////////////////////////////////////////////////////////////
1070 HasLUT = header->HasLUT();
1073 // Just in case some access to a Header element requires disk access.
1074 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
1075 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
1076 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
1078 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1079 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1080 // Document::Document() ], the loading of the value (content) of a
1081 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1082 // loaded). Hence, we first try to obtain the LUTs data from the header
1083 // and when this fails we read the LUTs data directely from disk.
1084 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1085 /// We should NOT bypass the [Bin|Val]Entry class. Instead
1086 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
1087 /// (e.g. BinEntry::GetBinArea()) should force disk access from
1088 /// within the [Bin|Val]Entry class itself. The only problem
1089 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
1090 /// parsed from. Fix that. FIXME.
1093 header->LoadEntryBinArea(0x0028, 0x1201);
1094 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
1097 gdcmVerboseMacro( "Unable to read red LUT data" );
1101 header->LoadEntryBinArea(0x0028, 0x1202);
1102 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
1103 if ( ! LutGreenData)
1105 gdcmVerboseMacro( "Unable to read green LUT data" );
1109 header->LoadEntryBinArea(0x0028, 0x1203);
1110 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
1111 if ( ! LutBlueData )
1113 gdcmVerboseMacro( "Unable to read blue LUT data" );
1117 ComputeRawAndRGBSizes();
1121 * \brief Build Red/Green/Blue/Alpha LUT from Header
1122 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1123 * and (0028,1101),(0028,1102),(0028,1102)
1124 * - xxx Palette Color Lookup Table Descriptor - are found
1125 * and (0028,1201),(0028,1202),(0028,1202)
1126 * - xxx Palette Color Lookup Table Data - are found
1127 * \warning does NOT deal with :
1128 * 0028 1100 Gray Lookup Table Descriptor (Retired)
1129 * 0028 1221 Segmented Red Palette Color Lookup Table Data
1130 * 0028 1222 Segmented Green Palette Color Lookup Table Data
1131 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
1132 * no known Dicom reader deals with them :-(
1133 * @return a RGBA Lookup Table
1135 void PixelReadConvert::BuildLUTRGBA()
1141 // Not so easy : see
1142 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1144 if ( ! IsPaletteColor )
1149 if ( LutRedDescriptor == GDCM_UNFOUND
1150 || LutGreenDescriptor == GDCM_UNFOUND
1151 || LutBlueDescriptor == GDCM_UNFOUND )
1156 ////////////////////////////////////////////
1157 // Extract the info from the LUT descriptors
1158 int lengthR; // Red LUT length in Bytes
1159 int debR; // Subscript of the first Lut Value
1160 int nbitsR; // Lut item size (in Bits)
1161 int nbRead = sscanf( LutRedDescriptor.c_str(),
1163 &lengthR, &debR, &nbitsR );
1166 gdcmVerboseMacro( "Wrong red LUT descriptor" );
1169 int lengthG; // Green LUT length in Bytes
1170 int debG; // Subscript of the first Lut Value
1171 int nbitsG; // Lut item size (in Bits)
1172 nbRead = sscanf( LutGreenDescriptor.c_str(),
1174 &lengthG, &debG, &nbitsG );
1177 gdcmVerboseMacro( "Wrong green LUT descriptor" );
1180 int lengthB; // Blue LUT length in Bytes
1181 int debB; // Subscript of the first Lut Value
1182 int nbitsB; // Lut item size (in Bits)
1183 nbRead = sscanf( LutRedDescriptor.c_str(),
1185 &lengthB, &debB, &nbitsB );
1188 gdcmVerboseMacro( "Wrong blue LUT descriptor" );
1191 ////////////////////////////////////////////////////////
1192 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1197 ////////////////////////////////////////////////
1198 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1199 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1204 memset( LutRGBA, 0, 1024 );
1207 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1209 // when LUT item size is different than pixel size
1210 mult = 2; // high byte must be = low byte
1214 // See PS 3.3-2003 C.11.1.1.2 p 619
1218 // if we get a black image, let's just remove the '+1'
1219 // from 'i*mult+1' and check again
1220 // if it works, we shall have to check the 3 Palettes
1221 // to see which byte is ==0 (first one, or second one)
1223 // We give up the checking to avoid some (useless ?)overhead
1224 // (optimistic asumption)
1226 uint8_t* a = LutRGBA + 0;
1227 for( i=0; i < lengthR; ++i )
1229 *a = LutRedData[i*mult+1];
1234 for( i=0; i < lengthG; ++i)
1236 *a = LutGreenData[i*mult+1];
1241 for(i=0; i < lengthB; ++i)
1243 *a = LutBlueData[i*mult+1];
1248 for(i=0; i < 256; ++i)
1250 *a = 1; // Alpha component
1256 * \brief Build the RGB image from the Raw imagage and the LUTs.
1258 bool PixelReadConvert::BuildRGBImage()
1262 // The job is already done.
1268 // The job can't be done
1275 // The job can't be done
1281 uint8_t* localRGB = RGB;
1282 for (size_t i = 0; i < RawSize; ++i )
1285 *localRGB++ = LutRGBA[j];
1286 *localRGB++ = LutRGBA[j+1];
1287 *localRGB++ = LutRGBA[j+2];
1293 * \brief Print self.
1294 * @param os Stream to print to.
1296 void PixelReadConvert::Print( std::ostream &os )
1302 * \brief Print self.
1303 * @param indent Indentation string to be prepended during printing.
1304 * @param os Stream to print to.
1306 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1309 << "--- Pixel information -------------------------"
1312 << "Pixel Data: offset " << PixelOffset
1313 << " x(" << std::hex << PixelOffset << std::dec
1314 << ") length " << PixelDataLength
1315 << " x(" << std::hex << PixelDataLength << std::dec
1316 << ")" << std::endl;
1318 if ( IsRLELossless )
1322 RLEInfo->Print( indent, os );
1326 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1330 if ( IsJPEG2000 || IsJPEGLossless )
1334 JPEGInfo->Print( indent, os );
1338 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1343 } // end namespace gdcm
1345 // NOTES on File internal calls
1347 // ---> GetImageData
1348 // ---> GetImageDataIntoVector
1349 // |---> GetImageDataIntoVectorRaw
1350 // | lut intervention
1352 // ---> GetImageDataRaw
1353 // ---> GetImageDataIntoVectorRaw