]> Creatis software - gdcm.git/blobdiff - src/gdcmFile.cxx
* Update Windows projects and .cvsignore files
[gdcm.git] / src / gdcmFile.cxx
index ed51d6984503b8d15e0ef21f7e77c3abd586d808..69fba75867b02e30d7db4318657454647e97c8d6 100644 (file)
@@ -49,7 +49,6 @@ gdcmFile::gdcmFile(const char * filename)
 void gdcmFile::SetPixelDataSizeFromHeader(void) {
    int nb;
    std::string str_nb;
-
    str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
    if (str_nb == GDCM_UNFOUND ) {
       nb = 16;
@@ -57,14 +56,19 @@ void gdcmFile::SetPixelDataSizeFromHeader(void) {
       nb = atoi(str_nb.c_str() );
       if (nb == 12) nb =16;
    }
-   lgrTotale =  GetXSize() *  GetYSize() *  GetZSize() 
+   lgrTotale =  lgrTotaleRaw = GetXSize() *  GetYSize() *  GetZSize() 
               * (nb/8)* GetSamplesPerPixel();
    std::string str_PhotometricInterpretation = 
                              gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
-   if ( str_PhotometricInterpretation == "PALETTE COLOR " ) { 
+                            
+   /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
+   // pb when undealt Segmented Palette Color
+   
+    if (HasLUT()) { 
       lgrTotale*=3;
    }
 }
+
    // see PS 3.3-2003 : C.7.6.3.2.1  
    // 
    //   MONOCHROME1
@@ -86,17 +90,27 @@ void gdcmFile::SetPixelDataSizeFromHeader(void) {
   // 0028|1222 [OW]   [Segmented Green Palette Color Lookup Table Data]  
   // 0028|1223 [OW]   [Segmented Blue Palette Color Lookup Table Data]
 
-  // ex : US-PAL-8-10x-echo.dcm, 8BitsRunLengthColor.dcm
-  // 0028|1201 [OW]   [Red Palette Color Lookup Table Data]
-  // 0028|1202 [OW]   [Green Palette Color Lookup Table Data]
-  // 0028|1203 [OW]   [Blue Palette Color Lookup Table Data]
-
   // ex  : OT-PAL-8-face.dcm
   // 0028|1201 [US]   [Red Palette Color Lookup Table Data]
   // 0028|1202 [US]   [Green Palette Color Lookup Table Data]
   // 0028|1203 [US]   [Blue Palette Color Lookup Table Data]
 
 
+/////////////////////////////////////////////////////////////////
+/**
+ * \ingroup   gdcmFile
+ * \brief     Returns the size (in bytes) of required memory to hold
+ * \          the pixel data represented in this file, when user DOESN'T want 
+ * \          to get RGB pixels image when it's stored as a PALETTE COLOR image
+ * \          - the (vtk) user is supposed to know how deal with LUTs - 
+ * \          warning to be used with GetImagePixelsRaw()
+ * @return    The size of pixel data in bytes.
+ */
+
+size_t gdcmFile::GetImageDataSizeRaw(void) {
+   return (lgrTotaleRaw);
+}
+
 /////////////////////////////////////////////////////////////////
 /**
  * \ingroup   gdcmFile
@@ -127,8 +141,9 @@ bool gdcmFile::ReadPixelData(void* destination) {
       CloseFile();
       return false;
    }
+   
 
-// -------------------------  Compacted File (12 Bits Per Pixel)
+   // ----------------------  Compacted File (12 Bits Per Pixel)
 
    /* unpack 12 Bits pixels into 16 Bits pixels */
    /* 2 pixels 12bit =     [0xABCDEF]           */
@@ -138,32 +153,32 @@ bool gdcmFile::ReadPixelData(void* destination) {
       int nbPixels = GetXSize()*GetYSize();
       unsigned char b0, b1, b2;
       
+      unsigned short int* pdestination = (unsigned short int*)destination;    
       for(int p=0;p<nbPixels;p+=2) {
          fread(&b0,1,1,fp);
          fread(&b1,1,1,fp);
          fread(&b2,1,1,fp);      
-         *((unsigned short int*)destination)++ = 
-                   ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
+         //Two steps is necessary to please VC++
+         *pdestination++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
                        /* A */          /* B */            /* D */
-         *((unsigned short int*)destination)++ = 
-                   ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
+         *pdestination++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
                        /* F */          /* C */            /* E */
                  
        // Troubles expected on Big-Endian processors ?       
       }
       return(true);
-   }
-        
+   }        
 
-// -------------------------  Uncompressed File
+   // ----------------------  Uncompressed File
     
    if ( !IsDicomV3()                             ||
         IsImplicitVRLittleEndianTransferSyntax() ||
         IsExplicitVRLittleEndianTransferSyntax() ||
         IsExplicitVRBigEndianTransferSyntax()    ||
-        IsDeflatedExplicitVRLittleEndianTransferSyntax() ) { 
-                    
-      size_t ItemRead = fread(destination, lgrTotale, 1, fp);
+        IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
+
+      size_t ItemRead = fread(destination, GetPixelAreaLength(), 1, fp);
+      
       if ( ItemRead != 1 ) {
          CloseFile();
          return false;
@@ -173,17 +188,14 @@ bool gdcmFile::ReadPixelData(void* destination) {
       }
    } 
 
-   
-// ------------------------- Run Length Encoding
+   // ---------------------- Run Length Encoding
 
       if (gdcmHeader::IsRLELossLessTransferSyntax()) {
             int res = (bool)gdcm_read_RLE_file (destination);
             return res; 
       }  
-
     
-// ----------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
+   // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
        
       int nb;
       std::string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
@@ -293,6 +305,9 @@ bool gdcmFile::ReadPixelData(void* destination) {
  * \ingroup gdcmFile
  * \brief   Allocates necessary memory, copies the pixel data
  *          (image[s]/volume[s]) to newly allocated zone.
+ *          Transforms YBR pixels into RGB pixels if any
+            Transforms 3 planes R, G, B into a single RGB Plane
+           Transforms single Grey plane + 3 Palettes into a RGB Plane
  * @return  Pointer to newly allocated pixel data.
  * \        NULL if alloc fails 
  */
@@ -303,10 +318,40 @@ void * gdcmFile::GetImageData (void) {
    return(PixelData);
 }
 
+/**
+ * \ingroup gdcmFile
+ * \brief   Allocates necessary memory, copies the pixel data
+ *          (image[s]/volume[s]) to newly allocated zone.
+ *          Transforms YBR pixels into RGB pixels if any
+            Transforms 3 planes R, G, B into a single RGB Plane
+           DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
+ * @return  Pointer to newly allocated pixel data.
+ * \        NULL if alloc fails 
+ */
+void * gdcmFile::GetImageDataRaw (void) {
+   if (HasLUT())
+      lgrTotale /= 3;  // TODO Let gdcmHeadar user a chance 
+                       // to get the right value
+                      // Create a member lgrTotaleRaw ???
+   PixelData = (void *) malloc(lgrTotale);
+   if (PixelData)
+      GetImageDataIntoVectorRaw(PixelData, lgrTotale);
+   return(PixelData);
+}
+
 /**
  * \ingroup gdcmFile
  * \brief   Copies at most MaxSize bytes of pixel data to caller's
  *          memory space.
+ * \warning This function was designed to avoid people that want to build
+ *          a volume from an image stack to need first to get the image pixels 
+ *          and then move them to the volume area.
+ *          It's absolutely useless for any VTK user since vtk chooses 
+ *          to invert the lines of an image, that is the last line comes first
+ *          (for some axis related reasons?). Hence he will have 
+ *          to load the image line by line, starting from the end.
+ *          VTK users have to call GetImageData
+ *     
  * @param   destination Address (in caller's memory space) at which the
  *          pixel data should be copied
  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
@@ -318,6 +363,92 @@ void * gdcmFile::GetImageData (void) {
 
 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
 
+   size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
+   
+   if (!HasLUT())
+      return lgrTotale; 
+                            
+         //       from Lut R + Lut G + Lut B
+         
+   unsigned char * newDest = (unsigned char *)malloc(lgrTotale);
+   unsigned char * a       = (unsigned char *)destination;      
+   unsigned char * lutRGBA =                  GetLUTRGBA();
+   if (lutRGBA) {          
+      int l = lgrTotaleRaw;
+      memmove(newDest, destination, l);// move Gray pixels to temp area            
+      int j;    
+      for (int i=0;i<l; i++) {         // Build RGB Pixels
+         j=newDest[i]*4;
+         *a++ = lutRGBA[j]; 
+         *a++ = lutRGBA[j+1];
+         *a++ = lutRGBA[j+2];
+      }
+      free(newDest);
+    
+   // now, it's an RGB image
+   // Lets's write it in the Header
+
+         // CreateOrReplaceIfExist ?
+        
+   std::string spp = "3";        // Samples Per Pixel
+   gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
+   std::string rgb= "RGB ";      // Photometric Interpretation
+   gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
+   std::string planConfig = "0"; // Planar Configuration
+   gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
+       
+               
+   } else { 
+            // need to make RGB Pixels (?)
+             //    from grey Pixels (?!)
+             //     and Gray Lut  (!?!) 
+            //    or Segmented xxx Palette Color Lookup Table Data and so on
+                 
+             // Well . I'll wait till I find such an image 
+                                 
+                  // Oops! I get one (gdcm-US-ALOKA-16.dcm)
+                   // No idea how to manage it 
+                  // It seems that *no Dicom Viewer* has any idea :-(
+                  // Segmented xxx Palette Color are *more* than 65535 long ?!?
+                  
+      std::string rgb= "MONOCHROME1 ";      // Photometric Interpretation
+      gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);                 
+                  
+   }   
+        
+   // TODO : Drop Palette Color out of the Header?          
+   return lgrTotale; 
+}
+
+
+
+/**
+ * \ingroup gdcmFile
+ * \brief   Copies at most MaxSize bytes of pixel data to caller's
+ *          memory space.
+ * \warning This function was designed to avoid people that want to build
+ *          a volume from an image stack to need first to get the image pixels 
+ *          and then move them to the volume area.
+ *          It's absolutely useless for any VTK user since vtk chooses 
+ *          to invert the lines of an image, that is the last line comes first
+ *          (for some axis related reasons?). Hence he will have 
+ *          to load the image line by line, starting from the end.
+ *          VTK users hace to call GetImageData
+  * \warning DOES NOT transform the Grey Plane + Palette Color (if any) 
+ *                   into a single RGB Pixels Plane
+ *          the (VTK) user will manage the palettes
+ *     
+ * @param   destination Address (in caller's memory space) at which the
+ *          pixel data should be copied
+ * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
+ *          is not sufficient to hold the pixel data the copy is not
+ *          executed (i.e. no partial copy).
+ * @return  On success, the number of bytes actually copied. Zero on
+ *          failure e.g. MaxSize is lower than necessary.
+ */
+
+size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t MaxSize) {
+
    int nb, nbu, highBit, signe;
    std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
  
@@ -351,12 +482,13 @@ size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
       highBit = nb - 1;
    } else {
       highBit = atoi(str_highBit.c_str() );
-   }
-               
-       // Signe des Pixels 
+   }           
+       // Pixel sign
+       // 0 = Unsigned
+       // 1 = Signed
    str_signe=GetPubElValByNumber(0x0028,0x0103);
    if (str_signe == GDCM_UNFOUND ) {
-      signe = 1;
+      signe = 0;  // default is unsigned
    } else {
       signe = atoi(str_signe.c_str() );
    }
@@ -364,7 +496,18 @@ size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
    // re arange bytes inside the integer
    if (nb != 8)
      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
+     
+   // to avoid pb with some xmedcon breakers images 
+   if (nb==16 && nbu<nb && signe==0) {
+     int l = (int)lgrTotale / (nb/8);
+     guint16 *deb = (guint16 *)destination;
+     for(int i = 0; i<l; i++) {
+        if(*deb == 0xffff) 
+          *deb=0; 
+          deb++;   
+         }
+    }
+
    // re arange bits inside the bytes
    if (nbu != nb){
       int l = (int)lgrTotale / (nb/8);
@@ -390,11 +533,15 @@ size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
       }
    } 
 
-// Just to 'see' was was actually read on disk :-(
+// Just to 'see' what was actually read on disk :-(
 // Some troubles expected
+//   FILE * f2;
+//   f2 = fopen("SpuriousFile.raw","wb");
+//   fwrite(destination,lgrTotale,1,f2);
+//   fclose(f2);
 
-   // *Try* to deal with the color
-   // ----------------------------
+   // Deal with the color
+   // -------------------
    
        std::string str_PhotometricInterpretation = 
                  gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
@@ -428,12 +575,18 @@ size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
       case 1:
 
          {
-         if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
-
-         //       need to make RGB Pixels from Planes Y,cB,cR
+         if (str_PhotometricInterpretation == "YBR_FULL") { 
+        
+        // Warning : YBR_FULL_422 acts as RGB
+         //         : we need to make RGB Pixels from Planes Y,cB,cR
          // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
          // for code optimisation
-
+        
+        // to see the tricks about YBR_FULL, YBR_FULL_422, 
+         // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
+        //   ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
+        // and be *very* affraid
+        //
             int l = GetXSize()*GetYSize();
             int nbFrames = GetZSize();
 
@@ -471,27 +624,23 @@ size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
 
         } else {
          
-         //       need to make RGB Pixels from Planes R,G,B
+         //       need to make RGB Pixels from R,G,B Planes
+        //       (all the Frames at a time)
 
-            int l = GetXSize()*GetYSize();
-            int nbFrames = GetZSize();
+            int l = GetXSize()*GetYSize()*GetZSize();
 
             char * newDest = (char*) malloc(lgrTotale);
-            char * = newDest;
+            char * x = newDest;
             char * a = (char *)destination;
             char * b = a + l;
             char * c = b + l;
 
-               // TODO :
-               // any trick not to have to allocate temporary buffer is welcome ...
-
-            for (int i=0;i<nbFrames;i++) {
-               for (int j=0;j<l; j++) {
-                  *(x++) = *(a++);
-                  *(x++) = *(b++);
-                  *(x++) = *(c++);  
-               }
+            for (int j=0;j<l; j++) {
+               *(x++) = *(a++);
+               *(x++) = *(b++);
+               *(x++) = *(c++);  
             }
+           
             memmove(destination,newDest,lgrTotale);
             free(newDest);
         }
@@ -500,92 +649,31 @@ size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
        }
      
        case 2:                      
-         //       from Lut R + Lut G + Lut B
-       
-         // we no longer use gdcmHeader::GetLUTRGB
-         // since a lot of images have strange info 
-         // in the Lookup Table Descriptors (0028,1101),...
-         {
-         unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
-         unsigned char * a = (unsigned char *)destination;
-
-         unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
-         unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
-         unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
-
-         if (lutR && lutG && lutB ) { // need to make RGB Pixels 
-                                      // from grey Pixels 
-                                      // and Lut R,Lut G,Lut B
-
-            unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
-            int l = lgrTotale/3;
-            memmove(newDest, destination, l);// move Gray pixels to temp area
-
-            int j;
-               // See PS 3.3-2003 C.11.1.1.2 p 619
-               // 
-            int mult;
-            if (GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3 
-            else mult=1;
-
-            // if we get a black image, let's just remove the '+1'
-            // and check again 
-            // if it works, we shall have to check the 3 Palettes
-            // to see which byte is ==0 (first one, or second one)
-                          
-            for (int i=0;i<l; i++) {
-               j=newDest[i]*mult +1;
-               *a++ = lutR[j]; 
-               *a++ = lutG[j];
-               *a++ = lutB[j];
-            }
-
-            free(newDest);
-               
-         } else { 
-            // need to make RGB Pixels (?)
-             // from grey Pixels (?!)
-             // and Gray Lut  (!?!) 
-             //unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
-                 
-                             // Well . I'll wait till I find such an image 
-                 
-            // or Segmented Green Palette Color Lookup Table Data and so on
-                 
-                           // Oops! I get one (gdcm-US-ALOKA-16.dcm)
-                           // No idea how to manage it :-(
-                           // Segmented xxx Palette Color are *more* than 65535 long ?!?
-                           
-            // WARNING : quick and dirty trick to produce a single plane Grey image
-           // See also  gdcmHeaderHelper::GetNumberOfScalarComponents()                              
-                   lgrTotale /=3;
-                   return lgrTotale;
-           // end of dirty trick
-         }
-         break;
-      }
+         //       Palettes were found
+        //       Let the user deal with them !
+         return lgrTotale;        
    } 
-
             // now, it's an RGB image
             // Lets's write it in the Header
 
          // CreateOrReplaceIfExist ?
         
+
+
    std::string spp = "3";        // Samples Per Pixel
    gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
-   std::string rgb="RGB ";       // Photometric Interpretation
+   std::string rgb="RGB ";   // Photometric Interpretation
    gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
+
    std::string planConfig = "0"; // Planar Configuration
    gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
         
-        // + Drop Palette Color 
+        // TODO : Drop Palette Color out of the Header
             
    return lgrTotale; 
 }
 
-//
-// Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
-//
+
 
 /**
  * \ingroup gdcmFile