1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/10/14 05:33:14 $
7 Version: $Revision: 1.12 $
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"
28 // External JPEG decompression
30 // for JPEGLosslessDecodeImage
31 #include "jpeg/ljpg/jpegless.h"
36 #define str2num(str, typeNum) *((typeNum *)(str))
38 // For JPEG 2000, body in file gdcmJpeg2000.cxx
39 bool gdcm_read_JPEG2000_file (FILE* fp, void* image_buffer);
41 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
42 bool gdcm_read_JPEG_file (FILE* fp, void* image_buffer);
44 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
45 bool gdcm_read_JPEG_file12 (FILE* fp, void* image_buffer);
49 //-----------------------------------------------------------------------------
50 // Constructor / Destructor
51 PixelConvert::PixelConvert()
59 void PixelConvert::Squeeze()
65 delete [] Decompressed;
69 PixelConvert::~PixelConvert()
74 void PixelConvert::AllocateRGB()
79 RGB = new uint8_t[RGBSize];
82 void PixelConvert::AllocateDecompressed()
85 delete [] Decompressed;
87 Decompressed = new uint8_t[ DecompressedSize ];
91 * \brief Read from file a 12 bits per pixel image and uncompress it
92 * into a 16 bits per pixel image.
94 void PixelConvert::ReadAndDecompress12BitsTo16Bits(
99 int nbPixels = XSize * YSize;
100 uint16_t* destination = (uint16_t*)pixelZone;
102 for( int p = 0; p < nbPixels; p += 2 )
107 ItemRead = fread( &b0, 1, 1, filePtr);
110 throw FormatError( "File::ReadAndDecompress12BitsTo16Bits()",
111 "Unfound first block" );
114 ItemRead = fread( &b1, 1, 1, filePtr);
117 throw FormatError( "File::ReadAndDecompress12BitsTo16Bits()",
118 "Unfound second block" );
121 ItemRead = fread( &b2, 1, 1, filePtr);
124 throw FormatError( "File::ReadAndDecompress12BitsTo16Bits()",
125 "Unfound second block" );
128 // Two steps are necessary to please VC++
130 // 2 pixels 12bit = [0xABCDEF]
131 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
133 *destination++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
135 *destination++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
137 /// \todo JPR Troubles expected on Big-Endian processors ?
142 * \brief Try to deal with RLE 16 Bits.
143 * We assume the RLE has allready been parsed and loaded in
144 * Uncompressed (through \ref ReadAndDecompressJPEGFile ).
145 * We here need to make 16 Bits Pixels from Low Byte and
146 * High Byte 'Planes'...(for what it may mean)
149 bool PixelConvert::UncompressRLE16BitsFromRLE8Bits(
151 uint8_t* fixMemUncompressed )
153 size_t PixelNumber = XSize * YSize;
154 size_t fixMemUncompressedSize = XSize * YSize * NumberOfFrames;
156 // We assumed Uncompressed contains the decoded RLE pixels but as
157 // 8 bits per pixel. In order to convert those pixels to 16 bits
158 // per pixel we cannot work in place within Uncompressed and hence
159 // we copy Uncompressed in a safe place, say OldUncompressed.
161 uint8_t* OldUncompressed = new uint8_t[ fixMemUncompressedSize * 2 ];
162 memmove( OldUncompressed, fixMemUncompressed, fixMemUncompressedSize * 2);
164 uint8_t* x = fixMemUncompressed;
165 uint8_t* a = OldUncompressed;
166 uint8_t* b = a + PixelNumber;
168 for ( int i = 0; i < NumberOfFrames; i++ )
170 for ( unsigned int j = 0; j < PixelNumber; j++ )
177 delete[] OldUncompressed;
179 /// \todo check that operator new []didn't fail, and sometimes return false
184 * \brief Implementation of the RLE decoding algorithm for uncompressing
185 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
187 bool PixelConvert::ReadAndUncompressRLEFragment( uint8_t* decodedZone,
189 long uncompressedSegmentSize,
193 long numberOfOutputBytes = 0;
194 long numberOfReadBytes = 0;
196 while( numberOfOutputBytes < uncompressedSegmentSize )
198 fread( &count, 1, 1, fp );
199 numberOfReadBytes += 1;
201 // Note: count <= 127 comparison is always true due to limited range
202 // of data type int8_t [since the maximum of an exact width
203 // signed integer of width N is 2^(N-1) - 1, which for int8_t
206 fread( decodedZone, count + 1, 1, fp);
207 numberOfReadBytes += count + 1;
208 decodedZone += count + 1;
209 numberOfOutputBytes += count + 1;
213 if ( ( count <= -1 ) && ( count >= -127 ) )
216 fread( &newByte, 1, 1, fp);
217 numberOfReadBytes += 1;
218 for( int i = 0; i < -count + 1; i++ )
220 decodedZone[i] = newByte;
222 decodedZone += -count + 1;
223 numberOfOutputBytes += -count + 1;
226 // if count = 128 output nothing
228 if ( numberOfReadBytes > fragmentSize )
230 dbg.Verbose(0, "File::gdcm_read_RLE_fragment: we read more "
231 "bytes than the segment size.");
239 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
240 * Dicom encapsulated file and uncompress it.
241 * @param fp already open File Pointer
242 * @param image_buffer destination Address (in caller's memory space)
243 * at which the pixel data should be copied
246 bool PixelConvert::ReadAndDecompressRLEFile(
250 uint8_t* im = (uint8_t*)image_buffer;
251 long uncompressedSegmentSize = XSize * YSize;
254 // Loop on the frame[s]
255 for( RLEFramesInfo::RLEFrameList::iterator
256 it = RLEInfo->Frames.begin();
257 it != RLEInfo->Frames.end();
260 // Loop on the fragments
261 for( int k = 1; k <= (*it)->NumberFragments; k++ )
263 fseek( fp, (*it)->Offset[k] ,SEEK_SET );
264 (void)PixelConvert::ReadAndUncompressRLEFragment(
265 (uint8_t*) im, (*it)->Length[k],
266 uncompressedSegmentSize, fp );
267 im += uncompressedSegmentSize;
271 if ( BitsAllocated == 16 )
273 // Try to deal with RLE 16 Bits
274 (void)UncompressRLE16BitsFromRLE8Bits( ZSize,
275 (uint8_t*) image_buffer);
282 * \brief Swap the bytes, according to swap code.
283 * \warning not end user intended
284 * @param im area to deal with
286 void PixelConvert::SwapZone( uint8_t* im )
290 if( BitsAllocated == 16 )
292 uint16_t* im16 = (uint16_t*)im;
303 for( i = 0; i < DecompressedSize / 2; i++ )
305 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
309 dbg.Verbose( 0, "PixelConvert::SwapZone: SwapCode value "
310 "(16 bits) not allowed." );
313 else if( BitsAllocated == 32 )
316 uint16_t fort, faible;
317 uint32_t* im32 = (uint32_t*)im;
324 for( i = 0; i < DecompressedSize / 4; i++ )
326 faible = im32[i] & 0x0000ffff; // 4321
327 fort = im32[i] >> 16;
328 fort = ( fort >> 8 ) | ( fort << 8 );
329 faible = ( faible >> 8 ) | ( faible << 8);
331 im32[i] = ( s32 << 16 ) | fort;
335 for( i = 0; i < DecompressedSize / 4; i++ )
337 faible = im32[i] & 0x0000ffff; // 2143
338 fort = im32[i] >> 16;
339 fort = ( fort >> 8 ) | ( fort << 8 );
340 faible = ( faible >> 8) | ( faible << 8);
342 im32[i] = ( s32 << 16 ) | faible;
346 for( i = 0; i < DecompressedSize / 4; i++ )
348 faible = im32[i] & 0x0000ffff; // 3412
349 fort = im32[i] >> 16;
351 im32[i] = ( s32 << 16 ) | fort;
355 dbg.Verbose( 0, "PixelConvert::SwapZone: SwapCode value "
356 "(32 bits) not allowed." );
362 * \brief Deal with endianity i.e. re-arange bytes inside the integer
364 void PixelConvert::ReorderEndianity( uint8_t* pixelZone )
366 if ( BitsAllocated != 8 )
368 SwapZone( pixelZone );
371 // Special kludge in order to deal with xmedcon broken images:
372 if ( ( BitsAllocated == 16 )
373 && ( BitsStored < BitsAllocated )
376 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
377 uint16_t *deb = (uint16_t *)pixelZone;
378 for(int i = 0; i<l; i++)
390 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
391 & file and uncompress it.
392 * @param fp already open File Pointer
393 * @param destination Where decompressed fragments should end up
396 bool PixelConvert::ReadAndDecompressJPEGFile(
397 uint8_t* destination,
400 // Loop on the fragment[s]
401 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
402 it = JPEGInfo->Fragments.begin();
403 it != JPEGInfo->Fragments.end();
406 fseek( fp, (*it)->Offset, SEEK_SET );
410 if ( ! gdcm_read_JPEG2000_file( fp, destination ) )
415 else if ( IsJPEGLossless )
417 // JPEG LossLess : call to xmedcom Lossless JPEG
418 JPEGLosslessDecodeImage( fp,
419 (uint16_t*)destination,
420 PixelSize * 8 * SamplesPerPixel,
423 else if ( BitsStored == 8)
425 // JPEG Lossy : call to IJG 6b
426 if ( ! gdcm_read_JPEG_file ( fp, destination ) )
431 else if ( BitsStored == 12)
433 // Reading Fragment pixels
434 if ( ! gdcm_read_JPEG_file12 ( fp, destination ) )
441 // other JPEG lossy not supported
442 dbg.Error(" File::ReadAndDecompressJPEGFile: unknown jpeg lossy "
447 // Advance to next free location in destination
448 // for next fragment decompression (if any)
449 int length = XSize * YSize * SamplesPerPixel;
450 int numberBytes = BitsAllocated / 8;
452 destination = (uint8_t*)destination + length * numberBytes;
459 * \brief Re-arrange the bits within the bytes.
460 * @param pixelZone zone
463 bool PixelConvert::ReArrangeBits( uint8_t* pixelZone )
464 throw ( FormatError )
466 if ( BitsStored != BitsAllocated )
468 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
469 if ( BitsAllocated == 16 )
471 uint16_t mask = 0xffff;
472 mask = mask >> ( BitsAllocated - BitsStored );
473 uint16_t* deb = (uint16_t*)pixelZone;
474 for(int i = 0; i<l; i++)
476 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
480 else if ( BitsAllocated == 32 )
482 uint32_t mask = 0xffffffff;
483 mask = mask >> ( BitsAllocated - BitsStored );
484 uint32_t* deb = (uint32_t*)pixelZone;
485 for(int i = 0; i<l; i++)
487 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
493 dbg.Verbose(0, "PixelConvert::ReArrangeBits: weird image");
494 throw FormatError( "File::ReArrangeBits()",
502 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
503 * \warning Works on all the frames at a time
505 void PixelConvert::ConvertYcBcRPlanesToRGBPixels( uint8_t* destination )
507 uint8_t* oldPixelZone = new uint8_t[ DecompressedSize ];
508 memmove( oldPixelZone, destination, DecompressedSize );
510 // to see the tricks about YBR_FULL, YBR_FULL_422,
511 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
512 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
513 // and be *very* affraid
515 int l = XSize * YSize;
516 int nbFrames = ZSize;
518 uint8_t* a = oldPixelZone;
519 uint8_t* b = oldPixelZone + l;
520 uint8_t* c = oldPixelZone + l + l;
523 /// \todo : Replace by the 'well known' integer computation
524 /// counterpart. Refer to
525 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
526 /// for code optimisation.
528 for ( int i = 0; i < nbFrames; i++ )
530 for ( int j = 0; j < l; j++ )
532 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
533 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
534 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
536 if (R < 0.0) R = 0.0;
537 if (G < 0.0) G = 0.0;
538 if (B < 0.0) B = 0.0;
539 if (R > 255.0) R = 255.0;
540 if (G > 255.0) G = 255.0;
541 if (B > 255.0) B = 255.0;
543 *(destination++) = (uint8_t)R;
544 *(destination++) = (uint8_t)G;
545 *(destination++) = (uint8_t)B;
551 delete[] oldPixelZone;
555 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
556 * \warning Works on all the frames at a time
558 void PixelConvert::ConvertRGBPlanesToRGBPixels( uint8_t* destination )
560 uint8_t* oldPixelZone = new uint8_t[ DecompressedSize ];
561 memmove( oldPixelZone, destination, DecompressedSize );
563 int l = XSize * YSize * ZSize;
565 uint8_t* a = oldPixelZone;
566 uint8_t* b = oldPixelZone + l;
567 uint8_t* c = oldPixelZone + l + l;
569 for (int j = 0; j < l; j++)
571 *(destination++) = *(a++);
572 *(destination++) = *(b++);
573 *(destination++) = *(c++);
575 delete[] oldPixelZone;
578 bool PixelConvert::ReadAndDecompressPixelData( void* destination, FILE* fp )
580 //////////////////////////////////////////////////
581 //// First stage: get our hands on the Pixel Data.
584 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
585 "unavailable file pointer." );
589 if ( fseek(fp, PixelOffset, SEEK_SET) == -1 )
591 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
592 "unable to find PixelOffset in file." );
596 //////////////////////////////////////////////////
597 //// Second stage: read from disk dans uncompress.
598 if ( BitsAllocated == 12 )
600 ReadAndDecompress12BitsTo16Bits( (uint8_t*)destination, fp);
602 else if ( IsUncompressed )
604 size_t ItemRead = fread( destination, PixelDataLength, 1, fp);
607 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
608 "reading of uncompressed pixel data failed." );
612 else if ( IsRLELossless )
614 if ( ! ReadAndDecompressRLEFile( destination, fp ) )
616 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
617 "RLE decompressor failed." );
623 // Default case concerns JPEG family
624 if ( ! ReadAndDecompressJPEGFile( (uint8_t*)destination, fp ) )
626 dbg.Verbose( 0, "PixelConvert::ReadAndDecompressPixelData: "
627 "JPEG decompressor failed." );
632 ////////////////////////////////////////////
633 //// Third stage: twigle the bytes and bits.
634 ReorderEndianity( (uint8_t*) destination );
635 ReArrangeBits( (uint8_t*) destination );
640 bool PixelConvert::HandleColor( uint8_t* destination )
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.
681 || ( PlanarConfiguration == 2 )
684 // [Planar 2] OR [Photo D]: LUT intervention done outside
688 if ( PlanarConfiguration == 1 )
692 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
693 ConvertYcBcRPlanesToRGBPixels( (uint8_t*)destination );
697 // [Planar 1] AND [Photo C]
698 ConvertRGBPlanesToRGBPixels( (uint8_t*)destination );
702 // When planarConf is 0, pixels are allready in RGB
706 void PixelConvert::ComputeDecompressedImageDataSize()
709 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
710 // in this case we will expand the image to 16 bits (see
711 // \ref ReadAndDecompress12BitsTo16Bits() )
712 if ( BitsAllocated == 12 )
717 DecompressedSize = XSize * YSize * ZSize
718 * ( bitsAllocated / 8 )
722 } // end namespace gdcm
724 // NOTES on File internal calls
727 // ---> GetImageDataIntoVector
728 // |---> GetImageDataIntoVectorRaw
729 // | lut intervention
731 // ---> GetImageDataRaw
732 // ---> GetImageDataIntoVectorRaw