1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/06/20 17:12:03 $
7 Version: $Revision: 1.68 $
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 #include "gdcmPixelReadConvert.h"
20 #include "gdcmDebug.h"
22 #include "gdcmGlobal.h"
24 #include "gdcmDocEntry.h"
25 #include "gdcmRLEFramesInfo.h"
26 #include "gdcmJPEGFragmentsInfo.h"
29 #include <stdio.h> //for sscanf
34 //bool ReadMPEGFile (std::ifstream *fp, void *image_buffer, size_t lenght);
35 bool gdcm_read_JPEG2000_file (void* raw,
36 char *inputdata, size_t inputlength);
37 //-----------------------------------------------------------------------------
38 #define str2num(str, typeNum) *((typeNum *)(str))
40 //-----------------------------------------------------------------------------
41 // Constructor / Destructor
43 PixelReadConvert::PixelReadConvert()
55 /// Canonical Destructor
56 PixelReadConvert::~PixelReadConvert()
61 //-----------------------------------------------------------------------------
64 * \brief Predicate to know whether the image[s] (once Raw) is RGB.
65 * \note See comments of \ref ConvertHandleColor
67 bool PixelReadConvert::IsRawRGB()
70 || PlanarConfiguration == 2
78 * \brief Gets various usefull informations from the file header
79 * @param file gdcm::File pointer
81 void PixelReadConvert::GrabInformationsFromFile( File *file )
83 // Number of Bits Allocated for storing a Pixel is defaulted to 16
84 // when absent from the file.
85 BitsAllocated = file->GetBitsAllocated();
86 if ( BitsAllocated == 0 )
91 // Number of "Bits Stored", defaulted to number of "Bits Allocated"
92 // when absent from the file.
93 BitsStored = file->GetBitsStored();
94 if ( BitsStored == 0 )
96 BitsStored = BitsAllocated;
99 // High Bit Position, defaulted to "Bits Allocated" - 1
100 HighBitPosition = file->GetHighBitPosition();
101 if ( HighBitPosition == 0 )
103 HighBitPosition = BitsAllocated - 1;
106 XSize = file->GetXSize();
107 YSize = file->GetYSize();
108 ZSize = file->GetZSize();
109 SamplesPerPixel = file->GetSamplesPerPixel();
110 PixelSize = file->GetPixelSize();
111 PixelSign = file->IsSignedPixelData();
112 SwapCode = file->GetSwapCode();
113 std::string ts = file->GetTransferSyntax();
115 ( ! file->IsDicomV3() )
116 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
117 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
118 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
119 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
120 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
122 IsMPEG = Global::GetTS()->IsMPEG(ts);
123 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
124 IsJPEGLS = Global::GetTS()->IsJPEGLS(ts);
125 IsJPEGLossy = Global::GetTS()->IsJPEGLossy(ts);
126 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
127 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
129 PixelOffset = file->GetPixelOffset();
130 PixelDataLength = file->GetPixelAreaLength();
131 RLEInfo = file->GetRLEInfo();
132 JPEGInfo = file->GetJPEGInfo();
134 IsMonochrome = file->IsMonochrome();
135 IsMonochrome1 = file->IsMonochrome1();
136 IsPaletteColor = file->IsPaletteColor();
137 IsYBRFull = file->IsYBRFull();
139 PlanarConfiguration = file->GetPlanarConfiguration();
141 /////////////////////////////////////////////////////////////////
143 HasLUT = file->HasLUT();
146 // Just in case some access to a File element requires disk access.
147 LutRedDescriptor = file->GetEntryValue( 0x0028, 0x1101 );
148 LutGreenDescriptor = file->GetEntryValue( 0x0028, 0x1102 );
149 LutBlueDescriptor = file->GetEntryValue( 0x0028, 0x1103 );
151 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
152 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
153 // Document::Document() ], the loading of the value (content) of a
154 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
155 // loaded). Hence, we first try to obtain the LUTs data from the file
156 // and when this fails we read the LUTs data directly from disk.
157 // \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
158 // We should NOT bypass the [Bin|Val]Entry class. Instead
159 // an access to an UNLOADED content of a [Bin|Val]Entry occurence
160 // (e.g. BinEntry::GetBinArea()) should force disk access from
161 // within the [Bin|Val]Entry class itself. The only problem
162 // is that the [Bin|Val]Entry is unaware of the FILE* is was
163 // parsed from. Fix that. FIXME.
166 file->LoadEntryBinArea(0x0028, 0x1201);
167 LutRedData = (uint8_t*)file->GetEntryBinArea( 0x0028, 0x1201 );
170 gdcmWarningMacro( "Unable to read Red LUT data" );
174 file->LoadEntryBinArea(0x0028, 0x1202);
175 LutGreenData = (uint8_t*)file->GetEntryBinArea(0x0028, 0x1202 );
178 gdcmWarningMacro( "Unable to read Green LUT data" );
182 file->LoadEntryBinArea(0x0028, 0x1203);
183 LutBlueData = (uint8_t*)file->GetEntryBinArea( 0x0028, 0x1203 );
186 gdcmWarningMacro( "Unable to read Blue LUT data" );
190 ComputeRawAndRGBSizes();
193 /// \brief Reads from disk and decompresses Pixels
194 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
196 // ComputeRawAndRGBSizes is already made by
197 // ::GrabInformationsFromfile. So, the structure sizes are
201 //////////////////////////////////////////////////
202 //// First stage: get our hands on the Pixel Data.
205 gdcmWarningMacro( "Unavailable file pointer." );
209 fp->seekg( PixelOffset, std::ios::beg );
210 if( fp->fail() || fp->eof())
212 gdcmWarningMacro( "Unable to find PixelOffset in file." );
218 //////////////////////////////////////////////////
219 //// Second stage: read from disk dans decompress.
220 if ( BitsAllocated == 12 )
222 ReadAndDecompress12BitsTo16Bits( fp);
226 // This problem can be found when some obvious informations are found
227 // after the field containing the image data. In this case, these
228 // bad data are added to the size of the image (in the PixelDataLength
229 // variable). But RawSize is the right size of the image !
230 if( PixelDataLength != RawSize)
232 gdcmWarningMacro( "Mismatch between PixelReadConvert : "
233 << PixelDataLength << " and RawSize : " << RawSize );
235 if( PixelDataLength > RawSize)
237 fp->read( (char*)Raw, RawSize);
241 fp->read( (char*)Raw, PixelDataLength);
244 if ( fp->fail() || fp->eof())
246 gdcmWarningMacro( "Reading of Raw pixel data failed." );
250 else if ( IsRLELossless )
252 if ( ! RLEInfo->DecompressRLEFile( fp, Raw, XSize, YSize, ZSize, BitsAllocated ) )
254 gdcmWarningMacro( "RLE decompressor failed." );
260 //gdcmWarningMacro( "Sorry, MPEG not yet taken into account" );
262 //ReadMPEGFile(fp, Raw, PixelDataLength); // fp has already been seek to start of mpeg
267 // Default case concerns JPEG family
268 if ( ! ReadAndDecompressJPEGFile( fp ) )
270 gdcmWarningMacro( "JPEG decompressor failed." );
275 ////////////////////////////////////////////
276 //// Third stage: twigle the bytes and bits.
277 ConvertReorderEndianity();
278 ConvertReArrangeBits();
279 ConvertFixGreyLevels();
280 ConvertHandleColor();
285 /// Deletes Pixels Area
286 void PixelReadConvert::Squeeze()
302 * \brief Build the RGB image from the Raw image and the LUTs.
304 bool PixelReadConvert::BuildRGBImage()
308 // The job is already done.
314 // The job can't be done
321 // The job can't be done
329 if( BitsAllocated <= 8)
331 uint8_t *localRGB = RGB;
332 for (size_t i = 0; i < RawSize; ++i )
335 *localRGB++ = LutRGBA[j];
336 *localRGB++ = LutRGBA[j+1];
337 *localRGB++ = LutRGBA[j+2];
341 else // deal with 16 bits pixels and 16 bits Palette color
343 uint16_t *localRGB = (uint16_t *)RGB;
344 for (size_t i = 0; i < RawSize/2; ++i )
346 j = ((uint16_t *)Raw)[i] * 4;
347 *localRGB++ = ((uint16_t *)LutRGBA)[j];
348 *localRGB++ = ((uint16_t *)LutRGBA)[j+1];
349 *localRGB++ = ((uint16_t *)LutRGBA)[j+2];
356 //-----------------------------------------------------------------------------
359 //-----------------------------------------------------------------------------
362 * \brief Read from file a 12 bits per pixel image and decompress it
363 * into a 16 bits per pixel image.
365 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
366 throw ( FormatError )
368 int nbPixels = XSize * YSize;
369 uint16_t *localDecompres = (uint16_t*)Raw;
371 for( int p = 0; p < nbPixels; p += 2 )
375 fp->read( (char*)&b0, 1);
376 if ( fp->fail() || fp->eof() )
378 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
379 "Unfound first block" );
382 fp->read( (char*)&b1, 1 );
383 if ( fp->fail() || fp->eof())
385 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
386 "Unfound second block" );
389 fp->read( (char*)&b2, 1 );
390 if ( fp->fail() || fp->eof())
392 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
393 "Unfound second block" );
396 // Two steps are necessary to please VC++
398 // 2 pixels 12bit = [0xABCDEF]
399 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
401 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
403 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
405 /// \todo JPR Troubles expected on Big-Endian processors ?
410 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
411 * file and decompress it.
412 * @param fp File Pointer
415 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
419 // make sure this is the right JPEG compression
420 assert( !IsJPEGLossless || !IsJPEGLossy || !IsJPEGLS );
421 // FIXME this is really ugly but it seems I have to load the complete
422 // jpeg2000 stream to use jasper:
423 // I don't think we'll ever be able to deal with multiple fragments properly
425 unsigned long inputlength = 0;
426 JPEGFragment *jpegfrag = JPEGInfo->GetFirstFragment();
429 inputlength += jpegfrag->GetLength();
430 jpegfrag = JPEGInfo->GetNextFragment();
432 gdcmAssertMacro( inputlength != 0);
433 uint8_t *inputdata = new uint8_t[inputlength];
434 char *pinputdata = (char*)inputdata;
435 jpegfrag = JPEGInfo->GetFirstFragment();
438 fp->seekg( jpegfrag->GetOffset(), std::ios::beg);
439 fp->read(pinputdata, jpegfrag->GetLength());
440 pinputdata += jpegfrag->GetLength();
441 jpegfrag = JPEGInfo->GetNextFragment();
443 // Warning the inputdata buffer is delete in the function
444 if ( ! gdcm_read_JPEG2000_file( Raw,
445 (char*)inputdata, inputlength ) )
449 // wow what happen, must be an error
454 // make sure this is the right JPEG compression
455 assert( !IsJPEGLossless || !IsJPEGLossy || !IsJPEG2000 );
456 // WARNING : JPEG-LS is NOT the 'classical' Jpeg Lossless :
457 // [JPEG-LS is the basis for new lossless/near-lossless compression
458 // standard for continuous-tone images intended for JPEG2000. The standard
459 // is based on the LOCO-I algorithm (LOw COmplexity LOssless COmpression
460 // for Images) developed at Hewlett-Packard Laboratories]
462 // see http://datacompression.info/JPEGLS.shtml
465 std::cerr << "count:" << JPEGInfo->GetFragmentCount() << std::endl;
466 unsigned long inputlength = 0;
467 JPEGFragment *jpegfrag = JPEGInfo->GetFirstFragment();
470 inputlength += jpegfrag->GetLength();
471 jpegfrag = JPEGInfo->GetNextFragment();
473 gdcmAssertMacro( inputlength != 0);
474 uint8_t *inputdata = new uint8_t[inputlength];
475 char *pinputdata = (char*)inputdata;
476 jpegfrag = JPEGInfo->GetFirstFragment();
479 fp->seekg( jpegfrag->GetOffset(), std::ios::beg);
480 fp->read(pinputdata, jpegfrag->GetLength());
481 pinputdata += jpegfrag->GetLength();
482 jpegfrag = JPEGInfo->GetNextFragment();
485 //fp->read((char*)Raw, PixelDataLength);
487 std::ofstream out("/tmp/jpegls.jpg");
488 out.write((char*)inputdata, inputlength);
493 gdcmWarningMacro( "Sorry, JPEG-LS not yet taken into account" );
494 fp->seekg( JPEGInfo->GetFirstFragment()->GetOffset(), std::ios::beg);
495 // if ( ! gdcm_read_JPEGLS_file( fp,Raw ) )
500 // make sure this is the right JPEG compression
501 assert( !IsJPEGLS || !IsJPEG2000 );
502 // Precompute the offset localRaw will be shifted with
503 int length = XSize * YSize * SamplesPerPixel;
504 int numberBytes = BitsAllocated / 8;
506 JPEGInfo->DecompressFromFile(fp, Raw, BitsStored, numberBytes, length );
512 * \brief Build Red/Green/Blue/Alpha LUT from File
513 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
514 * and (0028,1101),(0028,1102),(0028,1102)
515 * - xxx Palette Color Lookup Table Descriptor - are found
516 * and (0028,1201),(0028,1202),(0028,1202)
517 * - xxx Palette Color Lookup Table Data - are found
518 * \warning does NOT deal with :
519 * 0028 1100 Gray Lookup Table Descriptor (Retired)
520 * 0028 1221 Segmented Red Palette Color Lookup Table Data
521 * 0028 1222 Segmented Green Palette Color Lookup Table Data
522 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
523 * no known Dicom reader deals with them :-(
524 * @return a RGBA Lookup Table
526 void PixelReadConvert::BuildLUTRGBA()
533 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
535 if ( ! IsPaletteColor )
540 if ( LutRedDescriptor == GDCM_UNFOUND
541 || LutGreenDescriptor == GDCM_UNFOUND
542 || LutBlueDescriptor == GDCM_UNFOUND )
544 gdcmWarningMacro( "(At least) a LUT Descriptor is missing" );
548 ////////////////////////////////////////////
549 // Extract the info from the LUT descriptors
550 int lengthR; // Red LUT length in Bytes
551 int debR; // Subscript of the first Lut Value
552 int nbitsR; // Lut item size (in Bits)
553 int nbRead; // nb of items in LUT descriptor (must be = 3)
555 nbRead = sscanf( LutRedDescriptor.c_str(),
557 &lengthR, &debR, &nbitsR );
560 gdcmWarningMacro( "Wrong Red LUT descriptor" );
562 int lengthG; // Green LUT length in Bytes
563 int debG; // Subscript of the first Lut Value
564 int nbitsG; // Lut item size (in Bits)
566 nbRead = sscanf( LutGreenDescriptor.c_str(),
568 &lengthG, &debG, &nbitsG );
571 gdcmWarningMacro( "Wrong Green LUT descriptor" );
574 int lengthB; // Blue LUT length in Bytes
575 int debB; // Subscript of the first Lut Value
576 int nbitsB; // Lut item size (in Bits)
577 nbRead = sscanf( LutRedDescriptor.c_str(),
579 &lengthB, &debB, &nbitsB );
582 gdcmWarningMacro( "Wrong Blue LUT descriptor" );
585 gdcmWarningMacro(" lengthR " << lengthR << " debR "
586 << debR << " nbitsR " << nbitsR);
587 gdcmWarningMacro(" lengthG " << lengthG << " debG "
588 << debG << " nbitsG " << nbitsG);
589 gdcmWarningMacro(" lengthB " << lengthB << " debB "
590 << debB << " nbitsB " << nbitsB);
592 if ( !lengthR ) // if = 2^16, this shall be 0 see : CP-143
594 if( !lengthG ) // if = 2^16, this shall be 0
596 if ( !lengthB ) // if = 2^16, this shall be 0
599 ////////////////////////////////////////////////////////
601 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
603 gdcmWarningMacro( "(At least) a LUT is missing" );
607 // -------------------------------------------------------------
609 if ( BitsAllocated <= 8)
611 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
612 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
617 memset( LutRGBA, 0, 1024 );
620 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
622 // when LUT item size is different than pixel size
623 mult = 2; // high byte must be = low byte
627 // See PS 3.3-2003 C.11.1.1.2 p 619
631 // if we get a black image, let's just remove the '+1'
632 // from 'i*mult+1' and check again
633 // if it works, we shall have to check the 3 Palettes
634 // to see which byte is ==0 (first one, or second one)
636 // We give up the checking to avoid some (useless ?) overhead
637 // (optimistic asumption)
641 //take "Subscript of the first Lut Value" (debR,debG,debB) into account!
643 a = LutRGBA + 0 + debR;
644 for( i=0; i < lengthR; ++i )
646 *a = LutRedData[i*mult+1];
650 a = LutRGBA + 1 + debG;
651 for( i=0; i < lengthG; ++i)
653 *a = LutGreenData[i*mult+1];
657 a = LutRGBA + 2 + debB;
658 for(i=0; i < lengthB; ++i)
660 *a = LutBlueData[i*mult+1];
665 for(i=0; i < 256; ++i)
667 *a = 1; // Alpha component
673 // Probabely the same stuff is to be done for 16 Bits Pixels
674 // with 65536 entries LUT ?!?
675 // Still looking for accurate info on the web :-(
677 gdcmWarningMacro( "Sorry Palette Color Lookup Tables not yet dealt with"
678 << " for 16 Bits Per Pixel images" );
680 // forge the 4 * 16 Bits Red/Green/Blue/Alpha LUT
682 LutRGBA = (uint8_t *)new uint16_t[ 65536*4 ]; // 2^16 * 4 (R, G, B, Alpha)
685 memset( LutRGBA, 0, 65536*4*2 ); // 16 bits = 2 bytes ;-)
687 LutItemNumber = 65536;
693 //take "Subscript of the first Lut Value" (debR,debG,debB) into account!
695 a16 = (uint16_t*)LutRGBA + 0 + debR;
696 for( i=0; i < lengthR; ++i )
698 *a16 = ((uint16_t*)LutRedData)[i];
702 a16 = (uint16_t*)LutRGBA + 1 + debG;
703 for( i=0; i < lengthG; ++i)
705 *a16 = ((uint16_t*)LutGreenData)[i];
709 a16 = (uint16_t*)LutRGBA + 2 + debB;
710 for(i=0; i < lengthB; ++i)
712 *a16 = ((uint16_t*)LutBlueData)[i];
716 a16 = (uint16_t*)LutRGBA + 3 ;
717 for(i=0; i < 65536; ++i)
719 *a16 = 1; // Alpha component
722 /* Just to 'see' the LUT, at debug time
724 a16=(uint16_t*)LutRGBA;
725 for (int j=0;j<65536;j++)
727 std::cout << *a16 << " " << *(a16+1) << " "
728 << *(a16+2) << " " << *(a16+3) << std::endl;
736 * \brief Swap the bytes, according to \ref SwapCode.
738 void PixelReadConvert::ConvertSwapZone()
742 if( BitsAllocated == 16 )
744 uint16_t *im16 = (uint16_t*)Raw;
752 for( i = 0; i < RawSize / 2; i++ )
754 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
758 gdcmWarningMacro("SwapCode value (16 bits) not allowed.");
761 else if( BitsAllocated == 32 )
766 uint32_t *im32 = (uint32_t*)Raw;
772 for( i = 0; i < RawSize / 4; i++ )
774 low = im32[i] & 0x0000ffff; // 4321
775 high = im32[i] >> 16;
776 high = ( high >> 8 ) | ( high << 8 );
777 low = ( low >> 8 ) | ( low << 8 );
779 im32[i] = ( s32 << 16 ) | high;
783 for( i = 0; i < RawSize / 4; i++ )
785 low = im32[i] & 0x0000ffff; // 2143
786 high = im32[i] >> 16;
787 high = ( high >> 8 ) | ( high << 8 );
788 low = ( low >> 8 ) | ( low << 8 );
790 im32[i] = ( s32 << 16 ) | low;
794 for( i = 0; i < RawSize / 4; i++ )
796 low = im32[i] & 0x0000ffff; // 3412
797 high = im32[i] >> 16;
799 im32[i] = ( s32 << 16 ) | high;
803 gdcmWarningMacro("SwapCode value (32 bits) not allowed." );
809 * \brief Deal with endianness i.e. re-arange bytes inside the integer
811 void PixelReadConvert::ConvertReorderEndianity()
813 if ( BitsAllocated != 8 )
818 // Special kludge in order to deal with xmedcon broken images:
819 if ( BitsAllocated == 16
820 && BitsStored < BitsAllocated
823 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
824 uint16_t *deb = (uint16_t *)Raw;
825 for(int i = 0; i<l; i++)
837 * \brief Deal with Grey levels i.e. re-arange them
838 * to have low values = dark, high values = bright
840 void PixelReadConvert::ConvertFixGreyLevels()
845 uint32_t i; // to please M$VC6
850 if ( BitsAllocated == 8 )
852 uint8_t *deb = (uint8_t *)Raw;
853 for (i=0; i<RawSize; i++)
861 if ( BitsAllocated == 16 )
864 for (j=0; j<BitsStored-1; j++)
866 mask = (mask << 1) +1; // will be fff when BitsStored=12
869 uint16_t *deb = (uint16_t *)Raw;
870 for (i=0; i<RawSize/2; i++)
880 if ( BitsAllocated == 8 )
882 uint8_t smask8 = 255;
883 uint8_t *deb = (uint8_t *)Raw;
884 for (i=0; i<RawSize; i++)
886 *deb = smask8 - *deb;
891 if ( BitsAllocated == 16 )
893 uint16_t smask16 = 65535;
894 uint16_t *deb = (uint16_t *)Raw;
895 for (i=0; i<RawSize/2; i++)
897 *deb = smask16 - *deb;
906 * \brief Re-arrange the bits within the bytes.
907 * @return Boolean always true
909 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
911 if ( BitsStored != BitsAllocated )
913 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
914 if ( BitsAllocated == 16 )
916 uint16_t mask = 0xffff;
917 mask = mask >> ( BitsAllocated - BitsStored );
918 uint16_t *deb = (uint16_t*)Raw;
919 for(int i = 0; i<l; i++)
921 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
925 else if ( BitsAllocated == 32 )
927 uint32_t mask = 0xffffffff;
928 mask = mask >> ( BitsAllocated - BitsStored );
929 uint32_t *deb = (uint32_t*)Raw;
930 for(int i = 0; i<l; i++)
932 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
938 gdcmWarningMacro("Weird image");
939 throw FormatError( "Weird image !?" );
946 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
947 * \warning Works on all the frames at a time
949 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
951 gdcmWarningMacro("ConvertRGBPlanesToRGBPixels");
953 uint8_t *localRaw = Raw;
954 uint8_t *copyRaw = new uint8_t[ RawSize ];
955 memmove( copyRaw, localRaw, RawSize );
957 int l = XSize * YSize * ZSize;
959 uint8_t *a = copyRaw;
960 uint8_t *b = copyRaw + l;
961 uint8_t *c = copyRaw + l + l;
963 for (int j = 0; j < l; j++)
965 *(localRaw++) = *(a++);
966 *(localRaw++) = *(b++);
967 *(localRaw++) = *(c++);
973 * \brief Convert (cY plane, cB plane, cR plane) to RGB pixels
974 * \warning Works on all the frames at a time
976 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
978 // Remarks for YBR newbees :
979 // YBR_FULL works very much like RGB, i.e. three samples per pixel,
980 // just the color space is YCbCr instead of RGB. This is particularly useful
981 // for doppler ultrasound where most of the image is grayscale
982 // (i.e. only populates the Y components) and Cb and Cr are mostly zero,
983 // except for the few patches of color on the image.
984 // On such images, RLE achieves a compression ratio that is much better
985 // than the compression ratio on an equivalent RGB image.
987 uint8_t *localRaw = Raw;
988 uint8_t *copyRaw = new uint8_t[ RawSize ];
989 memmove( copyRaw, localRaw, RawSize );
991 // to see the tricks about YBR_FULL, YBR_FULL_422,
992 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
993 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
994 // and be *very* affraid
996 int l = XSize * YSize;
997 int nbFrames = ZSize;
999 uint8_t *a = copyRaw + 0;
1000 uint8_t *b = copyRaw + l;
1001 uint8_t *c = copyRaw + l+ l;
1004 /// We replaced easy to understand but time consuming floating point
1005 /// computations by the 'well known' integer computation counterpart
1007 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
1008 /// for code optimisation.
1010 gdcmWarningMacro("ConvertYcBcRPlanesToRGBPixels");
1012 for ( int i = 0; i < nbFrames; i++ )
1014 for ( int j = 0; j < l; j++ )
1016 R = 38142 *(*a-16) + 52298 *(*c -128);
1017 G = 38142 *(*a-16) - 26640 *(*c -128) - 12845 *(*b -128);
1018 B = 38142 *(*a-16) + 66093 *(*b -128);
1027 if (R > 255) R = 255;
1028 if (G > 255) G = 255;
1029 if (B > 255) B = 255;
1031 *(localRaw++) = (uint8_t)R;
1032 *(localRaw++) = (uint8_t)G;
1033 *(localRaw++) = (uint8_t)B;
1042 /// \brief Deals with the color decoding i.e. handle:
1043 /// - R, G, B planes (as opposed to RGB pixels)
1044 /// - YBR (various) encodings.
1045 /// - LUT[s] (or "PALETTE COLOR").
1047 void PixelReadConvert::ConvertHandleColor()
1049 //////////////////////////////////
1050 // Deal with the color decoding i.e. handle:
1051 // - R, G, B planes (as opposed to RGB pixels)
1052 // - YBR (various) encodings.
1053 // - LUT[s] (or "PALETTE COLOR").
1055 // The classification in the color decoding schema is based on the blending
1056 // of two Dicom tags values:
1057 // * "Photometric Interpretation" for which we have the cases:
1058 // - [Photo A] MONOCHROME[1|2] pictures,
1059 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
1060 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
1061 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
1062 // * "Planar Configuration" for which we have the cases:
1063 // - [Planar 0] 0 then Pixels are already RGB
1064 // - [Planar 1] 1 then we have 3 planes : R, G, B,
1065 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
1067 // Now in theory, one could expect some coherence when blending the above
1068 // cases. For example we should not encounter files belonging at the
1069 // time to case [Planar 0] and case [Photo D].
1070 // Alas, this was only theory ! Because in practice some odd (read ill
1071 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
1072 // - "Planar Configuration" = 0,
1073 // - "Photometric Interpretation" = "PALETTE COLOR".
1074 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
1075 // towards Dicom-non-conformant files:
1076 // << whatever the "Planar Configuration" value might be, a
1077 // "Photometric Interpretation" set to "PALETTE COLOR" forces
1078 // a LUT intervention >>
1080 // Now we are left with the following handling of the cases:
1081 // - [Planar 0] OR [Photo A] no color decoding (since respectively
1082 // Pixels are already RGB and monochrome pictures have no color :),
1083 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
1084 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
1085 // - [Planar 2] OR [Photo D] requires LUT intervention.
1087 gdcmWarningMacro("ConvertHandleColor");
1091 // [Planar 2] OR [Photo D]: LUT intervention done outside
1095 if ( PlanarConfiguration == 1 )
1099 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
1100 ConvertYcBcRPlanesToRGBPixels();
1104 // [Planar 1] AND [Photo C]
1105 ConvertRGBPlanesToRGBPixels();
1110 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
1111 // pixels need to be RGB-fyied anyway
1115 ConvertRGBPlanesToRGBPixels();
1118 // In *normal *case, when planarConf is 0, pixels are already in RGB
1121 /// Computes the Pixels Size
1122 void PixelReadConvert::ComputeRawAndRGBSizes()
1124 int bitsAllocated = BitsAllocated;
1125 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
1126 // in this case we will expand the image to 16 bits (see
1127 // \ref ReadAndDecompress12BitsTo16Bits() )
1128 if ( BitsAllocated == 12 )
1133 RawSize = XSize * YSize * ZSize
1134 * ( bitsAllocated / 8 )
1138 RGBSize = 3 * RawSize; // works for 8 and 16 bits per Pixel
1146 /// Allocates room for RGB Pixels
1147 void PixelReadConvert::AllocateRGB()
1151 RGB = new uint8_t[RGBSize];
1154 /// Allocates room for RAW Pixels
1155 void PixelReadConvert::AllocateRaw()
1159 Raw = new uint8_t[RawSize];
1162 //-----------------------------------------------------------------------------
1165 * \brief Print self.
1166 * @param indent Indentation string to be prepended during printing.
1167 * @param os Stream to print to.
1169 void PixelReadConvert::Print( std::ostream &os, std::string const &indent )
1172 << "--- Pixel information -------------------------"
1175 << "Pixel Data: offset " << PixelOffset
1176 << " x(" << std::hex << PixelOffset << std::dec
1177 << ") length " << PixelDataLength
1178 << " x(" << std::hex << PixelDataLength << std::dec
1179 << ")" << std::endl;
1181 if ( IsRLELossless )
1185 RLEInfo->Print( os, indent );
1189 gdcmWarningMacro("Set as RLE file but NO RLEinfo present.");
1193 if ( IsJPEG2000 || IsJPEGLossless || IsJPEGLossy || IsJPEGLS )
1197 JPEGInfo->Print( os, indent );
1201 gdcmWarningMacro("Set as JPEG file but NO JPEGinfo present.");
1206 //-----------------------------------------------------------------------------
1207 } // end namespace gdcm
1209 // NOTES on File internal calls
1211 // ---> GetImageData
1212 // ---> GetImageDataIntoVector
1213 // |---> GetImageDataIntoVectorRaw
1214 // | lut intervention
1216 // ---> GetImageDataRaw
1217 // ---> GetImageDataIntoVectorRaw