1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/10/15 10:43:28 $
7 Version: $Revision: 1.14 $
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( FILE* fp )
96 int nbPixels = XSize * YSize;
97 uint16_t* localDecompres = (uint16_t*)Decompressed;
99 for( int p = 0; p < nbPixels; p += 2 )
104 ItemRead = fread( &b0, 1, 1, fp );
107 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
108 "Unfound first block" );
111 ItemRead = fread( &b1, 1, 1, fp );
114 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
115 "Unfound second block" );
118 ItemRead = fread( &b2, 1, 1, fp );
121 throw FormatError( "PixelConvert::ReadAndDecompress12BitsTo16Bits()",
122 "Unfound second block" );
125 // Two steps are necessary to please VC++
127 // 2 pixels 12bit = [0xABCDEF]
128 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
130 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
132 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
134 /// \todo JPR Troubles expected on Big-Endian processors ?
139 * \brief Try to deal with RLE 16 Bits.
140 * We assume the RLE has allready been parsed and loaded in
141 * Decompressed (through \ref ReadAndDecompressJPEGFile ).
142 * We here need to make 16 Bits Pixels from Low Byte and
143 * High Byte 'Planes'...(for what it may mean)
146 bool PixelConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
148 size_t PixelNumber = XSize * YSize;
149 size_t uncompressedSize = XSize * YSize * NumberOfFrames;
151 // We assumed Decompressed contains the decoded RLE pixels but as
152 // 8 bits per pixel. In order to convert those pixels to 16 bits
153 // per pixel we cannot work in place within Decompressed and hence
154 // we copy it in a safe place, say copyDecompressed.
156 uint8_t* copyDecompressed = new uint8_t[ uncompressedSize * 2 ];
157 memmove( copyDecompressed, Decompressed, uncompressedSize * 2 );
159 uint8_t* x = Decompressed;
160 uint8_t* a = copyDecompressed;
161 uint8_t* b = a + PixelNumber;
163 for ( int i = 0; i < NumberOfFrames; i++ )
165 for ( unsigned int j = 0; j < PixelNumber; j++ )
172 delete[] copyDecompressed;
174 /// \todo check that operator new []didn't fail, and sometimes return false
179 * \brief Implementation of the RLE decoding algorithm for uncompressing
180 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
181 * @param subDecompressed Sub region of \ref Decompressed where the de
182 * decoded fragment should be placed.
183 * @param fragmentSize The length of the binary fragment as found on the disk.
184 * @param uncompressedSegmentSize The expected length of the fragment ONCE
186 * @param fp File Pointer: on entry the position should be the one of
187 * the fragment to be decoded.
189 bool PixelConvert::ReadAndDecompressRLEFragment( uint8_t* subDecompressed,
191 long uncompressedSegmentSize,
195 long numberOfOutputBytes = 0;
196 long numberOfReadBytes = 0;
198 while( numberOfOutputBytes < uncompressedSegmentSize )
200 fread( &count, 1, 1, fp );
201 numberOfReadBytes += 1;
203 // Note: count <= 127 comparison is always true due to limited range
204 // of data type int8_t [since the maximum of an exact width
205 // signed integer of width N is 2^(N-1) - 1, which for int8_t
208 fread( subDecompressed, count + 1, 1, fp);
209 numberOfReadBytes += count + 1;
210 subDecompressed += count + 1;
211 numberOfOutputBytes += count + 1;
215 if ( ( count <= -1 ) && ( count >= -127 ) )
218 fread( &newByte, 1, 1, fp);
219 numberOfReadBytes += 1;
220 for( int i = 0; i < -count + 1; i++ )
222 subDecompressed[i] = newByte;
224 subDecompressed += -count + 1;
225 numberOfOutputBytes += -count + 1;
228 // if count = 128 output nothing
230 if ( numberOfReadBytes > fragmentSize )
232 dbg.Verbose(0, "PixelConvert::ReadAndDecompressRLEFragment: we "
233 "read more bytes than the segment size.");
241 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
242 * Dicom encapsulated file and uncompress it.
243 * @param fp already open File Pointer
244 * at which the pixel data should be copied
247 bool PixelConvert::ReadAndDecompressRLEFile( FILE* fp )
249 uint8_t* subDecompressed = Decompressed;
250 long decompressedSegmentSize = 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)ReadAndDecompressRLEFragment( subDecompressed,
264 decompressedSegmentSize,
266 subDecompressed += decompressedSegmentSize;
270 if ( BitsAllocated == 16 )
272 // Try to deal with RLE 16 Bits
273 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
280 * \brief Swap the bytes, according to \ref SwapCode.
282 void PixelConvert::ConvertSwapZone()
286 if( BitsAllocated == 16 )
288 uint16_t* im16 = (uint16_t*)Decompressed;
299 for( i = 0; i < DecompressedSize / 2; i++ )
301 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
305 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
306 "(16 bits) not allowed." );
309 else if( BitsAllocated == 32 )
314 uint32_t* im32 = (uint32_t*)Decompressed;
321 for( i = 0; i < DecompressedSize / 4; i++ )
323 low = im32[i] & 0x0000ffff; // 4321
324 high = im32[i] >> 16;
325 high = ( high >> 8 ) | ( high << 8 );
326 low = ( low >> 8 ) | ( low << 8 );
328 im32[i] = ( s32 << 16 ) | high;
332 for( i = 0; i < DecompressedSize / 4; i++ )
334 low = im32[i] & 0x0000ffff; // 2143
335 high = im32[i] >> 16;
336 high = ( high >> 8 ) | ( high << 8 );
337 low = ( low >> 8 ) | ( low << 8 );
339 im32[i] = ( s32 << 16 ) | low;
343 for( i = 0; i < DecompressedSize / 4; i++ )
345 low = im32[i] & 0x0000ffff; // 3412
346 high = im32[i] >> 16;
348 im32[i] = ( s32 << 16 ) | high;
352 dbg.Verbose( 0, "PixelConvert::ConvertSwapZone: SwapCode value "
353 "(32 bits) not allowed." );
359 * \brief Deal with endianity i.e. re-arange bytes inside the integer
361 void PixelConvert::ConvertReorderEndianity()
363 if ( BitsAllocated != 8 )
368 // Special kludge in order to deal with xmedcon broken images:
369 if ( ( BitsAllocated == 16 )
370 && ( BitsStored < BitsAllocated )
373 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
374 uint16_t *deb = (uint16_t *)Decompressed;
375 for(int i = 0; i<l; i++)
387 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
388 & file and uncompress it.
389 * @param fp File Pointer
392 bool PixelConvert::ReadAndDecompressJPEGFile( FILE* fp )
394 uint8_t* localDecompressed = Decompressed;
395 // Loop on the fragment[s]
396 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
397 it = JPEGInfo->Fragments.begin();
398 it != JPEGInfo->Fragments.end();
401 fseek( fp, (*it)->Offset, SEEK_SET );
405 if ( ! gdcm_read_JPEG2000_file( fp,localDecompressed ) )
410 else if ( BitsStored == 8)
412 // JPEG Lossy : call to IJG 6b
413 if ( ! gdcm_read_JPEG_file8( fp, localDecompressed ) )
418 else if ( BitsStored == 12)
420 // Reading Fragment pixels
421 if ( ! gdcm_read_JPEG_file12 ( fp, localDecompressed ) )
426 else if ( BitsStored == 16)
428 // Reading Fragment pixels
429 if ( ! gdcm_read_JPEG_file16 ( fp, localDecompressed ) )
433 //assert( IsJPEGLossless );
437 // other JPEG lossy not supported
438 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
439 "jpeg lossy compression ");
443 // Advance to next free location in Decompressed
444 // for next fragment decompression (if any)
445 int length = XSize * YSize * SamplesPerPixel;
446 int numberBytes = BitsAllocated / 8;
448 localDecompressed += length * numberBytes;
454 * \brief Re-arrange the bits within the bytes.
457 bool PixelConvert::ConvertReArrangeBits() throw ( FormatError )
459 if ( BitsStored != BitsAllocated )
461 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
462 if ( BitsAllocated == 16 )
464 uint16_t mask = 0xffff;
465 mask = mask >> ( BitsAllocated - BitsStored );
466 uint16_t* deb = (uint16_t*)Decompressed;
467 for(int i = 0; i<l; i++)
469 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
473 else if ( BitsAllocated == 32 )
475 uint32_t mask = 0xffffffff;
476 mask = mask >> ( BitsAllocated - BitsStored );
477 uint32_t* deb = (uint32_t*)Decompressed;
478 for(int i = 0; i<l; i++)
480 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
486 dbg.Verbose(0, "PixelConvert::ConvertReArrangeBits: weird image");
487 throw FormatError( "PixelConvert::ConvertReArrangeBits()",
495 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
496 * \warning Works on all the frames at a time
498 void PixelConvert::ConvertYcBcRPlanesToRGBPixels()
500 uint8_t* localDecompressed = Decompressed;
501 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
502 memmove( copyDecompressed, localDecompressed, DecompressedSize );
504 // to see the tricks about YBR_FULL, YBR_FULL_422,
505 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
506 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
507 // and be *very* affraid
509 int l = XSize * YSize;
510 int nbFrames = ZSize;
512 uint8_t* a = copyDecompressed;
513 uint8_t* b = copyDecompressed + l;
514 uint8_t* c = copyDecompressed + l + l;
517 /// \todo : Replace by the 'well known' integer computation
518 /// counterpart. Refer to
519 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
520 /// for code optimisation.
522 for ( int i = 0; i < nbFrames; i++ )
524 for ( int j = 0; j < l; j++ )
526 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
527 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
528 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
530 if (R < 0.0) R = 0.0;
531 if (G < 0.0) G = 0.0;
532 if (B < 0.0) B = 0.0;
533 if (R > 255.0) R = 255.0;
534 if (G > 255.0) G = 255.0;
535 if (B > 255.0) B = 255.0;
537 *(localDecompressed++) = (uint8_t)R;
538 *(localDecompressed++) = (uint8_t)G;
539 *(localDecompressed++) = (uint8_t)B;
545 delete[] copyDecompressed;
549 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
550 * \warning Works on all the frames at a time
552 void PixelConvert::ConvertRGBPlanesToRGBPixels()
554 uint8_t* localDecompressed = Decompressed;
555 uint8_t* copyDecompressed = new uint8_t[ DecompressedSize ];
556 memmove( copyDecompressed, localDecompressed, DecompressedSize );
558 int l = XSize * YSize * ZSize;
560 uint8_t* a = copyDecompressed;
561 uint8_t* b = copyDecompressed + l;
562 uint8_t* c = copyDecompressed + l + l;
564 for (int j = 0; j < l; j++)
566 *(localDecompressed++) = *(a++);
567 *(localDecompressed++) = *(b++);
568 *(localDecompressed++) = *(c++);
570 delete[] copyDecompressed;
573 bool PixelConvert::ReadAndDecompressPixelData( FILE* fp )
575 ComputeDecompressedImageDataSize();
577 DecompressedSize *= 3;
578 AllocateDecompressed();
579 //////////////////////////////////////////////////
580 //// First stage: get our hands on the Pixel Data.
583 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
584 "unavailable file pointer." );
588 if ( fseek( fp, PixelOffset, SEEK_SET ) == -1 )
590 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
591 "unable to find PixelOffset in file." );
595 //////////////////////////////////////////////////
596 //// Second stage: read from disk dans uncompress.
597 if ( BitsAllocated == 12 )
599 ReadAndDecompress12BitsTo16Bits( fp);
601 else if ( IsUncompressed )
603 size_t ItemRead = fread( Decompressed, PixelDataLength, 1, fp );
606 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
607 "reading of uncompressed pixel data failed." );
611 else if ( IsRLELossless )
613 if ( ! ReadAndDecompressRLEFile( fp ) )
615 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
616 "RLE decompressor failed." );
622 // Default case concerns JPEG family
623 if ( ! ReadAndDecompressJPEGFile( fp ) )
625 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
626 "JPEG decompressor failed." );
631 ////////////////////////////////////////////
632 //// Third stage: twigle the bytes and bits.
633 ConvertReorderEndianity();
634 ConvertReArrangeBits();
635 ConvertHandleColor();
640 void PixelConvert::ConvertHandleColor()
642 //////////////////////////////////
643 // Deal with the color decoding i.e. handle:
644 // - R, G, B planes (as opposed to RGB pixels)
645 // - YBR (various) encodings.
646 // - LUT[s] (or "PALETTE COLOR").
648 // The classification in the color decoding schema is based on the blending
649 // of two Dicom tags values:
650 // * "Photometric Interpretation" for which we have the cases:
651 // - [Photo A] MONOCHROME[1|2] pictures,
652 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
653 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
654 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
655 // * "Planar Configuration" for which we have the cases:
656 // - [Planar 0] 0 then Pixels are already RGB
657 // - [Planar 1] 1 then we have 3 planes : R, G, B,
658 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
660 // Now in theory, one could expect some coherence when blending the above
661 // cases. For example we should not encounter files belonging at the
662 // time to case [Planar 0] and case [Photo D].
663 // Alas, this was only theory ! Because in practice some odd (read ill
664 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
665 // - "Planar Configuration" = 0,
666 // - "Photometric Interpretation" = "PALETTE COLOR".
667 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
668 // towards Dicom-non-conformance files:
669 // << whatever the "Planar Configuration" value might be, a
670 // "Photometric Interpretation" set to "PALETTE COLOR" forces
671 // a LUT intervention >>
673 // Now we are left with the following handling of the cases:
674 // - [Planar 0] OR [Photo A] no color decoding (since respectively
675 // Pixels are already RGB and monochrome pictures have no color :),
676 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
677 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
678 // - [Planar 2] OR [Photo D] requires LUT intervention.
680 if ( ! IsDecompressedRGB() )
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();
695 // [Planar 1] AND [Photo C]
696 ConvertRGBPlanesToRGBPixels();
700 // When planarConf is 0, pixels are allready in RGB
704 * \brief Predicate to know wether the image[s] (once decompressed) is RGB.
705 * \note See comments of \ref HandleColor
707 bool PixelConvert::IsDecompressedRGB()
710 || ( PlanarConfiguration == 2 )
718 void PixelConvert::ComputeDecompressedImageDataSize()
720 int bitsAllocated = BitsAllocated;
721 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
722 // in this case we will expand the image to 16 bits (see
723 // \ref ReadAndDecompress12BitsTo16Bits() )
724 if ( BitsAllocated == 12 )
729 DecompressedSize = XSize * YSize * ZSize
730 * ( bitsAllocated / 8 )
734 } // end namespace gdcm
736 // NOTES on File internal calls
739 // ---> GetImageDataIntoVector
740 // |---> GetImageDataIntoVectorRaw
741 // | lut intervention
743 // ---> GetImageDataRaw
744 // ---> GetImageDataIntoVectorRaw