1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/01/12 15:22:23 $
7 Version: $Revision: 1.25 $
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 already 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;
327 for( i = 0; i < RawSize / 2; i++ )
329 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
333 gdcmVerboseMacro("SwapCode value (16 bits) not allowed.");
336 else if( BitsAllocated == 32 )
341 uint32_t* im32 = (uint32_t*)Raw;
347 for( i = 0; i < RawSize / 4; i++ )
349 low = im32[i] & 0x0000ffff; // 4321
350 high = im32[i] >> 16;
351 high = ( high >> 8 ) | ( high << 8 );
352 low = ( low >> 8 ) | ( low << 8 );
354 im32[i] = ( s32 << 16 ) | high;
358 for( i = 0; i < RawSize / 4; i++ )
360 low = im32[i] & 0x0000ffff; // 2143
361 high = im32[i] >> 16;
362 high = ( high >> 8 ) | ( high << 8 );
363 low = ( low >> 8 ) | ( low << 8 );
365 im32[i] = ( s32 << 16 ) | low;
369 for( i = 0; i < RawSize / 4; i++ )
371 low = im32[i] & 0x0000ffff; // 3412
372 high = im32[i] >> 16;
374 im32[i] = ( s32 << 16 ) | high;
378 gdcmVerboseMacro("SwapCode value (32 bits) not allowed." );
384 * \brief Deal with endianity i.e. re-arange bytes inside the integer
386 void PixelReadConvert::ConvertReorderEndianity()
388 if ( BitsAllocated != 8 )
393 // Special kludge in order to deal with xmedcon broken images:
394 if ( ( BitsAllocated == 16 )
395 && ( BitsStored < BitsAllocated )
398 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
399 uint16_t *deb = (uint16_t *)Raw;
400 for(int i = 0; i<l; i++)
413 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
414 * file and decompress it. This funciton assumes that each
415 * jpeg fragment contains a whole frame (jpeg file).
416 * @param fp File Pointer
419 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream *fp )
421 uint8_t *localRaw = Raw;
422 // Loop on the fragment[s]
423 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
424 it = JPEGInfo->Fragments.begin();
425 it != JPEGInfo->Fragments.end();
428 fp->seekg( (*it)->Offset, std::ios::beg);
430 if ( BitsStored == 8)
432 // JPEG Lossy : call to IJG 6b
433 if ( ! gdcm_read_JPEG_file8( fp, localRaw ) )
438 else if ( BitsStored <= 12)
440 // Reading Fragment pixels
441 if ( ! gdcm_read_JPEG_file12 ( fp, localRaw ) )
446 else if ( BitsStored <= 16)
448 // Reading Fragment pixels
449 if ( ! gdcm_read_JPEG_file16 ( fp, localRaw ) )
453 //gdcmAssertMacro( IsJPEGLossless );
457 // other JPEG lossy not supported
458 gdcmErrorMacro( "Unknown jpeg lossy compression ");
462 // Advance to next free location in Raw
463 // for next fragment decompression (if any)
464 int length = XSize * YSize * SamplesPerPixel;
465 int numberBytes = BitsAllocated / 8;
467 localRaw += length * numberBytes;
473 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
474 * file and decompress it. This function assumes that the dicom
475 * image is a single frame split into several JPEG fragments.
476 * Those fragments will be glued together into a memory buffer
478 * @param fp File Pointer
481 bool PixelReadConvert::
482 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream *fp )
484 // Loop on the fragment[s] to get total length
485 size_t totalLength = 0;
486 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
487 for( it = JPEGInfo->Fragments.begin();
488 it != JPEGInfo->Fragments.end();
491 totalLength += (*it)->Length;
494 // Concatenate the jpeg fragments into a local buffer
495 JOCTET *buffer = new JOCTET [totalLength];
498 // Loop on the fragment[s]
499 for( it = JPEGInfo->Fragments.begin();
500 it != JPEGInfo->Fragments.end();
503 fp->seekg( (*it)->Offset, std::ios::beg);
504 size_t len = (*it)->Length;
505 fp->read((char *)p,len);
509 size_t howManyRead = 0;
510 size_t howManyWritten = 0;
512 if ( BitsStored == 8)
514 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
515 &howManyRead, &howManyWritten ) )
517 gdcmErrorMacro( "Failed to read jpeg8 ");
522 else if ( BitsStored <= 12)
524 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
525 &howManyRead, &howManyWritten ) )
527 gdcmErrorMacro( "Failed to read jpeg12 ");
532 else if ( BitsStored <= 16)
535 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
536 &howManyRead, &howManyWritten ) )
538 gdcmErrorMacro( "Failed to read jpeg16 ");
545 // other JPEG lossy not supported
546 gdcmErrorMacro( "Unknown jpeg lossy compression ");
558 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
559 * file and decompress it. This function handles the generic
560 * and complex case where the DICOM contains several frames,
561 * and some of the frames are possibly split into several JPEG
563 * @param fp File Pointer
566 bool PixelReadConvert::
567 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream *fp )
569 // Loop on the fragment[s] to get total length
570 size_t totalLength = 0;
571 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
572 for( it = JPEGInfo->Fragments.begin();
573 it != JPEGInfo->Fragments.end();
576 totalLength += (*it)->Length;
579 // Concatenate the jpeg fragments into a local buffer
580 JOCTET *buffer = new JOCTET [totalLength];
583 // Loop on the fragment[s]
584 for( it = JPEGInfo->Fragments.begin();
585 it != JPEGInfo->Fragments.end();
588 fp->seekg( (*it)->Offset, std::ios::beg);
589 size_t len = (*it)->Length;
590 fp->read((char *)p,len);
594 size_t howManyRead = 0;
595 size_t howManyWritten = 0;
596 size_t fragmentLength = 0;
598 for( it = JPEGInfo->Fragments.begin() ;
599 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
602 fragmentLength += (*it)->Length;
604 if (howManyRead > fragmentLength) continue;
606 if ( BitsStored == 8)
608 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
610 &howManyRead, &howManyWritten ) )
612 gdcmErrorMacro( "Failed to read jpeg8");
617 else if ( BitsStored <= 12)
620 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
622 &howManyRead, &howManyWritten ) )
624 gdcmErrorMacro( "Failed to read jpeg12");
629 else if ( BitsStored <= 16)
632 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
634 &howManyRead, &howManyWritten ) )
636 gdcmErrorMacro( "Failed to read jpeg16 ");
643 // other JPEG lossy not supported
644 gdcmErrorMacro( "Unknown jpeg lossy compression ");
649 if (howManyRead < fragmentLength)
650 howManyRead = fragmentLength;
660 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
661 * file and decompress it.
662 * @param fp File Pointer
665 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
669 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
670 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
674 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
676 // we have one frame split into several fragments
677 // we will pack those fragments into a single buffer and
679 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
681 else if (JPEGInfo->Fragments.size() == (size_t)ZSize)
683 // suppose each fragment is a frame
684 return ReadAndDecompressJPEGFramesFromFile( fp );
688 // The dicom image contains frames containing fragments of images
689 // a more complex algorithm :-)
690 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
695 * \brief Re-arrange the bits within the bytes.
698 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
700 if ( BitsStored != BitsAllocated )
702 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
703 if ( BitsAllocated == 16 )
705 uint16_t mask = 0xffff;
706 mask = mask >> ( BitsAllocated - BitsStored );
707 uint16_t* deb = (uint16_t*)Raw;
708 for(int i = 0; i<l; i++)
710 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
714 else if ( BitsAllocated == 32 )
716 uint32_t mask = 0xffffffff;
717 mask = mask >> ( BitsAllocated - BitsStored );
718 uint32_t* deb = (uint32_t*)Raw;
719 for(int i = 0; i<l; i++)
721 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
727 gdcmVerboseMacro("Weird image");
728 throw FormatError( "Weird image !?" );
735 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
736 * \warning Works on all the frames at a time
738 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
740 uint8_t *localRaw = Raw;
741 uint8_t *copyRaw = new uint8_t[ RawSize ];
742 memmove( copyRaw, localRaw, RawSize );
744 // to see the tricks about YBR_FULL, YBR_FULL_422,
745 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
746 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
747 // and be *very* affraid
749 int l = XSize * YSize;
750 int nbFrames = ZSize;
752 uint8_t *a = copyRaw;
753 uint8_t *b = copyRaw + l;
754 uint8_t *c = copyRaw + l + l;
757 /// \todo : Replace by the 'well known' integer computation
758 /// counterpart. Refer to
759 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
760 /// for code optimisation.
762 for ( int i = 0; i < nbFrames; i++ )
764 for ( int j = 0; j < l; j++ )
766 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
767 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
768 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
770 if (R < 0.0) R = 0.0;
771 if (G < 0.0) G = 0.0;
772 if (B < 0.0) B = 0.0;
773 if (R > 255.0) R = 255.0;
774 if (G > 255.0) G = 255.0;
775 if (B > 255.0) B = 255.0;
777 *(localRaw++) = (uint8_t)R;
778 *(localRaw++) = (uint8_t)G;
779 *(localRaw++) = (uint8_t)B;
789 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
790 * \warning Works on all the frames at a time
792 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
794 uint8_t *localRaw = Raw;
795 uint8_t *copyRaw = new uint8_t[ RawSize ];
796 memmove( copyRaw, localRaw, RawSize );
798 int l = XSize * YSize * ZSize;
800 uint8_t* a = copyRaw;
801 uint8_t* b = copyRaw + l;
802 uint8_t* c = copyRaw + l + l;
804 for (int j = 0; j < l; j++)
806 *(localRaw++) = *(a++);
807 *(localRaw++) = *(b++);
808 *(localRaw++) = *(c++);
813 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
815 // ComputeRawAndRGBSizes is already made by
816 // ::GrabInformationsFromHeader. So, the structure sizes are
820 //////////////////////////////////////////////////
821 //// First stage: get our hands on the Pixel Data.
824 gdcmVerboseMacro( "Unavailable file pointer." );
828 fp->seekg( PixelOffset, std::ios::beg );
829 if( fp->fail() || fp->eof())
831 gdcmVerboseMacro( "Unable to find PixelOffset in file." );
837 //////////////////////////////////////////////////
838 //// Second stage: read from disk dans decompress.
839 if ( BitsAllocated == 12 )
841 ReadAndDecompress12BitsTo16Bits( fp);
845 // This problem can be found when some obvious informations are found
846 // after the field containing the image datas. In this case, these
847 // bad datas are added to the size of the image (in the PixelDataLength
848 // variable). But RawSize is the right size of the image !
849 if( PixelDataLength != RawSize)
851 gdcmVerboseMacro( "Mismatch between PixelReadConvert and RawSize." );
853 if( PixelDataLength > RawSize)
855 fp->read( (char*)Raw, RawSize);
859 fp->read( (char*)Raw, PixelDataLength);
862 if ( fp->fail() || fp->eof())
864 gdcmVerboseMacro( "Reading of Raw pixel data failed." );
868 else if ( IsRLELossless )
870 if ( ! ReadAndDecompressRLEFile( fp ) )
872 gdcmVerboseMacro( "RLE decompressor failed." );
878 // Default case concerns JPEG family
879 if ( ! ReadAndDecompressJPEGFile( fp ) )
881 gdcmVerboseMacro( "JPEG decompressor failed." );
886 ////////////////////////////////////////////
887 //// Third stage: twigle the bytes and bits.
888 ConvertReorderEndianity();
889 ConvertReArrangeBits();
890 ConvertHandleColor();
895 void PixelReadConvert::ConvertHandleColor()
897 //////////////////////////////////
898 // Deal with the color decoding i.e. handle:
899 // - R, G, B planes (as opposed to RGB pixels)
900 // - YBR (various) encodings.
901 // - LUT[s] (or "PALETTE COLOR").
903 // The classification in the color decoding schema is based on the blending
904 // of two Dicom tags values:
905 // * "Photometric Interpretation" for which we have the cases:
906 // - [Photo A] MONOCHROME[1|2] pictures,
907 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
908 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
909 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
910 // * "Planar Configuration" for which we have the cases:
911 // - [Planar 0] 0 then Pixels are already RGB
912 // - [Planar 1] 1 then we have 3 planes : R, G, B,
913 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
915 // Now in theory, one could expect some coherence when blending the above
916 // cases. For example we should not encounter files belonging at the
917 // time to case [Planar 0] and case [Photo D].
918 // Alas, this was only theory ! Because in practice some odd (read ill
919 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
920 // - "Planar Configuration" = 0,
921 // - "Photometric Interpretation" = "PALETTE COLOR".
922 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
923 // towards Dicom-non-conformance files:
924 // << whatever the "Planar Configuration" value might be, a
925 // "Photometric Interpretation" set to "PALETTE COLOR" forces
926 // a LUT intervention >>
928 // Now we are left with the following handling of the cases:
929 // - [Planar 0] OR [Photo A] no color decoding (since respectively
930 // Pixels are already RGB and monochrome pictures have no color :),
931 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
932 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
933 // - [Planar 2] OR [Photo D] requires LUT intervention.
937 // [Planar 2] OR [Photo D]: LUT intervention done outside
941 if ( PlanarConfiguration == 1 )
945 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
946 ConvertYcBcRPlanesToRGBPixels();
950 // [Planar 1] AND [Photo C]
951 ConvertRGBPlanesToRGBPixels();
956 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
957 // pixels need to be RGB-fied anyway
960 ConvertRGBPlanesToRGBPixels();
962 // In *normal *case, when planarConf is 0, pixels are already in RGB
966 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
967 * \note See comments of \ref ConvertHandleColor
969 bool PixelReadConvert::IsRawRGB()
972 || PlanarConfiguration == 2
980 void PixelReadConvert::ComputeRawAndRGBSizes()
982 int bitsAllocated = BitsAllocated;
983 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
984 // in this case we will expand the image to 16 bits (see
985 // \ref ReadAndDecompress12BitsTo16Bits() )
986 if ( BitsAllocated == 12 )
991 RawSize = XSize * YSize * ZSize
992 * ( bitsAllocated / 8 )
996 RGBSize = 3 * RawSize;
1004 void PixelReadConvert::GrabInformationsFromHeader( Header *header )
1006 // Number of Bits Allocated for storing a Pixel is defaulted to 16
1007 // when absent from the header.
1008 BitsAllocated = header->GetBitsAllocated();
1009 if ( BitsAllocated == 0 )
1014 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
1015 // when absent from the header.
1016 BitsStored = header->GetBitsStored();
1017 if ( BitsStored == 0 )
1019 BitsStored = BitsAllocated;
1022 // High Bit Position
1023 HighBitPosition = header->GetHighBitPosition();
1024 if ( HighBitPosition == 0 )
1026 HighBitPosition = BitsAllocated - 1;
1029 XSize = header->GetXSize();
1030 YSize = header->GetYSize();
1031 ZSize = header->GetZSize();
1032 SamplesPerPixel = header->GetSamplesPerPixel();
1033 PixelSize = header->GetPixelSize();
1034 PixelSign = header->IsSignedPixelData();
1035 SwapCode = header->GetSwapCode();
1036 std::string ts = header->GetTransferSyntax();
1038 ( ! header->IsDicomV3() )
1039 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
1040 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
1041 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
1042 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
1043 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
1044 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
1045 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
1046 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
1047 PixelOffset = header->GetPixelOffset();
1048 PixelDataLength = header->GetPixelAreaLength();
1049 RLEInfo = header->GetRLEInfo();
1050 JPEGInfo = header->GetJPEGInfo();
1052 PlanarConfiguration = header->GetPlanarConfiguration();
1053 IsMonochrome = header->IsMonochrome();
1054 IsPaletteColor = header->IsPaletteColor();
1055 IsYBRFull = header->IsYBRFull();
1057 /////////////////////////////////////////////////////////////////
1059 HasLUT = header->HasLUT();
1062 // Just in case some access to a Header element requires disk access.
1063 LutRedDescriptor = header->GetEntry( 0x0028, 0x1101 );
1064 LutGreenDescriptor = header->GetEntry( 0x0028, 0x1102 );
1065 LutBlueDescriptor = header->GetEntry( 0x0028, 0x1103 );
1067 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
1068 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
1069 // Document::Document() ], the loading of the value (content) of a
1070 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
1071 // loaded). Hence, we first try to obtain the LUTs data from the header
1072 // and when this fails we read the LUTs data directely from disk.
1073 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
1074 /// We should NOT bypass the [Bin|Val]Entry class. Instead
1075 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
1076 /// (e.g. BinEntry::GetBinArea()) should force disk access from
1077 /// within the [Bin|Val]Entry class itself. The only problem
1078 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
1079 /// parsed from. Fix that. FIXME.
1082 header->LoadEntryBinArea(0x0028, 0x1201);
1083 LutRedData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1201 );
1086 gdcmVerboseMacro( "Unable to read red LUT data" );
1090 header->LoadEntryBinArea(0x0028, 0x1202);
1091 LutGreenData = (uint8_t*)header->GetEntryBinArea(0x0028, 0x1202 );
1092 if ( ! LutGreenData)
1094 gdcmVerboseMacro( "Unable to read green LUT data" );
1098 header->LoadEntryBinArea(0x0028, 0x1203);
1099 LutBlueData = (uint8_t*)header->GetEntryBinArea( 0x0028, 0x1203 );
1100 if ( ! LutBlueData )
1102 gdcmVerboseMacro( "Unable to read blue LUT data" );
1106 ComputeRawAndRGBSizes();
1110 * \brief Build Red/Green/Blue/Alpha LUT from Header
1111 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1112 * and (0028,1101),(0028,1102),(0028,1102)
1113 * - xxx Palette Color Lookup Table Descriptor - are found
1114 * and (0028,1201),(0028,1202),(0028,1202)
1115 * - xxx Palette Color Lookup Table Data - are found
1116 * \warning does NOT deal with :
1117 * 0028 1100 Gray Lookup Table Descriptor (Retired)
1118 * 0028 1221 Segmented Red Palette Color Lookup Table Data
1119 * 0028 1222 Segmented Green Palette Color Lookup Table Data
1120 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
1121 * no known Dicom reader deals with them :-(
1122 * @return a RGBA Lookup Table
1124 void PixelReadConvert::BuildLUTRGBA()
1130 // Not so easy : see
1131 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
1133 if ( ! IsPaletteColor )
1138 if ( LutRedDescriptor == GDCM_UNFOUND
1139 || LutGreenDescriptor == GDCM_UNFOUND
1140 || LutBlueDescriptor == GDCM_UNFOUND )
1145 ////////////////////////////////////////////
1146 // Extract the info from the LUT descriptors
1147 int lengthR; // Red LUT length in Bytes
1148 int debR; // Subscript of the first Lut Value
1149 int nbitsR; // Lut item size (in Bits)
1150 int nbRead = sscanf( LutRedDescriptor.c_str(),
1152 &lengthR, &debR, &nbitsR );
1155 gdcmVerboseMacro( "Wrong red LUT descriptor" );
1158 int lengthG; // Green LUT length in Bytes
1159 int debG; // Subscript of the first Lut Value
1160 int nbitsG; // Lut item size (in Bits)
1161 nbRead = sscanf( LutGreenDescriptor.c_str(),
1163 &lengthG, &debG, &nbitsG );
1166 gdcmVerboseMacro( "Wrong green LUT descriptor" );
1169 int lengthB; // Blue LUT length in Bytes
1170 int debB; // Subscript of the first Lut Value
1171 int nbitsB; // Lut item size (in Bits)
1172 nbRead = sscanf( LutRedDescriptor.c_str(),
1174 &lengthB, &debB, &nbitsB );
1177 gdcmVerboseMacro( "Wrong blue LUT descriptor" );
1180 ////////////////////////////////////////////////////////
1181 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
1186 ////////////////////////////////////////////////
1187 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
1188 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
1193 memset( LutRGBA, 0, 1024 );
1196 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
1198 // when LUT item size is different than pixel size
1199 mult = 2; // high byte must be = low byte
1203 // See PS 3.3-2003 C.11.1.1.2 p 619
1207 // if we get a black image, let's just remove the '+1'
1208 // from 'i*mult+1' and check again
1209 // if it works, we shall have to check the 3 Palettes
1210 // to see which byte is ==0 (first one, or second one)
1212 // We give up the checking to avoid some (useless ?)overhead
1213 // (optimistic asumption)
1215 uint8_t* a = LutRGBA + 0;
1216 for( i=0; i < lengthR; ++i )
1218 *a = LutRedData[i*mult+1];
1223 for( i=0; i < lengthG; ++i)
1225 *a = LutGreenData[i*mult+1];
1230 for(i=0; i < lengthB; ++i)
1232 *a = LutBlueData[i*mult+1];
1237 for(i=0; i < 256; ++i)
1239 *a = 1; // Alpha component
1245 * \brief Build the RGB image from the Raw imagage and the LUTs.
1247 bool PixelReadConvert::BuildRGBImage()
1251 // The job is already done.
1257 // The job can't be done
1264 // The job can't be done
1270 uint8_t* localRGB = RGB;
1271 for (size_t i = 0; i < RawSize; ++i )
1274 *localRGB++ = LutRGBA[j];
1275 *localRGB++ = LutRGBA[j+1];
1276 *localRGB++ = LutRGBA[j+2];
1282 * \brief Print self.
1283 * @param os Stream to print to.
1285 void PixelReadConvert::Print( std::ostream &os )
1291 * \brief Print self.
1292 * @param indent Indentation string to be prepended during printing.
1293 * @param os Stream to print to.
1295 void PixelReadConvert::Print( std::string indent, std::ostream &os )
1298 << "--- Pixel information -------------------------"
1301 << "Pixel Data: offset " << PixelOffset
1302 << " x(" << std::hex << PixelOffset << std::dec
1303 << ") length " << PixelDataLength
1304 << " x(" << std::hex << PixelDataLength << std::dec
1305 << ")" << std::endl;
1307 if ( IsRLELossless )
1311 RLEInfo->Print( indent, os );
1315 gdcmVerboseMacro("Set as RLE file but NO RLEinfo present.");
1319 if ( IsJPEG2000 || IsJPEGLossless )
1323 JPEGInfo->Print( indent, os );
1327 gdcmVerboseMacro("Set as JPEG file but NO JPEGinfo present.");
1332 } // end namespace gdcm
1334 // NOTES on File internal calls
1336 // ---> GetImageData
1337 // ---> GetImageDataIntoVector
1338 // |---> GetImageDataIntoVectorRaw
1339 // | lut intervention
1341 // ---> GetImageDataRaw
1342 // ---> GetImageDataIntoVectorRaw