1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/10/14 22:35:02 $
7 Version: $Revision: 1.13 $
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 PIXELCONVERT everywhere and clean up !
25 #include "gdcmDebug.h"
26 #include "gdcmPixelConvert.h"
31 #define str2num(str, typeNum) *((typeNum *)(str))
33 // For JPEG 2000, body in file gdcmJpeg2000.cxx
34 bool gdcm_read_JPEG2000_file (FILE* fp, void* image_buffer);
36 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
37 bool gdcm_read_JPEG_file8 (FILE* fp, void* image_buffer);
39 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
40 bool gdcm_read_JPEG_file12 (FILE* fp, void* image_buffer);
42 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
43 // Beware this is misleading there is no 16bits DCT algorithm, only
44 // jpeg lossless compression exist in 16bits.
45 bool gdcm_read_JPEG_file16 (FILE* fp, void* image_buffer);
48 //-----------------------------------------------------------------------------
49 // Constructor / Destructor
50 PixelConvert::PixelConvert()
58 void PixelConvert::Squeeze()
64 delete [] Decompressed;
68 PixelConvert::~PixelConvert()
73 void PixelConvert::AllocateRGB()
78 RGB = new uint8_t[RGBSize];
81 void PixelConvert::AllocateDecompressed()
84 delete [] Decompressed;
86 Decompressed = new uint8_t[ DecompressedSize ];
90 * \brief Read from file a 12 bits per pixel image and uncompress it
91 * into a 16 bits per pixel image.
93 void PixelConvert::ReadAndDecompress12BitsTo16Bits(
98 int nbPixels = XSize * YSize;
99 uint16_t* destination = (uint16_t*)pixelZone;
101 for( int p = 0; p < nbPixels; p += 2 )
106 ItemRead = fread( &b0, 1, 1, filePtr);
109 throw FormatError( "File::ReadAndDecompress12BitsTo16Bits()",
110 "Unfound first block" );
113 ItemRead = fread( &b1, 1, 1, filePtr);
116 throw FormatError( "File::ReadAndDecompress12BitsTo16Bits()",
117 "Unfound second block" );
120 ItemRead = fread( &b2, 1, 1, filePtr);
123 throw FormatError( "File::ReadAndDecompress12BitsTo16Bits()",
124 "Unfound second block" );
127 // Two steps are necessary to please VC++
129 // 2 pixels 12bit = [0xABCDEF]
130 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
132 *destination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
134 *destination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
136 /// \todo JPR Troubles expected on Big-Endian processors ?
141 * \brief Try to deal with RLE 16 Bits.
142 * We assume the RLE has allready been parsed and loaded in
143 * Uncompressed (through \ref ReadAndDecompressJPEGFile ).
144 * We here need to make 16 Bits Pixels from Low Byte and
145 * High Byte 'Planes'...(for what it may mean)
148 bool PixelConvert::UncompressRLE16BitsFromRLE8Bits(
150 uint8_t* fixMemUncompressed )
152 size_t PixelNumber = XSize * YSize;
153 size_t fixMemUncompressedSize = XSize * YSize * NumberOfFrames;
155 // We assumed Uncompressed contains the decoded RLE pixels but as
156 // 8 bits per pixel. In order to convert those pixels to 16 bits
157 // per pixel we cannot work in place within Uncompressed and hence
158 // we copy Uncompressed in a safe place, say OldUncompressed.
160 uint8_t* OldUncompressed = new uint8_t[ fixMemUncompressedSize * 2 ];
161 memmove( OldUncompressed, fixMemUncompressed, fixMemUncompressedSize * 2);
163 uint8_t* x = fixMemUncompressed;
164 uint8_t* a = OldUncompressed;
165 uint8_t* b = a + PixelNumber;
167 for ( int i = 0; i < NumberOfFrames; i++ )
169 for ( unsigned int j = 0; j < PixelNumber; j++ )
176 delete[] OldUncompressed;
178 /// \todo check that operator new []didn't fail, and sometimes return false
183 * \brief Implementation of the RLE decoding algorithm for uncompressing
184 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
186 bool PixelConvert::ReadAndUncompressRLEFragment( uint8_t* decodedZone,
188 long uncompressedSegmentSize,
192 long numberOfOutputBytes = 0;
193 long numberOfReadBytes = 0;
195 while( numberOfOutputBytes < uncompressedSegmentSize )
197 fread( &count, 1, 1, fp );
198 numberOfReadBytes += 1;
200 // Note: count <= 127 comparison is always true due to limited range
201 // of data type int8_t [since the maximum of an exact width
202 // signed integer of width N is 2^(N-1) - 1, which for int8_t
205 fread( decodedZone, count + 1, 1, fp);
206 numberOfReadBytes += count + 1;
207 decodedZone += count + 1;
208 numberOfOutputBytes += count + 1;
212 if ( ( count <= -1 ) && ( count >= -127 ) )
215 fread( &newByte, 1, 1, fp);
216 numberOfReadBytes += 1;
217 for( int i = 0; i < -count + 1; i++ )
219 decodedZone[i] = newByte;
221 decodedZone += -count + 1;
222 numberOfOutputBytes += -count + 1;
225 // if count = 128 output nothing
227 if ( numberOfReadBytes > fragmentSize )
229 dbg.Verbose(0, "File::gdcm_read_RLE_fragment: we read more "
230 "bytes than the segment size.");
238 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
239 * Dicom encapsulated file and uncompress it.
240 * @param fp already open File Pointer
241 * @param image_buffer destination Address (in caller's memory space)
242 * at which the pixel data should be copied
245 bool PixelConvert::ReadAndDecompressRLEFile(
249 uint8_t* im = (uint8_t*)image_buffer;
250 long uncompressedSegmentSize = XSize * YSize;
252 // Loop on the frame[s]
253 for( RLEFramesInfo::RLEFrameList::iterator
254 it = RLEInfo->Frames.begin();
255 it != RLEInfo->Frames.end();
258 // Loop on the fragments
259 for( int k = 1; k <= (*it)->NumberFragments; k++ )
261 fseek( fp, (*it)->Offset[k] ,SEEK_SET );
262 (void)PixelConvert::ReadAndUncompressRLEFragment(
263 (uint8_t*) im, (*it)->Length[k],
264 uncompressedSegmentSize, fp );
265 im += uncompressedSegmentSize;
269 if ( BitsAllocated == 16 )
271 // Try to deal with RLE 16 Bits
272 (void)UncompressRLE16BitsFromRLE8Bits( ZSize,
273 (uint8_t*) image_buffer);
280 * \brief Swap the bytes, according to swap code.
281 * \warning not end user intended
282 * @param im area to deal with
284 void PixelConvert::SwapZone( uint8_t* im )
288 if( BitsAllocated == 16 )
290 uint16_t* im16 = (uint16_t*)im;
301 for( i = 0; i < DecompressedSize / 2; i++ )
303 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
307 dbg.Verbose( 0, "PixelConvert::SwapZone: SwapCode value "
308 "(16 bits) not allowed." );
311 else if( BitsAllocated == 32 )
314 uint16_t fort, faible;
315 uint32_t* im32 = (uint32_t*)im;
322 for( i = 0; i < DecompressedSize / 4; i++ )
324 faible = im32[i] & 0x0000ffff; // 4321
325 fort = im32[i] >> 16;
326 fort = ( fort >> 8 ) | ( fort << 8 );
327 faible = ( faible >> 8 ) | ( faible << 8);
329 im32[i] = ( s32 << 16 ) | fort;
333 for( i = 0; i < DecompressedSize / 4; i++ )
335 faible = im32[i] & 0x0000ffff; // 2143
336 fort = im32[i] >> 16;
337 fort = ( fort >> 8 ) | ( fort << 8 );
338 faible = ( faible >> 8) | ( faible << 8);
340 im32[i] = ( s32 << 16 ) | faible;
344 for( i = 0; i < DecompressedSize / 4; i++ )
346 faible = im32[i] & 0x0000ffff; // 3412
347 fort = im32[i] >> 16;
349 im32[i] = ( s32 << 16 ) | fort;
353 dbg.Verbose( 0, "PixelConvert::SwapZone: SwapCode value "
354 "(32 bits) not allowed." );
360 * \brief Deal with endianity i.e. re-arange bytes inside the integer
362 void PixelConvert::ReorderEndianity( uint8_t* pixelZone )
364 if ( BitsAllocated != 8 )
366 SwapZone( pixelZone );
369 // Special kludge in order to deal with xmedcon broken images:
370 if ( ( BitsAllocated == 16 )
371 && ( BitsStored < BitsAllocated )
374 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
375 uint16_t *deb = (uint16_t *)pixelZone;
376 for(int i = 0; i<l; i++)
388 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
389 & file and uncompress it.
390 * @param fp already open File Pointer
391 * @param destination Where decompressed fragments should end up
394 bool PixelConvert::ReadAndDecompressJPEGFile(
395 uint8_t* destination,
398 // Loop on the fragment[s]
399 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
400 it = JPEGInfo->Fragments.begin();
401 it != JPEGInfo->Fragments.end();
404 fseek( fp, (*it)->Offset, SEEK_SET );
408 if ( ! gdcm_read_JPEG2000_file( fp, destination ) )
413 else if ( BitsStored == 8)
415 // JPEG Lossy : call to IJG 6b
416 if ( ! gdcm_read_JPEG_file8( fp, destination ) )
421 else if ( BitsStored == 12)
423 // Reading Fragment pixels
424 if ( ! gdcm_read_JPEG_file12 ( fp, destination ) )
429 else if ( BitsStored == 16)
431 // Reading Fragment pixels
432 if ( ! gdcm_read_JPEG_file16 ( fp, destination ) )
436 //assert( IsJPEGLossless );
440 // other JPEG lossy not supported
441 dbg.Error(" File::ReadAndDecompressJPEGFile: unknown jpeg lossy "
446 // Advance to next free location in destination
447 // for next fragment decompression (if any)
448 int length = XSize * YSize * SamplesPerPixel;
449 int numberBytes = BitsAllocated / 8;
451 destination += length * numberBytes;
457 * \brief Re-arrange the bits within the bytes.
458 * @param pixelZone zone
461 bool PixelConvert::ReArrangeBits( uint8_t* pixelZone )
462 throw ( FormatError )
464 if ( BitsStored != BitsAllocated )
466 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
467 if ( BitsAllocated == 16 )
469 uint16_t mask = 0xffff;
470 mask = mask >> ( BitsAllocated - BitsStored );
471 uint16_t* deb = (uint16_t*)pixelZone;
472 for(int i = 0; i<l; i++)
474 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
478 else if ( BitsAllocated == 32 )
480 uint32_t mask = 0xffffffff;
481 mask = mask >> ( BitsAllocated - BitsStored );
482 uint32_t* deb = (uint32_t*)pixelZone;
483 for(int i = 0; i<l; i++)
485 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
491 dbg.Verbose(0, "PixelConvert::ReArrangeBits: weird image");
492 throw FormatError( "File::ReArrangeBits()",
500 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
501 * \warning Works on all the frames at a time
503 void PixelConvert::ConvertYcBcRPlanesToRGBPixels( uint8_t* destination )
505 uint8_t* oldPixelZone = new uint8_t[ DecompressedSize ];
506 memmove( oldPixelZone, destination, DecompressedSize );
508 // to see the tricks about YBR_FULL, YBR_FULL_422,
509 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
510 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
511 // and be *very* affraid
513 int l = XSize * YSize;
514 int nbFrames = ZSize;
516 uint8_t* a = oldPixelZone;
517 uint8_t* b = oldPixelZone + l;
518 uint8_t* c = oldPixelZone + l + l;
521 /// \todo : Replace by the 'well known' integer computation
522 /// counterpart. Refer to
523 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
524 /// for code optimisation.
526 for ( int i = 0; i < nbFrames; i++ )
528 for ( int j = 0; j < l; j++ )
530 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
531 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
532 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
534 if (R < 0.0) R = 0.0;
535 if (G < 0.0) G = 0.0;
536 if (B < 0.0) B = 0.0;
537 if (R > 255.0) R = 255.0;
538 if (G > 255.0) G = 255.0;
539 if (B > 255.0) B = 255.0;
541 *(destination++) = (uint8_t)R;
542 *(destination++) = (uint8_t)G;
543 *(destination++) = (uint8_t)B;
549 delete[] oldPixelZone;
553 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
554 * \warning Works on all the frames at a time
556 void PixelConvert::ConvertRGBPlanesToRGBPixels( uint8_t* destination )
558 uint8_t* oldPixelZone = new uint8_t[ DecompressedSize ];
559 memmove( oldPixelZone, destination, DecompressedSize );
561 int l = XSize * YSize * ZSize;
563 uint8_t* a = oldPixelZone;
564 uint8_t* b = oldPixelZone + l;
565 uint8_t* c = oldPixelZone + l + l;
567 for (int j = 0; j < l; j++)
569 *(destination++) = *(a++);
570 *(destination++) = *(b++);
571 *(destination++) = *(c++);
573 delete[] oldPixelZone;
576 bool PixelConvert::ReadAndDecompressPixelData( void* destination, FILE* fp )
578 //////////////////////////////////////////////////
579 //// First stage: get our hands on the Pixel Data.
582 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
583 "unavailable file pointer." );
587 if ( fseek(fp, PixelOffset, SEEK_SET) == -1 )
589 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
590 "unable to find PixelOffset in file." );
594 //////////////////////////////////////////////////
595 //// Second stage: read from disk dans uncompress.
596 if ( BitsAllocated == 12 )
598 ReadAndDecompress12BitsTo16Bits( (uint8_t*)destination, fp);
600 else if ( IsUncompressed )
602 size_t ItemRead = fread( destination, PixelDataLength, 1, fp);
605 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
606 "reading of uncompressed pixel data failed." );
610 else if ( IsRLELossless )
612 if ( ! ReadAndDecompressRLEFile( destination, fp ) )
614 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
615 "RLE decompressor failed." );
621 // Default case concerns JPEG family
622 if ( ! ReadAndDecompressJPEGFile( (uint8_t*)destination, fp ) )
624 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
625 "JPEG decompressor failed." );
630 ////////////////////////////////////////////
631 //// Third stage: twigle the bytes and bits.
632 ReorderEndianity( (uint8_t*) destination );
633 ReArrangeBits( (uint8_t*) destination );
638 bool PixelConvert::HandleColor( uint8_t* destination )
640 //////////////////////////////////
641 // Deal with the color decoding i.e. handle:
642 // - R, G, B planes (as opposed to RGB pixels)
643 // - YBR (various) encodings.
644 // - LUT[s] (or "PALETTE COLOR").
646 // The classification in the color decoding schema is based on the blending
647 // of two Dicom tags values:
648 // * "Photometric Interpretation" for which we have the cases:
649 // - [Photo A] MONOCHROME[1|2] pictures,
650 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
651 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
652 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
653 // * "Planar Configuration" for which we have the cases:
654 // - [Planar 0] 0 then Pixels are already RGB
655 // - [Planar 1] 1 then we have 3 planes : R, G, B,
656 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
658 // Now in theory, one could expect some coherence when blending the above
659 // cases. For example we should not encounter files belonging at the
660 // time to case [Planar 0] and case [Photo D].
661 // Alas, this was only theory ! Because in practice some odd (read ill
662 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
663 // - "Planar Configuration" = 0,
664 // - "Photometric Interpretation" = "PALETTE COLOR".
665 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
666 // towards Dicom-non-conformance files:
667 // << whatever the "Planar Configuration" value might be, a
668 // "Photometric Interpretation" set to "PALETTE COLOR" forces
669 // a LUT intervention >>
671 // Now we are left with the following handling of the cases:
672 // - [Planar 0] OR [Photo A] no color decoding (since respectively
673 // Pixels are already RGB and monochrome pictures have no color :),
674 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
675 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
676 // - [Planar 2] OR [Photo D] requires LUT intervention.
679 || ( PlanarConfiguration == 2 )
682 // [Planar 2] OR [Photo D]: LUT intervention done outside
686 if ( PlanarConfiguration == 1 )
690 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
691 ConvertYcBcRPlanesToRGBPixels( (uint8_t*)destination );
695 // [Planar 1] AND [Photo C]
696 ConvertRGBPlanesToRGBPixels( (uint8_t*)destination );
700 // When planarConf is 0, pixels are allready in RGB
704 void PixelConvert::ComputeDecompressedImageDataSize()
707 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
708 // in this case we will expand the image to 16 bits (see
709 // \ref ReadAndDecompress12BitsTo16Bits() )
710 if ( BitsAllocated == 12 )
715 DecompressedSize = XSize * YSize * ZSize
716 * ( bitsAllocated / 8 )
720 } // end namespace gdcm
722 // NOTES on File internal calls
725 // ---> GetImageDataIntoVector
726 // |---> GetImageDataIntoVectorRaw
727 // | lut intervention
729 // ---> GetImageDataRaw
730 // ---> GetImageDataIntoVectorRaw