1 /*=========================================================================
4 Module: $RCSfile: gdcmPixelConvert.cxx,v $
6 Date: $Date: 2004/10/12 09:59:45 $
7 Version: $Revision: 1.9 $
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::Decompress12BitsTo16Bits(
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::Decompress12BitsTo16Bits()",
111 "Unfound first block" );
114 ItemRead = fread( &b1, 1, 1, filePtr);
117 throw FormatError( "File::Decompress12BitsTo16Bits()",
118 "Unfound second block" );
121 ItemRead = fread( &b2, 1, 1, filePtr);
124 throw FormatError( "File::Decompress12BitsTo16Bits()",
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( unsigned 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 fp already open File Pointer
461 * @param destination Where decompressed fragments should end up
464 bool PixelConvert::ReArrangeBits( uint8_t* pixelZone )
465 throw ( FormatError )
467 if ( BitsStored != BitsAllocated )
469 int l = (int)( DecompressedSize / ( BitsAllocated / 8 ) );
470 if ( BitsAllocated == 16 )
472 uint16_t mask = 0xffff;
473 mask = mask >> ( BitsAllocated - BitsStored );
474 uint16_t* deb = (uint16_t*)pixelZone;
475 for(int i = 0; i<l; i++)
477 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
481 else if ( BitsAllocated == 32 )
483 uint32_t mask = 0xffffffff;
484 mask = mask >> ( BitsAllocated - BitsStored );
485 uint32_t* deb = (uint32_t*)pixelZone;
486 for(int i = 0; i<l; i++)
488 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
494 dbg.Verbose(0, "PixelConvert::ReArrangeBits: weird image");
495 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(
506 uint8_t* destination,
507 size_t imageDataSize )
509 uint8_t* oldPixelZone = new uint8_t[ imageDataSize ];
510 memmove( oldPixelZone, destination, imageDataSize );
512 // to see the tricks about YBR_FULL, YBR_FULL_422,
513 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
514 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
515 // and be *very* affraid
517 int l = XSize * YSize;
518 int nbFrames = ZSize;
520 uint8_t* a = oldPixelZone;
521 uint8_t* b = oldPixelZone + l;
522 uint8_t* c = oldPixelZone + l + l;
525 /// \todo : Replace by the 'well known' integer computation
526 /// counterpart. Refer to
527 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
528 /// for code optimisation.
530 for ( int i = 0; i < nbFrames; i++ )
532 for ( int j = 0; j < l; j++ )
534 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
535 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
536 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
538 if (R < 0.0) R = 0.0;
539 if (G < 0.0) G = 0.0;
540 if (B < 0.0) B = 0.0;
541 if (R > 255.0) R = 255.0;
542 if (G > 255.0) G = 255.0;
543 if (B > 255.0) B = 255.0;
545 *(destination++) = (uint8_t)R;
546 *(destination++) = (uint8_t)G;
547 *(destination++) = (uint8_t)B;
553 delete[] oldPixelZone;
557 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
558 * \warning Works on all the frames at a time
560 void PixelConvert::ConvertRGBPlanesToRGBPixels(
561 uint8_t* destination,
562 size_t imageDataSize )
564 uint8_t* oldPixelZone = new uint8_t[ imageDataSize ];
565 memmove( oldPixelZone, destination, imageDataSize );
567 int l = XSize * YSize * ZSize;
569 uint8_t* a = oldPixelZone;
570 uint8_t* b = oldPixelZone + l;
571 uint8_t* c = oldPixelZone + l + l;
573 for (int j = 0; j < l; j++)
575 *(destination++) = *(a++);
576 *(destination++) = *(b++);
577 *(destination++) = *(c++);
579 delete[] oldPixelZone;
582 bool PixelConvert::ReadAndDecompressPixelData( void* destination, FILE* fp )
589 if ( fseek(fp, PixelOffset, SEEK_SET) == -1 )
594 if ( BitsAllocated == 12 )
596 Decompress12BitsTo16Bits( (uint8_t*)destination, fp);
600 //////////// Decompressed File
601 if ( IsUncompressed )
603 size_t ItemRead = fread( destination, PixelDataLength, 1, fp);
614 ///////////// Run Length Encoding
617 return ReadAndDecompressRLEFile( destination, fp );
620 ///////////// SingleFrame/Multiframe JPEG Lossless/Lossy/2000
621 return ReadAndDecompressJPEGFile( (uint8_t*)destination, fp );
624 void PixelConvert::ComputeDecompressedImageDataSize()
627 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
628 // in this case we will expand the image to 16 bits (see
629 // \ref Decompress12BitsTo16Bits() )
630 if ( BitsAllocated == 12 )
635 DecompressedSize = XSize * YSize * ZSize
636 * ( bitsAllocated / 8 )
640 } // end namespace gdcm