1 /*=========================================================================
\r
4 Module: $RCSfile: gdcmPixelReadConvert.cxx,v $
\r
6 Date: $Date: 2004/12/13 06:25:39 $
\r
7 Version: $Revision: 1.8 $
\r
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
\r
10 l'Image). All rights reserved. See Doc/License.txt or
\r
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
\r
13 This software is distributed WITHOUT ANY WARRANTY; without even
\r
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
\r
15 PURPOSE. See the above copyright notices for more information.
\r
17 =========================================================================*/
\r
19 ////////////////// TEMPORARY NOTE
\r
20 // look for "fixMem" and convert that to a member of this class
\r
21 // Removing the prefix fixMem and dealing with allocations should do the trick
\r
23 // grep PixelReadConvert everywhere and clean up !
\r
25 #include "gdcmDebug.h"
\r
26 #include "gdcmHeader.h"
\r
27 #include "gdcmPixelReadConvert.h"
\r
28 #include "gdcmDocEntry.h"
\r
29 #include "gdcmRLEFramesInfo.h"
\r
30 #include "gdcmJPEGFragmentsInfo.h"
\r
33 #include <stdio.h> //for sscanf
\r
37 #define str2num(str, typeNum) *((typeNum *)(str))
\r
39 // For JPEG 2000, body in file gdcmJpeg2000.cxx
\r
40 bool gdcm_read_JPEG2000_file (std::ifstream* fp, void* image_buffer);
\r
42 #define JOCTET uint8_t
\r
43 // For JPEG 8 Bits, body in file gdcmJpeg8.cxx
\r
44 bool gdcm_read_JPEG_file8 (std::ifstream* fp, void* image_buffer);
\r
45 bool gdcm_read_JPEG_memory8 (const JOCTET* buffer, const size_t buflen,
\r
47 size_t *howManyRead, size_t *howManyWritten);
\r
49 // For JPEG 12 Bits, body in file gdcmJpeg12.cxx
\r
50 bool gdcm_read_JPEG_file12 (std::ifstream* fp, void* image_buffer);
\r
51 bool gdcm_read_JPEG_memory12 (const JOCTET *buffer, const size_t buflen,
\r
53 size_t *howManyRead, size_t *howManyWritten);
\r
55 // For JPEG 16 Bits, body in file gdcmJpeg16.cxx
\r
56 // Beware this is misleading there is no 16bits DCT algorithm, only
\r
57 // jpeg lossless compression exist in 16bits.
\r
58 bool gdcm_read_JPEG_file16 (std::ifstream* fp, void* image_buffer);
\r
59 bool gdcm_read_JPEG_memory16 (const JOCTET *buffer, const size_t buflen,
\r
61 size_t *howManyRead, size_t *howManyWritten);
\r
64 //-----------------------------------------------------------------------------
\r
65 // Constructor / Destructor
\r
66 PixelReadConvert::PixelReadConvert()
\r
78 void PixelReadConvert::Squeeze()
\r
99 PixelReadConvert::~PixelReadConvert()
\r
104 void PixelReadConvert::AllocateRGB()
\r
109 RGB = new uint8_t[ RGBSize ];
\r
112 void PixelReadConvert::AllocateRaw()
\r
117 Raw = new uint8_t[ RawSize ];
\r
121 * \brief Read from file a 12 bits per pixel image and decompress it
\r
122 * into a 16 bits per pixel image.
\r
124 void PixelReadConvert::ReadAndDecompress12BitsTo16Bits( std::ifstream* fp )
\r
125 throw ( FormatError )
\r
127 int nbPixels = XSize * YSize;
\r
128 uint16_t* localDecompres = (uint16_t*)Raw;
\r
130 for( int p = 0; p < nbPixels; p += 2 )
\r
132 uint8_t b0, b1, b2;
\r
134 fp->read( (char*)&b0, 1);
\r
135 if ( fp->fail() || fp->eof() )//Fp->gcount() == 1
\r
137 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
\r
138 "Unfound first block" );
\r
141 fp->read( (char*)&b1, 1 );
\r
142 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
\r
144 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
\r
145 "Unfound second block" );
\r
148 fp->read( (char*)&b2, 1 );
\r
149 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
\r
151 throw FormatError( "PixelReadConvert::ReadAndDecompress12BitsTo16Bits()",
\r
152 "Unfound second block" );
\r
155 // Two steps are necessary to please VC++
\r
157 // 2 pixels 12bit = [0xABCDEF]
\r
158 // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
\r
160 *localDecompres++ = ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
\r
162 *localDecompres++ = ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
\r
164 /// \todo JPR Troubles expected on Big-Endian processors ?
\r
169 * \brief Try to deal with RLE 16 Bits.
\r
170 * We assume the RLE has allready been parsed and loaded in
\r
171 * Raw (through \ref ReadAndDecompressJPEGFile ).
\r
172 * We here need to make 16 Bits Pixels from Low Byte and
\r
173 * High Byte 'Planes'...(for what it may mean)
\r
176 bool PixelReadConvert::DecompressRLE16BitsFromRLE8Bits( int NumberOfFrames )
\r
178 size_t PixelNumber = XSize * YSize;
\r
179 size_t RawSize = XSize * YSize * NumberOfFrames;
\r
181 // We assumed Raw contains the decoded RLE pixels but as
\r
182 // 8 bits per pixel. In order to convert those pixels to 16 bits
\r
183 // per pixel we cannot work in place within Raw and hence
\r
184 // we copy it in a safe place, say copyRaw.
\r
186 uint8_t* copyRaw = new uint8_t[ RawSize * 2 ];
\r
187 memmove( copyRaw, Raw, RawSize * 2 );
\r
190 uint8_t* a = copyRaw;
\r
191 uint8_t* b = a + PixelNumber;
\r
193 for ( int i = 0; i < NumberOfFrames; i++ )
\r
195 for ( unsigned int j = 0; j < PixelNumber; j++ )
\r
204 /// \todo check that operator new []didn't fail, and sometimes return false
\r
209 * \brief Implementation of the RLE decoding algorithm for decompressing
\r
210 * a RLE fragment. [refer to PS 3.5-2003, section G.3.2 p 86]
\r
211 * @param subRaw Sub region of \ref Raw where the de
\r
212 * decoded fragment should be placed.
\r
213 * @param fragmentSize The length of the binary fragment as found on the disk.
\r
214 * @param RawSegmentSize The expected length of the fragment ONCE
\r
216 * @param fp File Pointer: on entry the position should be the one of
\r
217 * the fragment to be decoded.
\r
219 bool PixelReadConvert::ReadAndDecompressRLEFragment( uint8_t* subRaw,
\r
221 long RawSegmentSize,
\r
222 std::ifstream* fp )
\r
225 long numberOfOutputBytes = 0;
\r
226 long numberOfReadBytes = 0;
\r
228 while( numberOfOutputBytes < RawSegmentSize )
\r
230 fp->read( (char*)&count, 1 );
\r
231 numberOfReadBytes += 1;
\r
233 // Note: count <= 127 comparison is always true due to limited range
\r
234 // of data type int8_t [since the maximum of an exact width
\r
235 // signed integer of width N is 2^(N-1) - 1, which for int8_t
\r
238 fp->read( (char*)subRaw, count + 1);
\r
239 numberOfReadBytes += count + 1;
\r
240 subRaw += count + 1;
\r
241 numberOfOutputBytes += count + 1;
\r
245 if ( ( count <= -1 ) && ( count >= -127 ) )
\r
248 fp->read( (char*)&newByte, 1);
\r
249 numberOfReadBytes += 1;
\r
250 for( int i = 0; i < -count + 1; i++ )
\r
252 subRaw[i] = newByte;
\r
254 subRaw += -count + 1;
\r
255 numberOfOutputBytes += -count + 1;
\r
258 // if count = 128 output nothing
\r
260 if ( numberOfReadBytes > fragmentSize )
\r
262 dbg.Verbose(0, "PixelReadConvert::ReadAndDecompressRLEFragment: we "
\r
263 "read more bytes than the segment size.");
\r
271 * \brief Reads from disk the Pixel Data of 'Run Length Encoded'
\r
272 * Dicom encapsulated file and decompress it.
\r
273 * @param fp already open File Pointer
\r
274 * at which the pixel data should be copied
\r
277 bool PixelReadConvert::ReadAndDecompressRLEFile( std::ifstream* fp )
\r
279 uint8_t* subRaw = Raw;
\r
280 long RawSegmentSize = XSize * YSize;
\r
282 // Loop on the frame[s]
\r
283 for( RLEFramesInfo::RLEFrameList::iterator
\r
284 it = RLEInfo->Frames.begin();
\r
285 it != RLEInfo->Frames.end();
\r
288 // Loop on the fragments
\r
289 for( unsigned int k = 1; k <= (*it)->NumberFragments; k++ )
\r
291 fp->seekg( (*it)->Offset[k] , std::ios::beg );
\r
292 (void)ReadAndDecompressRLEFragment( subRaw,
\r
296 subRaw += RawSegmentSize;
\r
300 if ( BitsAllocated == 16 )
\r
302 // Try to deal with RLE 16 Bits
\r
303 (void)DecompressRLE16BitsFromRLE8Bits( ZSize );
\r
310 * \brief Swap the bytes, according to \ref SwapCode.
\r
312 void PixelReadConvert::ConvertSwapZone()
\r
316 if( BitsAllocated == 16 )
\r
318 uint16_t* im16 = (uint16_t*)Raw;
\r
329 for( i = 0; i < RawSize / 2; i++ )
\r
331 im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
\r
335 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
\r
336 "(16 bits) not allowed." );
\r
339 else if( BitsAllocated == 32 )
\r
344 uint32_t* im32 = (uint32_t*)Raw;
\r
345 switch ( SwapCode )
\r
351 for( i = 0; i < RawSize / 4; i++ )
\r
353 low = im32[i] & 0x0000ffff; // 4321
\r
354 high = im32[i] >> 16;
\r
355 high = ( high >> 8 ) | ( high << 8 );
\r
356 low = ( low >> 8 ) | ( low << 8 );
\r
358 im32[i] = ( s32 << 16 ) | high;
\r
362 for( i = 0; i < RawSize / 4; i++ )
\r
364 low = im32[i] & 0x0000ffff; // 2143
\r
365 high = im32[i] >> 16;
\r
366 high = ( high >> 8 ) | ( high << 8 );
\r
367 low = ( low >> 8 ) | ( low << 8 );
\r
369 im32[i] = ( s32 << 16 ) | low;
\r
373 for( i = 0; i < RawSize / 4; i++ )
\r
375 low = im32[i] & 0x0000ffff; // 3412
\r
376 high = im32[i] >> 16;
\r
378 im32[i] = ( s32 << 16 ) | high;
\r
382 dbg.Verbose( 0, "PixelReadConvert::ConvertSwapZone: SwapCode value "
\r
383 "(32 bits) not allowed." );
\r
389 * \brief Deal with endianity i.e. re-arange bytes inside the integer
\r
391 void PixelReadConvert::ConvertReorderEndianity()
\r
393 if ( BitsAllocated != 8 )
\r
398 // Special kludge in order to deal with xmedcon broken images:
\r
399 if ( ( BitsAllocated == 16 )
\r
400 && ( BitsStored < BitsAllocated )
\r
401 && ( ! PixelSign ) )
\r
403 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
\r
404 uint16_t *deb = (uint16_t *)Raw;
\r
405 for(int i = 0; i<l; i++)
\r
407 if( *deb == 0xffff )
\r
418 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
\r
419 * file and decompress it. This funciton assumes that each
\r
420 * jpeg fragment contains a whole frame (jpeg file).
\r
421 * @param fp File Pointer
\r
424 bool PixelReadConvert::ReadAndDecompressJPEGFramesFromFile( std::ifstream* fp )
\r
426 uint8_t* localRaw = Raw;
\r
427 // Loop on the fragment[s]
\r
428 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
\r
429 it = JPEGInfo->Fragments.begin();
\r
430 it != JPEGInfo->Fragments.end();
\r
433 fp->seekg( (*it)->Offset, std::ios::beg);
\r
435 if ( BitsStored == 8)
\r
437 // JPEG Lossy : call to IJG 6b
\r
438 if ( ! gdcm_read_JPEG_file8( fp, localRaw ) )
\r
443 else if ( BitsStored <= 12)
\r
445 // Reading Fragment pixels
\r
446 if ( ! gdcm_read_JPEG_file12 ( fp, localRaw ) )
\r
451 else if ( BitsStored <= 16)
\r
453 // Reading Fragment pixels
\r
454 if ( ! gdcm_read_JPEG_file16 ( fp, localRaw ) )
\r
458 //assert( IsJPEGLossless );
\r
462 // other JPEG lossy not supported
\r
463 dbg.Error("PixelReadConvert::ReadAndDecompressJPEGFile: unknown "
\r
464 "jpeg lossy compression ");
\r
468 // Advance to next free location in Raw
\r
469 // for next fragment decompression (if any)
\r
470 int length = XSize * YSize * SamplesPerPixel;
\r
471 int numberBytes = BitsAllocated / 8;
\r
473 localRaw += length * numberBytes;
\r
479 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
\r
480 * file and decompress it. This function assumes that the dicom
\r
481 * image is a single frame split into several JPEG fragments.
\r
482 * Those fragments will be glued together into a memory buffer
\r
483 * before being read.
\r
484 * @param fp File Pointer
\r
487 bool PixelReadConvert::
\r
488 ReadAndDecompressJPEGSingleFrameFragmentsFromFile( std::ifstream* fp )
\r
490 // Loop on the fragment[s] to get total length
\r
491 size_t totalLength = 0;
\r
492 JPEGFragmentsInfo::JPEGFragmentsList::iterator it;
\r
493 for( it = JPEGInfo->Fragments.begin();
\r
494 it != JPEGInfo->Fragments.end();
\r
497 totalLength += (*it)->Length;
\r
500 // Concatenate the jpeg fragments into a local buffer
\r
501 JOCTET *buffer = new JOCTET [totalLength];
\r
502 JOCTET *p = buffer;
\r
504 uint8_t* localRaw = Raw;
\r
505 // Loop on the fragment[s]
\r
506 for( it = JPEGInfo->Fragments.begin();
\r
507 it != JPEGInfo->Fragments.end();
\r
510 fp->seekg( (*it)->Offset, std::ios::beg);
\r
511 size_t len = (*it)->Length;
\r
512 fp->read((char *)p,len);
\r
516 size_t howManyRead = 0;
\r
517 size_t howManyWritten = 0;
\r
518 size_t fragmentLength = 0;
\r
520 if ( BitsStored == 8)
\r
522 if ( ! gdcm_read_JPEG_memory8( buffer, totalLength, Raw,
\r
523 &howManyRead, &howManyWritten ) )
\r
526 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 "
\r
532 else if ( BitsStored <= 12)
\r
534 if ( ! gdcm_read_JPEG_memory12( buffer, totalLength, Raw,
\r
535 &howManyRead, &howManyWritten ) )
\r
538 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 "
\r
544 else if ( BitsStored <= 16)
\r
547 if ( ! gdcm_read_JPEG_memory16( buffer, totalLength, Raw,
\r
548 &howManyRead, &howManyWritten ) )
\r
551 "PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 "
\r
559 // other JPEG lossy not supported
\r
560 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
\r
561 "jpeg lossy compression ");
\r
566 // free local buffer
\r
573 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
\r
574 * file and decompress it. This function handles the generic
\r
575 * and complex case where the DICOM contains several frames,
\r
576 * and some of the frames are possibly split into several JPEG
\r
578 * @param fp File Pointer
\r
581 bool PixelReadConvert::
\r
582 ReadAndDecompressJPEGFragmentedFramesFromFile( std::ifstream* fp )
\r
584 // Loop on the fragment[s] to get total length
\r
585 size_t totalLength = 0;
\r
586 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
\r
587 it = JPEGInfo->Fragments.begin();
\r
588 it != JPEGInfo->Fragments.end();
\r
591 totalLength += (*it)->Length;
\r
594 // Concatenate the jpeg fragments into a local buffer
\r
595 JOCTET *buffer = new JOCTET [totalLength];
\r
596 JOCTET *p = buffer;
\r
598 uint8_t* localRaw = Raw;
\r
599 // Loop on the fragment[s]
\r
600 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
\r
601 it = JPEGInfo->Fragments.begin();
\r
602 it != JPEGInfo->Fragments.end();
\r
605 fp->seekg( (*it)->Offset, std::ios::beg);
\r
606 size_t len = (*it)->Length;
\r
607 fp->read((char *)p,len);
\r
611 size_t howManyRead = 0;
\r
612 size_t howManyWritten = 0;
\r
613 size_t fragmentLength = 0;
\r
615 for( JPEGFragmentsInfo::JPEGFragmentsList::iterator
\r
616 it = JPEGInfo->Fragments.begin() ;
\r
617 (it != JPEGInfo->Fragments.end()) && (howManyRead < totalLength);
\r
620 fragmentLength += (*it)->Length;
\r
622 if (howManyRead > fragmentLength) continue;
\r
624 if ( BitsStored == 8)
\r
626 if ( ! gdcm_read_JPEG_memory8( buffer+howManyRead, totalLength-howManyRead,
\r
627 Raw+howManyWritten,
\r
628 &howManyRead, &howManyWritten ) )
\r
630 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg8 ");
\r
635 else if ( BitsStored <= 12)
\r
638 if ( ! gdcm_read_JPEG_memory12( buffer+howManyRead, totalLength-howManyRead,
\r
639 Raw+howManyWritten,
\r
640 &howManyRead, &howManyWritten ) )
\r
642 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg12 ");
\r
647 else if ( BitsStored <= 16)
\r
650 if ( ! gdcm_read_JPEG_memory16( buffer+howManyRead, totalLength-howManyRead,
\r
651 Raw+howManyWritten,
\r
652 &howManyRead, &howManyWritten ) )
\r
654 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: failed to read jpeg16 ");
\r
661 // other JPEG lossy not supported
\r
662 dbg.Error("PixelConvert::ReadAndDecompressJPEGFile: unknown "
\r
663 "jpeg lossy compression ");
\r
668 if (howManyRead < fragmentLength)
\r
669 howManyRead = fragmentLength;
\r
672 // free local buffer
\r
679 * \brief Reads from disk the Pixel Data of JPEG Dicom encapsulated
\r
680 * file and decompress it.
\r
681 * @param fp File Pointer
\r
684 bool PixelReadConvert::ReadAndDecompressJPEGFile( std::ifstream* fp )
\r
688 fp->seekg( (*JPEGInfo->Fragments.begin())->Offset, std::ios::beg);
\r
689 if ( ! gdcm_read_JPEG2000_file( fp,Raw ) )
\r
693 if ( ( ZSize == 1 ) && ( JPEGInfo->Fragments.size() > 1 ) )
\r
695 // we have one frame split into several fragments
\r
696 // we will pack those fragments into a single buffer and
\r
698 return ReadAndDecompressJPEGSingleFrameFragmentsFromFile( fp );
\r
700 else if (JPEGInfo->Fragments.size() == ZSize)
\r
702 // suppose each fragment is a frame
\r
703 return ReadAndDecompressJPEGFramesFromFile( fp );
\r
707 // The dicom image contains frames containing fragments of images
\r
708 // a more complex algorithm :-)
\r
709 return ReadAndDecompressJPEGFragmentedFramesFromFile( fp );
\r
714 * \brief Re-arrange the bits within the bytes.
\r
717 bool PixelReadConvert::ConvertReArrangeBits() throw ( FormatError )
\r
719 if ( BitsStored != BitsAllocated )
\r
721 int l = (int)( RawSize / ( BitsAllocated / 8 ) );
\r
722 if ( BitsAllocated == 16 )
\r
724 uint16_t mask = 0xffff;
\r
725 mask = mask >> ( BitsAllocated - BitsStored );
\r
726 uint16_t* deb = (uint16_t*)Raw;
\r
727 for(int i = 0; i<l; i++)
\r
729 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
\r
733 else if ( BitsAllocated == 32 )
\r
735 uint32_t mask = 0xffffffff;
\r
736 mask = mask >> ( BitsAllocated - BitsStored );
\r
737 uint32_t* deb = (uint32_t*)Raw;
\r
738 for(int i = 0; i<l; i++)
\r
740 *deb = (*deb >> (BitsStored - HighBitPosition - 1)) & mask;
\r
746 dbg.Verbose(0, "PixelReadConvert::ConvertReArrangeBits: weird image");
\r
747 throw FormatError( "PixelReadConvert::ConvertReArrangeBits()",
\r
748 "weird image !?" );
\r
755 * \brief Convert (Y plane, cB plane, cR plane) to RGB pixels
\r
756 * \warning Works on all the frames at a time
\r
758 void PixelReadConvert::ConvertYcBcRPlanesToRGBPixels()
\r
760 uint8_t* localRaw = Raw;
\r
761 uint8_t* copyRaw = new uint8_t[ RawSize ];
\r
762 memmove( copyRaw, localRaw, RawSize );
\r
764 // to see the tricks about YBR_FULL, YBR_FULL_422,
\r
765 // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
\r
766 // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
\r
767 // and be *very* affraid
\r
769 int l = XSize * YSize;
\r
770 int nbFrames = ZSize;
\r
772 uint8_t* a = copyRaw;
\r
773 uint8_t* b = copyRaw + l;
\r
774 uint8_t* c = copyRaw + l + l;
\r
777 /// \todo : Replace by the 'well known' integer computation
\r
778 /// counterpart. Refer to
\r
779 /// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
\r
780 /// for code optimisation.
\r
782 for ( int i = 0; i < nbFrames; i++ )
\r
784 for ( int j = 0; j < l; j++ )
\r
786 R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
\r
787 G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
\r
788 B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
\r
790 if (R < 0.0) R = 0.0;
\r
791 if (G < 0.0) G = 0.0;
\r
792 if (B < 0.0) B = 0.0;
\r
793 if (R > 255.0) R = 255.0;
\r
794 if (G > 255.0) G = 255.0;
\r
795 if (B > 255.0) B = 255.0;
\r
797 *(localRaw++) = (uint8_t)R;
\r
798 *(localRaw++) = (uint8_t)G;
\r
799 *(localRaw++) = (uint8_t)B;
\r
809 * \brief Convert (Red plane, Green plane, Blue plane) to RGB pixels
\r
810 * \warning Works on all the frames at a time
\r
812 void PixelReadConvert::ConvertRGBPlanesToRGBPixels()
\r
814 uint8_t* localRaw = Raw;
\r
815 uint8_t* copyRaw = new uint8_t[ RawSize ];
\r
816 memmove( copyRaw, localRaw, RawSize );
\r
818 int l = XSize * YSize * ZSize;
\r
820 uint8_t* a = copyRaw;
\r
821 uint8_t* b = copyRaw + l;
\r
822 uint8_t* c = copyRaw + l + l;
\r
824 for (int j = 0; j < l; j++)
\r
826 *(localRaw++) = *(a++);
\r
827 *(localRaw++) = *(b++);
\r
828 *(localRaw++) = *(c++);
\r
833 bool PixelReadConvert::ReadAndDecompressPixelData( std::ifstream* fp )
\r
835 // ComputeRawAndRGBSizes is already made by
\r
836 // ::GrabInformationsFromHeader. So, the structure sizes are
\r
840 //////////////////////////////////////////////////
\r
841 //// First stage: get our hands on the Pixel Data.
\r
844 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
\r
845 "unavailable file pointer." );
\r
849 fp->seekg( PixelOffset, std::ios::beg );
\r
850 if( fp->fail() || fp->eof()) //Fp->gcount() == 1
\r
852 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
\r
853 "unable to find PixelOffset in file." );
\r
859 //////////////////////////////////////////////////
\r
860 //// Second stage: read from disk dans decompress.
\r
861 if ( BitsAllocated == 12 )
\r
863 ReadAndDecompress12BitsTo16Bits( fp);
\r
867 // This problem can be found when some obvious informations are found
\r
868 // after the field containing the image datas. In this case, these
\r
869 // bad datas are added to the size of the image (in the PixelDataLength
\r
870 // variable). But RawSize is the right size of the image !
\r
871 if( PixelDataLength != RawSize)
\r
873 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
\r
874 "Mismatch between PixelReadConvert and RawSize." );
\r
876 if( PixelDataLength > RawSize)
\r
878 fp->read( (char*)Raw, RawSize);
\r
882 fp->read( (char*)Raw, PixelDataLength);
\r
885 if ( fp->fail() || fp->eof())//Fp->gcount() == 1
\r
887 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
\r
888 "reading of Raw pixel data failed." );
\r
892 else if ( IsRLELossless )
\r
894 if ( ! ReadAndDecompressRLEFile( fp ) )
\r
896 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
\r
897 "RLE decompressor failed." );
\r
903 // Default case concerns JPEG family
\r
904 if ( ! ReadAndDecompressJPEGFile( fp ) )
\r
906 dbg.Verbose( 0, "PixelReadConvert::ReadAndDecompressPixelData: "
\r
907 "JPEG decompressor failed." );
\r
912 ////////////////////////////////////////////
\r
913 //// Third stage: twigle the bytes and bits.
\r
914 ConvertReorderEndianity();
\r
915 ConvertReArrangeBits();
\r
916 ConvertHandleColor();
\r
921 void PixelReadConvert::ConvertHandleColor()
\r
923 //////////////////////////////////
\r
924 // Deal with the color decoding i.e. handle:
\r
925 // - R, G, B planes (as opposed to RGB pixels)
\r
926 // - YBR (various) encodings.
\r
927 // - LUT[s] (or "PALETTE COLOR").
\r
929 // The classification in the color decoding schema is based on the blending
\r
930 // of two Dicom tags values:
\r
931 // * "Photometric Interpretation" for which we have the cases:
\r
932 // - [Photo A] MONOCHROME[1|2] pictures,
\r
933 // - [Photo B] RGB or YBR_FULL_422 (which acts as RGB),
\r
934 // - [Photo C] YBR_* (with the above exception of YBR_FULL_422)
\r
935 // - [Photo D] "PALETTE COLOR" which indicates the presence of LUT[s].
\r
936 // * "Planar Configuration" for which we have the cases:
\r
937 // - [Planar 0] 0 then Pixels are already RGB
\r
938 // - [Planar 1] 1 then we have 3 planes : R, G, B,
\r
939 // - [Planar 2] 2 then we have 1 gray Plane and 3 LUTs
\r
941 // Now in theory, one could expect some coherence when blending the above
\r
942 // cases. For example we should not encounter files belonging at the
\r
943 // time to case [Planar 0] and case [Photo D].
\r
944 // Alas, this was only theory ! Because in practice some odd (read ill
\r
945 // formated Dicom) files (e.g. gdcmData/US-PAL-8-10x-echo.dcm) we encounter:
\r
946 // - "Planar Configuration" = 0,
\r
947 // - "Photometric Interpretation" = "PALETTE COLOR".
\r
948 // Hence gdcm shall use the folowing "heuristic" in order to be tolerant
\r
949 // towards Dicom-non-conformance files:
\r
950 // << whatever the "Planar Configuration" value might be, a
\r
951 // "Photometric Interpretation" set to "PALETTE COLOR" forces
\r
952 // a LUT intervention >>
\r
954 // Now we are left with the following handling of the cases:
\r
955 // - [Planar 0] OR [Photo A] no color decoding (since respectively
\r
956 // Pixels are already RGB and monochrome pictures have no color :),
\r
957 // - [Planar 1] AND [Photo B] handled with ConvertRGBPlanesToRGBPixels()
\r
958 // - [Planar 1] AND [Photo C] handled with ConvertYcBcRPlanesToRGBPixels()
\r
959 // - [Planar 2] OR [Photo D] requires LUT intervention.
\r
961 if ( ! IsRawRGB() )
\r
963 // [Planar 2] OR [Photo D]: LUT intervention done outside
\r
967 if ( PlanarConfiguration == 1 )
\r
971 // [Planar 1] AND [Photo C] (remember YBR_FULL_422 acts as RGB)
\r
972 ConvertYcBcRPlanesToRGBPixels();
\r
976 // [Planar 1] AND [Photo C]
\r
977 ConvertRGBPlanesToRGBPixels();
\r
982 // When planarConf is 0, and RLELossless (forbidden by Dicom norm)
\r
983 // pixels need to be RGB-fied anyway
\r
986 ConvertRGBPlanesToRGBPixels();
\r
988 // In *normal *case, when planarConf is 0, pixels are already in RGB
\r
992 * \brief Predicate to know wether the image[s] (once Raw) is RGB.
\r
993 * \note See comments of \ref ConvertHandleColor
\r
995 bool PixelReadConvert::IsRawRGB()
\r
998 || PlanarConfiguration == 2
\r
999 || IsPaletteColor )
\r
1006 void PixelReadConvert::ComputeRawAndRGBSizes()
\r
1008 int bitsAllocated = BitsAllocated;
\r
1009 // Number of "Bits Allocated" is fixed to 16 when it's 12, since
\r
1010 // in this case we will expand the image to 16 bits (see
\r
1011 // \ref ReadAndDecompress12BitsTo16Bits() )
\r
1012 if ( BitsAllocated == 12 )
\r
1014 bitsAllocated = 16;
\r
1017 RawSize = XSize * YSize * ZSize
\r
1018 * ( bitsAllocated / 8 )
\r
1019 * SamplesPerPixel;
\r
1022 RGBSize = 3 * RawSize;
\r
1026 RGBSize = RawSize;
\r
1030 void PixelReadConvert::GrabInformationsFromHeader( Header* header )
\r
1032 // Number of Bits Allocated for storing a Pixel is defaulted to 16
\r
1033 // when absent from the header.
\r
1034 BitsAllocated = header->GetBitsAllocated();
\r
1035 if ( BitsAllocated == 0 )
\r
1037 BitsAllocated = 16;
\r
1040 // Number of "Bits Stored" defaulted to number of "Bits Allocated"
\r
1041 // when absent from the header.
\r
1042 BitsStored = header->GetBitsStored();
\r
1043 if ( BitsStored == 0 )
\r
1045 BitsStored = BitsAllocated;
\r
1048 // High Bit Position
\r
1049 HighBitPosition = header->GetHighBitPosition();
\r
1050 if ( HighBitPosition == 0 )
\r
1052 HighBitPosition = BitsAllocated - 1;
\r
1055 XSize = header->GetXSize();
\r
1056 YSize = header->GetYSize();
\r
1057 ZSize = header->GetZSize();
\r
1058 SamplesPerPixel = header->GetSamplesPerPixel();
\r
1059 PixelSize = header->GetPixelSize();
\r
1060 PixelSign = header->IsSignedPixelData();
\r
1061 SwapCode = header->GetSwapCode();
\r
1062 TransferSyntaxType ts = header->GetTransferSyntax();
\r
1064 ( ! header->IsDicomV3() )
\r
1065 || ts == ImplicitVRLittleEndian
\r
1066 || ts == ImplicitVRLittleEndianDLXGE
\r
1067 || ts == ExplicitVRLittleEndian
\r
1068 || ts == ExplicitVRBigEndian
\r
1069 || ts == DeflatedExplicitVRLittleEndian;
\r
1070 IsJPEG2000 = header->IsJPEG2000();
\r
1071 IsJPEGLossless = header->IsJPEGLossless();
\r
1072 IsRLELossless = ( ts == RLELossless );
\r
1073 PixelOffset = header->GetPixelOffset();
\r
1074 PixelDataLength = header->GetPixelAreaLength();
\r
1075 RLEInfo = header->GetRLEInfo();
\r
1076 JPEGInfo = header->GetJPEGInfo();
\r
1078 PlanarConfiguration = header->GetPlanarConfiguration();
\r
1079 IsMonochrome = header->IsMonochrome();
\r
1080 IsPaletteColor = header->IsPaletteColor();
\r
1081 IsYBRFull = header->IsYBRFull();
\r
1083 /////////////////////////////////////////////////////////////////
\r
1085 HasLUT = header->HasLUT();
\r
1088 // Just in case some access to a Header element requires disk access.
\r
1089 // Note: gdcmDocument::Fp is leaved open after OpenFile.
\r
1090 LutRedDescriptor = header->GetEntryByNumber( 0x0028, 0x1101 );
\r
1091 LutGreenDescriptor = header->GetEntryByNumber( 0x0028, 0x1102 );
\r
1092 LutBlueDescriptor = header->GetEntryByNumber( 0x0028, 0x1103 );
\r
1094 // Depending on the value of Document::MAX_SIZE_LOAD_ELEMENT_VALUE
\r
1095 // [ refer to invocation of Document::SetMaxSizeLoadEntry() in
\r
1096 // Document::Document() ], the loading of the value (content) of a
\r
1097 // [Bin|Val]Entry occurence migth have been hindered (read simply NOT
\r
1098 // loaded). Hence, we first try to obtain the LUTs data from the header
\r
1099 // and when this fails we read the LUTs data directely from disk.
\r
1100 /// \todo Reading a [Bin|Val]Entry directly from disk is a kludge.
\r
1101 /// We should NOT bypass the [Bin|Val]Entry class. Instead
\r
1102 /// an access to an UNLOADED content of a [Bin|Val]Entry occurence
\r
1103 /// (e.g. BinEntry::GetBinArea()) should force disk access from
\r
1104 /// within the [Bin|Val]Entry class itself. The only problem
\r
1105 /// is that the [Bin|Val]Entry is unaware of the FILE* is was
\r
1106 /// parsed from. Fix that. FIXME.
\r
1109 header->LoadEntryBinArea(0x0028, 0x1201);
\r
1110 LutRedData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1201 );
\r
1111 if ( ! LutRedData )
\r
1113 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
\r
1114 "unable to read red LUT data" );
\r
1117 ////// Green round:
\r
1118 header->LoadEntryBinArea(0x0028, 0x1202);
\r
1119 LutGreenData = (uint8_t*)header->GetEntryBinAreaByNumber(0x0028, 0x1202 );
\r
1120 if ( ! LutGreenData)
\r
1122 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
\r
1123 "unable to read green LUT data" );
\r
1126 ////// Blue round:
\r
1127 header->LoadEntryBinArea(0x0028, 0x1203);
\r
1128 LutBlueData = (uint8_t*)header->GetEntryBinAreaByNumber( 0x0028, 0x1203 );
\r
1129 if ( ! LutBlueData )
\r
1131 dbg.Verbose(0, "PixelReadConvert::GrabInformationsFromHeader: "
\r
1132 "unable to read blue LUT data" );
\r
1136 ComputeRawAndRGBSizes();
\r
1140 * \brief Build Red/Green/Blue/Alpha LUT from Header
\r
1141 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
\r
1142 * and (0028,1101),(0028,1102),(0028,1102)
\r
1143 * - xxx Palette Color Lookup Table Descriptor - are found
\r
1144 * and (0028,1201),(0028,1202),(0028,1202)
\r
1145 * - xxx Palette Color Lookup Table Data - are found
\r
1146 * \warning does NOT deal with :
\r
1147 * 0028 1100 Gray Lookup Table Descriptor (Retired)
\r
1148 * 0028 1221 Segmented Red Palette Color Lookup Table Data
\r
1149 * 0028 1222 Segmented Green Palette Color Lookup Table Data
\r
1150 * 0028 1223 Segmented Blue Palette Color Lookup Table Data
\r
1151 * no known Dicom reader deals with them :-(
\r
1152 * @return a RGBA Lookup Table
\r
1154 void PixelReadConvert::BuildLUTRGBA()
\r
1160 // Not so easy : see
\r
1161 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
\r
1163 if ( ! IsPaletteColor )
\r
1168 if ( LutRedDescriptor == GDCM_UNFOUND
\r
1169 || LutGreenDescriptor == GDCM_UNFOUND
\r
1170 || LutBlueDescriptor == GDCM_UNFOUND )
\r
1175 ////////////////////////////////////////////
\r
1176 // Extract the info from the LUT descriptors
\r
1177 int lengthR; // Red LUT length in Bytes
\r
1178 int debR; // Subscript of the first Lut Value
\r
1179 int nbitsR; // Lut item size (in Bits)
\r
1180 int nbRead = sscanf( LutRedDescriptor.c_str(),
\r
1182 &lengthR, &debR, &nbitsR );
\r
1185 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong red LUT descriptor");
\r
1188 int lengthG; // Green LUT length in Bytes
\r
1189 int debG; // Subscript of the first Lut Value
\r
1190 int nbitsG; // Lut item size (in Bits)
\r
1191 nbRead = sscanf( LutGreenDescriptor.c_str(),
\r
1193 &lengthG, &debG, &nbitsG );
\r
1196 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong green LUT descriptor");
\r
1199 int lengthB; // Blue LUT length in Bytes
\r
1200 int debB; // Subscript of the first Lut Value
\r
1201 int nbitsB; // Lut item size (in Bits)
\r
1202 nbRead = sscanf( LutRedDescriptor.c_str(),
\r
1204 &lengthB, &debB, &nbitsB );
\r
1207 dbg.Verbose(0, "PixelReadConvert::BuildLUTRGBA: wrong blue LUT descriptor");
\r
1210 ////////////////////////////////////////////////////////
\r
1211 if ( ( ! LutRedData ) || ( ! LutGreenData ) || ( ! LutBlueData ) )
\r
1216 ////////////////////////////////////////////////
\r
1217 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
\r
1218 LutRGBA = new uint8_t[ 1024 ]; // 256 * 4 (R, G, B, Alpha)
\r
1223 memset( LutRGBA, 0, 1024 );
\r
1226 if ( ( nbitsR == 16 ) && ( BitsAllocated == 8 ) )
\r
1228 // when LUT item size is different than pixel size
\r
1229 mult = 2; // high byte must be = low byte
\r
1233 // See PS 3.3-2003 C.11.1.1.2 p 619
\r
1237 // if we get a black image, let's just remove the '+1'
\r
1238 // from 'i*mult+1' and check again
\r
1239 // if it works, we shall have to check the 3 Palettes
\r
1240 // to see which byte is ==0 (first one, or second one)
\r
1241 // and fix the code
\r
1242 // We give up the checking to avoid some (useless ?)overhead
\r
1243 // (optimistic asumption)
\r
1245 uint8_t* a = LutRGBA + 0;
\r
1246 for( i=0; i < lengthR; ++i )
\r
1248 *a = LutRedData[i*mult+1];
\r
1253 for( i=0; i < lengthG; ++i)
\r
1255 *a = LutGreenData[i*mult+1];
\r
1260 for(i=0; i < lengthB; ++i)
\r
1262 *a = LutBlueData[i*mult+1];
\r
1267 for(i=0; i < 256; ++i)
\r
1269 *a = 1; // Alpha component
\r
1275 * \brief Build the RGB image from the Raw imagage and the LUTs.
\r
1277 bool PixelReadConvert::BuildRGBImage()
\r
1281 // The job is already done.
\r
1287 // The job can't be done
\r
1294 // The job can't be done
\r
1298 // Build RGB Pixels
\r
1300 uint8_t* localRGB = RGB;
\r
1301 for (size_t i = 0; i < RawSize; ++i )
\r
1303 int j = Raw[i] * 4;
\r
1304 *localRGB++ = LutRGBA[j];
\r
1305 *localRGB++ = LutRGBA[j+1];
\r
1306 *localRGB++ = LutRGBA[j+2];
\r
1312 * \brief Print self.
\r
1313 * @param indent Indentation string to be prepended during printing.
\r
1314 * @param os Stream to print to.
\r
1316 void PixelReadConvert::Print( std::string indent, std::ostream &os )
\r
1319 << "--- Pixel information -------------------------"
\r
1322 << "Pixel Data: offset " << PixelOffset
\r
1323 << " x" << std::hex << PixelOffset << std::dec
\r
1324 << " length " << PixelDataLength
\r
1325 << " x" << std::hex << PixelDataLength << std::dec
\r
1328 if ( IsRLELossless )
\r
1332 RLEInfo->Print( indent, os );
\r
1336 dbg.Verbose(0, "PixelReadConvert::Print: set as RLE file "
\r
1337 "but NO RLEinfo present.");
\r
1341 if ( IsJPEG2000 || IsJPEGLossless )
\r
1345 JPEGInfo->Print( indent, os );
\r
1349 dbg.Verbose(0, "PixelReadConvert::Print: set as JPEG file "
\r
1350 "but NO JPEGinfo present.");
\r
1355 } // end namespace gdcm
\r
1357 // NOTES on File internal calls
\r
1359 // ---> GetImageData
\r
1360 // ---> GetImageDataIntoVector
\r
1361 // |---> GetImageDataIntoVectorRaw
\r
1362 // | lut intervention
\r
1364 // ---> GetImageDataRaw
\r
1365 // ---> GetImageDataIntoVectorRaw
\r