1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
6 Date: $Date: 2005/07/01 11:25:51 $
7 Version: $Revision: 1.74 $
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()
57 /// Canonical Destructor
58 PixelReadConvert::~PixelReadConvert()
63 //-----------------------------------------------------------------------------
66 * \brief Predicate to know whether the image[s] (once Raw) is RGB.
67 * \note See comments of \ref ConvertHandleColor
69 bool PixelReadConvert::IsRawRGB()
72 || PlanarConfiguration == 2
80 * \brief Gets various usefull informations from the file header
81 * @param file gdcm::File pointer
83 void PixelReadConvert::GrabInformationsFromFile( File *file )
85 // Number of Bits Allocated for storing a Pixel is defaulted to 16
86 // when absent from the file.
87 BitsAllocated = file->GetBitsAllocated();
88 if ( BitsAllocated == 0 )
93 // Number of "Bits Stored", defaulted to number of "Bits Allocated"
94 // when absent from the file.
95 BitsStored = file->GetBitsStored();
96 if ( BitsStored == 0 )
98 BitsStored = BitsAllocated;
101 // High Bit Position, defaulted to "Bits Allocated" - 1
102 HighBitPosition = file->GetHighBitPosition();
103 if ( HighBitPosition == 0 )
105 HighBitPosition = BitsAllocated - 1;
108 XSize = file->GetXSize();
109 YSize = file->GetYSize();
110 ZSize = file->GetZSize();
111 SamplesPerPixel = file->GetSamplesPerPixel();
112 PixelSize = file->GetPixelSize();
113 PixelSign = file->IsSignedPixelData();
114 SwapCode = file->GetSwapCode();
115 std::string ts = file->GetTransferSyntax();
117 ( ! file->IsDicomV3() )
118 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndian
119 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ImplicitVRLittleEndianDLXGE
120 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRLittleEndian
121 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::ExplicitVRBigEndian
122 || Global::GetTS()->GetSpecialTransferSyntax(ts) == TS::DeflatedExplicitVRLittleEndian;
124 IsMPEG = Global::GetTS()->IsMPEG(ts);
125 IsJPEG2000 = Global::GetTS()->IsJPEG2000(ts);
126 IsJPEGLS = Global::GetTS()->IsJPEGLS(ts);
127 IsJPEGLossy = Global::GetTS()->IsJPEGLossy(ts);
128 IsJPEGLossless = Global::GetTS()->IsJPEGLossless(ts);
129 IsRLELossless = Global::GetTS()->IsRLELossless(ts);
131 PixelOffset = file->GetPixelOffset();
132 PixelDataLength = file->GetPixelAreaLength();
133 RLEInfo = file->GetRLEInfo();
134 JPEGInfo = file->GetJPEGInfo();
136 IsMonochrome = file->IsMonochrome();
137 IsMonochrome1 = file->IsMonochrome1();
138 IsPaletteColor = file->IsPaletteColor();
139 IsYBRFull = file->IsYBRFull();
141 PlanarConfiguration = file->GetPlanarConfiguration();
143 /////////////////////////////////////////////////////////////////
145 HasLUT = file->HasLUT();
148 // Just in case some access to a File element requires disk access.
149 LutRedDescriptor = file->GetEntryValue( 0x0028, 0x1101 );
150 LutGreenDescriptor = file->GetEntryValue( 0x0028, 0x1102 );
151 LutBlueDescriptor = file->GetEntryValue( 0x0028, 0x1103 );
153 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
154 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
155 // Document::Document() ], the loading of the value (content) of a
156 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
157 // loaded). Hence, we first try to obtain the LUTs data from the file
158 // and when this fails we read the LUTs data directly from disk.
159 // \TODO Reading a [Bin|Val]Entry directly from disk is a kludge.
160 // We should NOT bypass the [Bin|Val]Entry class. Instead
161 // an access to an UNLOADED content of a [Bin|Val]Entry occurence
162 // (e.g. BinEntry::GetBinArea()) should force disk access from
163 // within the [Bin|Val]Entry class itself. The only problem
164 // is that the [Bin|Val]Entry is unaware of the FILE* is was
165 // parsed from. Fix that. FIXME.
168 file->LoadEntryBinArea(0x0028, 0x1201);
169 LutRedData = (uint8_t*)file->GetEntryBinArea( 0x0028, 0x1201 );
172 gdcmWarningMacro( "Unable to read Red Palette Color Lookup Table data" );
176 file->LoadEntryBinArea(0x0028, 0x1202);
177 LutGreenData = (uint8_t*)file->GetEntryBinArea(0x0028, 0x1202 );
180 gdcmWarningMacro( "Unable to read Green Palette Color Lookup Table data" );
184 file->LoadEntryBinArea(0x0028, 0x1203);
185 LutBlueData = (uint8_t*)file->GetEntryBinArea( 0x0028, 0x1203 );
188 gdcmWarningMacro( "Unable to read Blue Palette Color Lookup Table data" );
192 ComputeRawAndRGBSizes();
195 /// \brief Reads from disk and decompresses Pixels
196 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream *fp )
198 // ComputeRawAndRGBSizes is already made by
199 // ::GrabInformationsFromfile. So, the structure sizes are
203 //////////////////////////////////////////////////
204 //// First stage: get our hands on the Pixel Data.
207 gdcmWarningMacro( "Unavailable file pointer." );
211 fp->seekg( PixelOffset, std::ios::beg );
212 if ( fp->fail() || fp->eof() )
214 gdcmWarningMacro( "Unable to find PixelOffset in file." );
220 //////////////////////////////////////////////////
221 //// Second stage: read from disk and decompress.
222 if ( BitsAllocated == 12 )
224 ReadAndDecompress12BitsTo16Bits( fp);
228 // This problem can be found when some obvious informations are found
229 // after the field containing the image data. In this case, these
230 // bad data are added to the size of the image (in the PixelDataLength
231 // variable). But RawSize is the right size of the image !
232 if ( PixelDataLength != RawSize )
234 gdcmWarningMacro( "Mismatch between PixelReadConvert : "
235 << PixelDataLength << " and RawSize : " << RawSize );
237 if ( PixelDataLength > RawSize )
239 fp->read( (char*)Raw, RawSize);
243 fp->read( (char*)Raw, PixelDataLength);
246 if ( fp->fail() || fp->eof())
248 gdcmWarningMacro( "Reading of Raw pixel data failed." );
252 else if ( IsRLELossless )
254 if ( ! RLEInfo->DecompressRLEFile( fp, Raw, XSize, YSize, ZSize, BitsAllocated ) )
256 gdcmWarningMacro( "RLE decompressor failed." );
262 //gdcmWarningMacro( "Sorry, MPEG not yet taken into account" );
264 //ReadMPEGFile(fp, Raw, PixelDataLength); // fp has already been seek to start of mpeg
269 // Default case concerns JPEG family
270 if ( ! ReadAndDecompressJPEGFile( fp ) )
272 gdcmWarningMacro( "JPEG decompressor failed." );
277 ////////////////////////////////////////////
278 //// Third stage: twigle the bytes and bits.
279 ConvertReorderEndianity();
280 ConvertReArrangeBits();
281 ConvertFixGreyLevels();
282 ConvertHandleColor();
287 /// Deletes Pixels Area
288 void PixelReadConvert::Squeeze()
304 * \brief Build the RGB image from the Raw image and the LUTs.
306 bool PixelReadConvert::BuildRGBImage()
310 // The job is already done.
316 // The job can't be done
323 // The job can't be done
327 gdcmWarningMacro( "--> BuildRGBImage" );
333 if ( BitsAllocated <= 8 )
335 uint8_t *localRGB = RGB;
336 for (size_t i = 0; i < RawSize; ++i )
339 *localRGB++ = LutRGBA[j];
340 *localRGB++ = LutRGBA[j+1];
341 *localRGB++ = LutRGBA[j+2];
345 else // deal with 16 bits pixels and 16 bits Palette color
347 uint16_t *localRGB = (uint16_t *)RGB;
348 for (size_t i = 0; i < RawSize/2; ++i )
350 j = ((uint16_t *)Raw)[i] * 4;
351 *localRGB++ = ((uint16_t *)LutRGBA)[j];
352 *localRGB++ = ((uint16_t *)LutRGBA)[j+1];
353 *localRGB++ = ((uint16_t *)LutRGBA)[j+2];
360 //-----------------------------------------------------------------------------
363 //-----------------------------------------------------------------------------
366 * \brief Read from file a 12 bits per pixel image and decompress it
367 * into a 16 bits per pixel image.
369 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream *fp )
370 throw ( FormatError )
372 int nbPixels = XSize * YSize;
373 uint16_t *localDecompres = (uint16_t*)Raw;
375 for( int p = 0; p < nbPixels; p += 2 )
379 fp->read( (char*)&b0, 1);
380 if ( fp->fail() || fp->eof() )
382 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
383 "Unfound first block" );
386 fp->read( (char*)&b1, 1 );
387 if ( fp->fail() || fp->eof())
389 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
390 "Unfound second block" );
393 fp->read( (char*)&b2, 1 );
394 if ( fp->fail() || fp->eof())
396 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
397 "Unfound second block" );
400 // Two steps are necessary to please VC++
402 // 2 pixels 12bit = [0xABCDEF]
403 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
405 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
407 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
409 /// \todo JPR Troubles expected on Big-Endian processors ?
414 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
415 * file and decompress it.
416 * @param fp File Pointer
419 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream *fp )
423 // make sure this is the right JPEG compression
424 assert( !IsJPEGLossless || !IsJPEGLossy || !IsJPEGLS );
425 // FIXME this is really ugly but it seems I have to load the complete
426 // jpeg2000 stream to use jasper:
427 // I don't think we'll ever be able to deal with multiple fragments properly
429 unsigned long inputlength = 0;
430 JPEGFragment *jpegfrag = JPEGInfo->GetFirstFragment();
433 inputlength += jpegfrag->GetLength();
434 jpegfrag = JPEGInfo->GetNextFragment();
436 gdcmAssertMacro( inputlength != 0);
437 uint8_t *inputdata = new uint8_t[inputlength];
438 char *pinputdata = (char*)inputdata;
439 jpegfrag = JPEGInfo->GetFirstFragment();
442 fp->seekg( jpegfrag->GetOffset(), std::ios::beg);
443 fp->read(pinputdata, jpegfrag->GetLength());
444 pinputdata += jpegfrag->GetLength();
445 jpegfrag = JPEGInfo->GetNextFragment();
447 // Warning the inputdata buffer is delete in the function
448 if ( ! gdcm_read_JPEG2000_file( Raw,
449 (char*)inputdata, inputlength ) )
453 // wow what happen, must be an error
458 // make sure this is the right JPEG compression
459 assert( !IsJPEGLossless || !IsJPEGLossy || !IsJPEG2000 );
460 // WARNING : JPEG-LS is NOT the 'classical' Jpeg Lossless :
461 // [JPEG-LS is the basis for new lossless/near-lossless compression
462 // standard for continuous-tone images intended for JPEG2000. The standard
463 // is based on the LOCO-I algorithm (LOw COmplexity LOssless COmpression
464 // for Images) developed at Hewlett-Packard Laboratories]
466 // see http://datacompression.info/JPEGLS.shtml
469 std::cerr << "count:" << JPEGInfo->GetFragmentCount() << std::endl;
470 unsigned long inputlength = 0;
471 JPEGFragment *jpegfrag = JPEGInfo->GetFirstFragment();
474 inputlength += jpegfrag->GetLength();
475 jpegfrag = JPEGInfo->GetNextFragment();
477 gdcmAssertMacro( inputlength != 0);
478 uint8_t *inputdata = new uint8_t[inputlength];
479 char *pinputdata = (char*)inputdata;
480 jpegfrag = JPEGInfo->GetFirstFragment();
483 fp->seekg( jpegfrag->GetOffset(), std::ios::beg);
484 fp->read(pinputdata, jpegfrag->GetLength());
485 pinputdata += jpegfrag->GetLength();
486 jpegfrag = JPEGInfo->GetNextFragment();
489 //fp->read((char*)Raw, PixelDataLength);
491 std::ofstream out("/tmp/jpegls.jpg");
492 out.write((char*)inputdata, inputlength);
497 gdcmWarningMacro( "Sorry, JPEG-LS not yet taken into account" );
498 fp->seekg( JPEGInfo->GetFirstFragment()->GetOffset(), std::ios::beg);
499 // if ( ! gdcm_read_JPEGLS_file( fp,Raw ) )
504 // make sure this is the right JPEG compression
505 assert( !IsJPEGLS || !IsJPEG2000 );
506 // Precompute the offset localRaw will be shifted with
507 int length = XSize * YSize * SamplesPerPixel;
508 int numberBytes = BitsAllocated / 8;
510 JPEGInfo->DecompressFromFile(fp, Raw, BitsStored, numberBytes, length );
516 * \brief Build Red/Green/Blue/Alpha LUT from File
517 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
518 * and (0028,1101),(0028,1102),(0028,1102)
519 * - xxx Palette Color Lookup Table Descriptor - are found
520 * and (0028,1201),(0028,1202),(0028,1202)
521 * - xxx Palette Color Lookup Table Data - are found
522 * \warning does NOT deal with :
523 * 0028 1100 Gray Lookup Table Descriptor (Retired)
524 * 0028 1221 Segmented Red Palette Color Lookup Table Data
525 * 0028 1222 Segmented Green Palette Color Lookup Table Data
526 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
527 * no known Dicom reader deals with them :-(
528 * @return a RGBA Lookup Table
530 void PixelReadConvert::BuildLUTRGBA()
537 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
539 if ( ! IsPaletteColor )
544 if ( LutRedDescriptor == GDCM_UNFOUND
545 || LutGreenDescriptor == GDCM_UNFOUND
546 || LutBlueDescriptor == GDCM_UNFOUND )
548 gdcmWarningMacro( "(At least) a LUT Descriptor is missing" );
552 ////////////////////////////////////////////
553 // Extract the info from the LUT descriptors
554 int lengthR; // Red LUT length in Bytes
555 int debR; // Subscript of the first Lut Value
556 int nbitsR; // Lut item size (in Bits)
557 int nbRead; // nb of items in LUT descriptor (must be = 3)
559 nbRead = sscanf( LutRedDescriptor.c_str(),
561 &lengthR, &debR, &nbitsR );
564 gdcmWarningMacro( "Wrong Red LUT descriptor" );
566 int lengthG; // Green LUT length in Bytes
567 int debG; // Subscript of the first Lut Value
568 int nbitsG; // Lut item size (in Bits)
570 nbRead = sscanf( LutGreenDescriptor.c_str(),
572 &lengthG, &debG, &nbitsG );
575 gdcmWarningMacro( "Wrong Green LUT descriptor" );
578 int lengthB; // Blue LUT length in Bytes
579 int debB; // Subscript of the first Lut Value
580 int nbitsB; // Lut item size (in Bits)
581 nbRead = sscanf( LutRedDescriptor.c_str(),
583 &lengthB, &debB, &nbitsB );
586 gdcmWarningMacro( "Wrong Blue LUT descriptor" );
589 gdcmWarningMacro(" lengthR " << lengthR << " debR "
590 << debR << " nbitsR " << nbitsR);
591 gdcmWarningMacro(" lengthG " << lengthG << " debG "
592 << debG << " nbitsG " << nbitsG);
593 gdcmWarningMacro(" lengthB " << lengthB << " debB "
594 << debB << " nbitsB " << nbitsB);
596 if ( !lengthR ) // if = 2^16, this shall be 0 see : CP-143
598 if ( !lengthG ) // if = 2^16, this shall be 0
600 if ( !lengthB ) // if = 2^16, this shall be 0
603 ////////////////////////////////////////////////////////
605 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
607 gdcmWarningMacro( "(At least) a LUT is missing" );
611 // -------------------------------------------------------------
613 if ( BitsAllocated <= 8 )
615 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
616 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
621 memset( LutRGBA, 0, 1024 );
624 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
626 // when LUT item size is different than pixel size
627 mult = 2; // high byte must be = low byte
631 // See PS 3.3-2003 C.11.1.1.2 p 619
635 // if we get a black image, let's just remove the '+1'
636 // from 'i*mult+1' and check again
637 // if it works, we shall have to check the 3 Palettes
638 // to see which byte is ==0 (first one, or second one)
640 // We give up the checking to avoid some (useless ?) overhead
641 // (optimistic asumption)
645 //take "Subscript of the first Lut Value" (debR,debG,debB) into account!
647 //FIXME : +1 : to get 'low value' byte
648 // Trouble expected on Big Endian Processors ?
649 // 16 BIts Per Pixel Palette Color to be swapped?
651 a = LutRGBA + 0 + debR;
652 for( i=0; i < lengthR; ++i )
654 *a = LutRedData[i*mult+1];
658 a = LutRGBA + 1 + debG;
659 for( i=0; i < lengthG; ++i)
661 *a = LutGreenData[i*mult+1];
665 a = LutRGBA + 2 + debB;
666 for(i=0; i < lengthB; ++i)
668 *a = LutBlueData[i*mult+1];
673 for(i=0; i < 256; ++i)
675 *a = 1; // Alpha component
681 // Probabely the same stuff is to be done for 16 Bits Pixels
682 // with 65536 entries LUT ?!?
683 // Still looking for accurate info on the web :-(
685 gdcmWarningMacro( "Sorry Palette Color Lookup Tables not yet dealt with"
686 << " for 16 Bits Per Pixel images" );
688 // forge the 4 * 16 Bits Red/Green/Blue/Alpha LUT
690 LutRGBA = (uint8_t *)new uint16_t[ 65536*4 ]; // 2^16 * 4 (R, G, B, Alpha)
693 memset( LutRGBA, 0, 65536*4*2 ); // 16 bits = 2 bytes ;-)
695 LutItemNumber = 65536;
701 //take "Subscript of the first Lut Value" (debR,debG,debB) into account!
703 a16 = (uint16_t*)LutRGBA + 0 + debR;
704 for( i=0; i < lengthR; ++i )
706 *a16 = ((uint16_t*)LutRedData)[i];
710 a16 = (uint16_t*)LutRGBA + 1 + debG;
711 for( i=0; i < lengthG; ++i)
713 *a16 = ((uint16_t*)LutGreenData)[i];
717 a16 = (uint16_t*)LutRGBA + 2 + debB;
718 for(i=0; i < lengthB; ++i)
720 *a16 = ((uint16_t*)LutBlueData)[i];
724 a16 = (uint16_t*)LutRGBA + 3 ;
725 for(i=0; i < 65536; ++i)
727 *a16 = 1; // Alpha component
730 /* Just to 'see' the LUT, at debug time
732 a16=(uint16_t*)LutRGBA;
733 for (int j=0;j<65536;j++)
735 std::cout << *a16 << " " << *(a16+1) << " "
736 << *(a16+2) << " " << *(a16+3) << std::endl;
744 * \brief Swap the bytes, according to \ref SwapCode.
746 void PixelReadConvert::ConvertSwapZone()
750 if ( BitsAllocated == 16 )
752 uint16_t *im16 = (uint16_t*)Raw;
760 for( i = 0; i < RawSize / 2; i++ )
762 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
766 gdcmWarningMacro("SwapCode value (16 bits) not allowed.");
769 else if ( BitsAllocated == 32 )
774 uint32_t *im32 = (uint32_t*)Raw;
780 for( i = 0; i < RawSize / 4; i++ )
782 low = im32[i] & 0x0000ffff; // 4321
783 high = im32[i] >> 16;
784 high = ( high >> 8 ) | ( high << 8 );
785 low = ( low >> 8 ) | ( low << 8 );
787 im32[i] = ( s32 << 16 ) | high;
791 for( i = 0; i < RawSize / 4; i++ )
793 low = im32[i] & 0x0000ffff; // 2143
794 high = im32[i] >> 16;
795 high = ( high >> 8 ) | ( high << 8 );
796 low = ( low >> 8 ) | ( low << 8 );
798 im32[i] = ( s32 << 16 ) | low;
802 for( i = 0; i < RawSize / 4; i++ )
804 low = im32[i] & 0x0000ffff; // 3412
805 high = im32[i] >> 16;
807 im32[i] = ( s32 << 16 ) | high;
811 gdcmWarningMacro("SwapCode value (32 bits) not allowed." );
817 * \brief Deal with endianness i.e. re-arange bytes inside the integer
819 void PixelReadConvert::ConvertReorderEndianity()
821 if ( BitsAllocated != 8 )
826 // Special kludge in order to deal with xmedcon broken images:
827 if ( BitsAllocated == 16
828 && BitsStored < BitsAllocated
831 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
832 uint16_t *deb = (uint16_t *)Raw;
833 for(int i = 0; i<l; i++)
835 if ( *deb == 0xffff )
845 * \brief Deal with Grey levels i.e. re-arange them
846 * to have low values = dark, high values = bright
848 void PixelReadConvert::ConvertFixGreyLevels()
853 uint32_t i; // to please M$VC6
858 if ( BitsAllocated == 8 )
860 uint8_t *deb = (uint8_t *)Raw;
861 for (i=0; i<RawSize; i++)
869 if ( BitsAllocated == 16 )
872 for (j=0; j<BitsStored-1; j++)
874 mask = (mask << 1) +1; // will be fff when BitsStored=12
877 uint16_t *deb = (uint16_t *)Raw;
878 for (i=0; i<RawSize/2; i++)
888 if ( BitsAllocated == 8 )
890 uint8_t smask8 = 255;
891 uint8_t *deb = (uint8_t *)Raw;
892 for (i=0; i<RawSize; i++)
894 *deb = smask8 - *deb;
899 if ( BitsAllocated == 16 )
901 uint16_t smask16 = 65535;
902 uint16_t *deb = (uint16_t *)Raw;
903 for (i=0; i<RawSize/2; i++)
905 *deb = smask16 - *deb;
914 * \brief Re-arrange the bits within the bytes.
915 * @return Boolean always true
917 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
920 if ( BitsStored != BitsAllocated )
922 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
923 if ( BitsAllocated == 16 )
925 // pmask : to mask the 'unused bits' (may contain overlays)
926 uint16_t pmask = 0xffff;
927 pmask = pmask >> ( BitsAllocated - BitsStored );
929 uint16_t *deb = (uint16_t*)Raw;
931 if ( !PixelSign ) // Pixels are unsigned
933 for(int i = 0; i<l; i++)
935 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & pmask;
939 else // Pixels are signed
941 // smask : to check the 'sign' when BitsStored != BitsAllocated
942 uint16_t smask = 0x0001;
943 smask = smask << ( 16 - (BitsAllocated - BitsStored + 1) );
944 // nmask : to propagate sign bit on negative values
945 int16_t nmask = (int16_t)0x8000;
946 nmask = nmask >> ( BitsAllocated - BitsStored - 1 );
948 std::cout << "BitsStored " << BitsStored
949 << " BitsAllocated " << BitsAllocated
951 std::cout << std::hex << "pmask " << pmask
952 << " smask " << smask
953 << " nmask " << nmask
956 for(int i = 0; i<l; i++)
958 *deb = *deb >> (BitsStored - HighBitPosition - 1);
971 else if ( BitsAllocated == 32 )
973 // pmask : to mask the 'unused bits' (may contain overlays)
974 uint32_t pmask = 0xffffffff;
975 pmask = pmask >> ( BitsAllocated - BitsStored );
977 uint32_t *deb = (uint32_t*)Raw;
981 for(int i = 0; i<l; i++)
983 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & pmask;
989 // smask : to check the 'sign' when BitsStored != BitsAllocated
990 uint32_t smask = 0x00000001;
991 smask = smask >> ( 32 - (BitsAllocated - BitsStored +1 ));
992 // nmask : to propagate sign bit on negative values
993 int32_t nmask = 0x80000000;
994 nmask = nmask >> ( BitsAllocated - BitsStored -1 );
996 for(int i = 0; i<l; i++)
998 *deb = *deb >> (BitsStored - HighBitPosition - 1);
1000 *deb = *deb | nmask;
1002 *deb = *deb & pmask;
1009 gdcmWarningMacro("Weird image (BitsAllocated !=8, 12, 16, 32)");
1010 throw FormatError( "Weird image !?" );
1017 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
1018 * \warning Works on all the frames at a time
1020 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
1022 gdcmWarningMacro("--> ConvertRGBPlanesToRGBPixels");
1024 uint8_t *localRaw = Raw;
1025 uint8_t *copyRaw = new uint8_t[ RawSize ];
1026 memmove( copyRaw, localRaw, RawSize );
1028 int l = XSize * YSize * ZSize;
1030 uint8_t *a = copyRaw;
1031 uint8_t *b = copyRaw + l;
1032 uint8_t *c = copyRaw + l + l;
1034 for (int j = 0; j < l; j++)
1036 *(localRaw++) = *(a++);
1037 *(localRaw++) = *(b++);
1038 *(localRaw++) = *(c++);
1044 * \brief Convert (cY plane, cB plane, cR plane) to RGB pixels
1045 * \warning Works on all the frames at a time
1047 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
1049 // Remarks for YBR newbees :
1050 // YBR_FULL works very much like RGB, i.e. three samples per pixel,
1051 // just the color space is YCbCr instead of RGB. This is particularly useful
1052 // for doppler ultrasound where most of the image is grayscale
1053 // (i.e. only populates the Y components) and Cb and Cr are mostly zero,
1054 // except for the few patches of color on the image.
1055 // On such images, RLE achieves a compression ratio that is much better
1056 // than the compression ratio on an equivalent RGB image.
1058 gdcmWarningMacro("--> ConvertYcBcRPlanesToRGBPixels");
1060 uint8_t *localRaw = Raw;
1061 uint8_t *copyRaw = new uint8_t[ RawSize ];
1062 memmove( copyRaw, localRaw, RawSize );
1064 // to see the tricks about YBR_FULL, YBR_FULL_422,
1065 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
1066 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
1067 // and be *very* affraid
1069 int l = XSize * YSize;
1070 int nbFrames = ZSize;
1072 uint8_t *a = copyRaw + 0;
1073 uint8_t *b = copyRaw + l;
1074 uint8_t *c = copyRaw + l+ l;
1077 /// We replaced easy to understand but time consuming floating point
1078 /// computations by the 'well known' integer computation counterpart
1080 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
1081 /// for code optimisation.
1083 for ( int i = 0; i < nbFrames; i++ )
1085 for ( int j = 0; j < l; j++ )
1087 R = 38142 *(*a-16) + 52298 *(*c -128);
1088 G = 38142 *(*a-16) - 26640 *(*c -128) - 12845 *(*b -128);
1089 B = 38142 *(*a-16) + 66093 *(*b -128);
1098 if (R > 255) R = 255;
1099 if (G > 255) G = 255;
1100 if (B > 255) B = 255;
1102 *(localRaw++) = (uint8_t)R;
1103 *(localRaw++) = (uint8_t)G;
1104 *(localRaw++) = (uint8_t)B;
1113 /// \brief Deals with the color decoding i.e. handle:
1114 /// - R, G, B planes (as opposed to RGB pixels)
1115 /// - YBR (various) encodings.
1116 /// - LUT[s] (or "PALETTE COLOR").
1118 void PixelReadConvert::ConvertHandleColor()
1120 //////////////////////////////////
1121 // Deal with the color decoding i.e. handle:
1122 // - R, G, B planes (as opposed to RGB pixels)
1123 // - YBR (various) encodings.
1124 // - LUT[s] (or "PALETTE COLOR").
1126 // The classification in the color decoding schema is based on the blending
1127 // of two Dicom tags values:
1128 // * "Photometric Interpretation" for which we have the cases:
1129 // - [Photo A] MONOCHROME[1|2] pictures,
1130 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
1131 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
1132 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
1133 // * "Planar Configuration" for which we have the cases:
1134 // - [Planar 0] 0 then Pixels are already RGB
1135 // - [Planar 1] 1 then we have 3 planes : R, G, B,
1136 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
1138 // Now in theory, one could expect some coherence when blending the above
1139 // cases. For example we should not encounter files belonging at the
1140 // time to case [Planar 0] and case [Photo D].
1141 // Alas, this was only theory ! Because in practice some odd (read ill
1142 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
1143 // - "Planar Configuration" = 0,
1144 // - "Photometric Interpretation" = "PALETTE COLOR".
1145 // Hence gdcm will use the folowing "heuristic" in order to be tolerant
1146 // towards Dicom-non-conformant files:
1147 // << whatever the "Planar Configuration" value might be, a
1148 // "Photometric Interpretation" set to "PALETTE COLOR" forces
1149 // a LUT intervention >>
1151 // Now we are left with the following handling of the cases:
1152 // - [Planar 0] OR [Photo A] no color decoding (since respectively
1153 // Pixels are already RGB and monochrome pictures have no color :),
1154 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
1155 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
1156 // - [Planar 2] OR [Photo D] requires LUT intervention.
1158 gdcmWarningMacro("--> ConvertHandleColor"
1159 << "Planar Configuration " << PlanarConfiguration );
1163 // [Planar 2] OR [Photo D]: LUT intervention done outside
1164 gdcmWarningMacro("--> RawRGB : LUT intervention done outside");
1168 if ( PlanarConfiguration == 1 )
1172 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
1173 gdcmWarningMacro("--> YBRFull");
1174 ConvertYcBcRPlanesToRGBPixels();
1178 // [Planar 1] AND [Photo C]
1179 gdcmWarningMacro("--> YBRFull");
1180 ConvertRGBPlanesToRGBPixels();
1185 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
1186 // pixels need to be RGB-fyied anyway
1190 gdcmWarningMacro("--> RLE Lossless");
1191 ConvertRGBPlanesToRGBPixels();
1194 // In *normal *case, when planarConf is 0, pixels are already in RGB
1197 /// Computes the Pixels Size
1198 void PixelReadConvert::ComputeRawAndRGBSizes()
1200 int bitsAllocated = BitsAllocated;
1201 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
1202 // in this case we will expand the image to 16 bits (see
1203 // \ref ReadAndDecompress12BitsTo16Bits() )
1204 if ( BitsAllocated == 12 )
1209 RawSize = XSize * YSize * ZSize
1210 * ( bitsAllocated / 8 )
1214 RGBSize = 3 * RawSize; // works for 8 and 16 bits per Pixel
1222 /// Allocates room for RGB Pixels
1223 void PixelReadConvert::AllocateRGB()
1227 RGB = new uint8_t[RGBSize];
1230 /// Allocates room for RAW Pixels
1231 void PixelReadConvert::AllocateRaw()
1235 Raw = new uint8_t[RawSize];
1238 //-----------------------------------------------------------------------------
1241 * \brief Print self.
1242 * @param indent Indentation string to be prepended during printing.
1243 * @param os Stream to print to.
1245 void PixelReadConvert::Print( std::ostream &os, std::string const &indent )
1248 << "--- Pixel information -------------------------"
1251 << "Pixel Data: offset " << PixelOffset
1252 << " x(" << std::hex << PixelOffset << std::dec
1253 << ") length " << PixelDataLength
1254 << " x(" << std::hex << PixelDataLength << std::dec
1255 << ")" << std::endl;
1257 if ( IsRLELossless )
1261 RLEInfo->Print( os, indent );
1265 gdcmWarningMacro("Set as RLE file but NO RLEinfo present.");
1269 if ( IsJPEG2000 || IsJPEGLossless || IsJPEGLossy || IsJPEGLS )
1273 JPEGInfo->Print( os, indent );
1277 gdcmWarningMacro("Set as JPEG file but NO JPEGinfo present.");
1282 //-----------------------------------------------------------------------------
1283 } // end namespace gdcm
1285 // NOTES on File internal calls
1287 // ---> GetImageData
1288 // ---> GetImageDataIntoVector
1289 // |---> GetImageDataIntoVectorRaw
1290 // | lut intervention
1292 // ---> GetImageDataRaw
1293 // ---> GetImageDataIntoVectorRaw