r593: no message
[ctsim.git] / libctsim / imagefile.cpp
index 37eaa8f636927c7273537677e9adb00f9027dd34..d0474045c9055744faa7dcde3a9cf468e213582e 100644 (file)
@@ -1,15 +1,15 @@
 /*****************************************************************************
 ** FILE IDENTIFICATION
 **
-**     Name:         imagefile.cpp
-**      Purpose:      Imagefile classes
+**     Name:           imagefile.cpp
+**  Purpose:      Imagefile classes
 **     Programmer:   Kevin Rosenberg
 **     Date Started: June 2000
 **
 **  This is part of the CTSim program
-**  Copyright (C) 1983-2000 Kevin Rosenberg
+**  Copyright (c) 1983-2001 Kevin Rosenberg
 **
-**  $Id: imagefile.cpp,v 1.35 2001/01/06 15:33:15 kevin Exp $
+**  $Id: imagefile.cpp,v 1.39 2001/03/02 02:08:14 kevin Exp $
 **
 **  This program is free software; you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License (version 2) as
 
 #include "ct.h"
 
-const int ImageFile::FORMAT_INVALID = -1;
-const int ImageFile::FORMAT_PGM = 0;
-const int ImageFile::FORMAT_PGMASCII = 1;
+const double ImageFile::s_dRedGrayscaleFactor = 0.299;
+const double ImageFile::s_dGreenGrayscaleFactor = 0.587;
+const double ImageFile::s_dBlueGrayscaleFactor = 0.114;
+
+
+const int ImageFile::EXPORT_FORMAT_INVALID = -1;
+const int ImageFile::EXPORT_FORMAT_PGM = 0;
+const int ImageFile::EXPORT_FORMAT_PGMASCII = 1;
 #ifdef HAVE_PNG
-const int ImageFile::FORMAT_PNG = 2;
-const int ImageFile::FORMAT_PNG16 = 3;
+const int ImageFile::EXPORT_FORMAT_PNG = 2;
+const int ImageFile::EXPORT_FORMAT_PNG16 = 3;
+#endif
+#ifdef HAVE_CTN_DICOM
+const int ImageFile::EXPORT_FORMAT_DICOM = 4;
 #endif
 
-const char* ImageFile::s_aszFormatName[] = 
+const char* ImageFile::s_aszExportFormatName[] = 
 {
   {"pgm"},
   {"pgmascii"},
@@ -43,17 +51,54 @@ const char* ImageFile::s_aszFormatName[] =
   {"png"},
   {"png16"},
 #endif
+#ifdef HAVE_CTN_DICOM
+  {"dicom"},
+#endif
 };
 
-const char* ImageFile::s_aszFormatTitle[] = 
+const char* ImageFile::s_aszExportFormatTitle[] = 
 {
   {"PGM"},
   {"PGM ASCII"},
   {"PNG"},
   {"PNG 16-bit"},
+#ifdef HAVE_CTN_DICOM
+  {"Dicom"},
+#endif
+};
+const int ImageFile::s_iExportFormatCount = sizeof(s_aszExportFormatName) / sizeof(const char*);
+
+
+const int ImageFile::IMPORT_FORMAT_INVALID = -1;
+const int ImageFile::IMPORT_FORMAT_PPM = 0;
+#ifdef HAVE_PNG
+const int ImageFile::IMPORT_FORMAT_PNG = 1;
+#endif
+#ifdef HAVE_CTN_DICOM
+const int ImageFile::IMPORT_FORMAT_DICOM = 2;
+#endif
+
+
+const char* ImageFile::s_aszImportFormatName[] = 
+{
+  {"ppm"},
+#ifdef HAVE_PNG
+  {"png"},
+#endif
+#ifdef HAVE_CTN_DICOM
+  {"dicom"},
+#endif
 };
 
-const int ImageFile::s_iFormatCount = sizeof(s_aszFormatName) / sizeof(const char*);
+const char* ImageFile::s_aszImportFormatTitle[] = 
+{
+  {"PPM"},
+  {"PNG"},
+#ifdef HAVE_CTN_DICOM
+  {"Dicom"},
+#endif
+};
+const int ImageFile::s_iImportFormatCount = sizeof(s_aszImportFormatName) / sizeof(const char*);
 
 
 
@@ -90,7 +135,7 @@ ImageFile::getCenterCoordinates (unsigned int& iXCenter, unsigned int& iYCenter)
     iXCenter = m_nx / 2;
   else
     iXCenter = (m_nx - 1) / 2;
-
+  
   if (isEven (m_ny))
     iYCenter = m_ny / 2;
   else
@@ -106,7 +151,7 @@ ImageFile::filterResponse (const char* const domainName, double bw, const char*
   
   unsigned int iXCenter, iYCenter;
   getCenterCoordinates (iXCenter, iYCenter);
-
+  
   for (unsigned int ix = 0; ix < m_nx; ix++)
     for (unsigned int iy = 0; iy < m_ny; iy++) {
       long lD2 = ((ix - iXCenter) * (ix - iXCenter)) + ((iy - iYCenter) * (iy - iYCenter));
@@ -599,7 +644,7 @@ bool
 ImageFile::log (ImageFile& result) const
 {
   if (m_nx != result.nx() || m_ny != result.ny()) {
-    sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
+    sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::log]");
     return false;
   }
   
@@ -621,8 +666,12 @@ ImageFile::log (ImageFile& result) const
         std::complex<double> cResult = std::log (cLHS);
         vResult[ix][iy] = cResult.real();
         vResultImag[ix][iy] = cResult.imag();
-      } else
-        vResult[ix][iy] = ::log (vLHS[ix][iy]);
+      } else {
+        if (vLHS[ix][iy] > 0)
+          vResult[ix][iy] = ::log (vLHS[ix][iy]);
+        else
+          vResult[ix][iy] = 0;
+      }
     }
   }
   
@@ -708,9 +757,9 @@ ImageFile::scaleImage (ImageFile& result) const
         if (result.isComplex()) {
           if (isComplex())
             vResultImag[ix][iy] = (1 - dXFrac) * (1 - dYFrac) * vImag[scaleNX][scaleNY] + 
-          dXFrac * (1 - dYFrac) * vImag[scaleNX+1][scaleNY] + 
-          dYFrac * (1 - dXFrac) * vImag[scaleNX][scaleNY+1] +
-          dXFrac * dYFrac * vImag[scaleNX+1][scaleNY+1];
+            dXFrac * (1 - dYFrac) * vImag[scaleNX+1][scaleNY] + 
+            dYFrac * (1 - dXFrac) * vImag[scaleNX][scaleNY+1] +
+            dXFrac * dYFrac * vImag[scaleNX+1][scaleNY+1];
           else
             vResultImag[ix][iy] = 0;
         }
@@ -855,7 +904,7 @@ ImageFile::fftRows (ImageFile& result) const
   
   fftw_plan plan = fftw_create_plan (m_nx, FFTW_FORWARD, FFTW_IN_PLACE);
   std::complex<double>* pcRow = new std::complex<double> [m_nx];
-
+  
   unsigned int ix, iy;
   unsigned int iArray = 0;
   for (iy = 0; iy < m_ny; iy++) {
@@ -866,12 +915,12 @@ ImageFile::fftRows (ImageFile& result) const
       else
         in[ix].im = 0;
     }
-
+    
     fftw_one (plan, in, NULL);
-
+    
     for (ix = 0; ix < m_nx; ix++)
       pcRow[ix] = std::complex<double>(in[ix].re, in[ix].im);
-
+    
     Fourier::shuffleFourierToNaturalOrder (pcRow, m_nx);
     for (ix = 0; ix < m_nx; ix++) {
       vReal[ix][iy] = pcRow[ix].real();
@@ -879,11 +928,11 @@ ImageFile::fftRows (ImageFile& result) const
     }
   }
   delete [] pcRow;
-   
-   fftw_destroy_plan (plan);
-   delete in;
-
-   return true;
+  
+  fftw_destroy_plan (plan);
+  delete in;
+  
+  return true;
 }     
 
 bool
@@ -906,7 +955,7 @@ ImageFile::ifftRows (ImageFile& result) const
   
   fftw_plan plan = fftw_create_plan (m_nx, FFTW_BACKWARD, FFTW_IN_PLACE);
   std::complex<double>* pcRow = new std::complex<double> [m_nx];
-
+  
   unsigned int ix, iy;
   unsigned int iArray = 0;
   for (iy = 0; iy < m_ny; iy++) {
@@ -916,16 +965,16 @@ ImageFile::ifftRows (ImageFile& result) const
         dImag = vImag[ix][iy];
       pcRow[ix] = std::complex<double> (vReal[ix][iy], dImag);
     }
-
+    
     Fourier::shuffleNaturalToFourierOrder (pcRow, m_nx);
-
+    
     for (ix = 0; ix < m_nx; ix++) {
       in[ix].re = pcRow[ix].real();
       in[ix].im = pcRow[ix].imag();
     }
-
+    
     fftw_one (plan, in, NULL);
-
+    
     for (ix = 0; ix < m_nx; ix++) {
       vReal[ix][iy] = in[ix].re;
       vImag[ix][iy] = in[ix].im;
@@ -933,10 +982,10 @@ ImageFile::ifftRows (ImageFile& result) const
   }
   delete [] pcRow;
   
-   fftw_destroy_plan (plan);
-   delete in;
-
-   return true;
+  fftw_destroy_plan (plan);
+  delete in;
+  
+  return true;
 }
 
 bool
@@ -1183,12 +1232,12 @@ ImageFile::square (ImageFile& result) const
 }
 
 int
-ImageFile::convertFormatNameToID (const char* const formatName)
+ImageFile::convertExportFormatNameToID (const char* const formatName)
 {
-  int formatID = FORMAT_INVALID;
+  int formatID = EXPORT_FORMAT_INVALID;
   
-  for (int i = 0; i < s_iFormatCount; i++)
-    if (strcasecmp (formatName, s_aszFormatName[i]) == 0) {
+  for (int i = 0; i < s_iExportFormatCount; i++)
+    if (strcasecmp (formatName, s_aszExportFormatName[i]) == 0) {
       formatID = i;
       break;
     }
@@ -1197,49 +1246,331 @@ ImageFile::convertFormatNameToID (const char* const formatName)
 }
 
 const char*
-ImageFile::convertFormatIDToName (int formatID)
+ImageFile::convertExportFormatIDToName (int formatID)
 {
   static const char *formatName = "";
   
-  if (formatID >= 0 && formatID < s_iFormatCount)
-    return (s_aszFormatName[formatID]);
+  if (formatID >= 0 && formatID < s_iExportFormatCount)
+    return (s_aszExportFormatName[formatID]);
   
   return (formatName);
 }
 
 const char*
-ImageFile::convertFormatIDToTitle (const int formatID)
+ImageFile::convertExportFormatIDToTitle (const int formatID)
 {
   static const char *formatTitle = "";
   
-  if (formatID >= 0 && formatID < s_iFormatCount)
-    return (s_aszFormatTitle[formatID]);
+  if (formatID >= 0 && formatID < s_iExportFormatCount)
+    return (s_aszExportFormatTitle[formatID]);
+  
+  return (formatTitle);
+}
+
+int
+ImageFile::convertImportFormatNameToID (const char* const formatName)
+{
+  int formatID = IMPORT_FORMAT_INVALID;
+  
+  for (int i = 0; i < s_iImportFormatCount; i++)
+    if (strcasecmp (formatName, s_aszImportFormatName[i]) == 0) {
+      formatID = i;
+      break;
+    }
+    
+    return (formatID);
+}
+
+const char*
+ImageFile::convertImportFormatIDToName (int formatID)
+{
+  static const char *formatName = "";
+  
+  if (formatID >= 0 && formatID < s_iImportFormatCount)
+    return (s_aszImportFormatName[formatID]);
+  
+  return (formatName);
+}
+
+const char*
+ImageFile::convertImportFormatIDToTitle (const int formatID)
+{
+  static const char *formatTitle = "";
+  
+  if (formatID >= 0 && formatID < s_iImportFormatCount)
+    return (s_aszImportFormatTitle[formatID]);
   
   return (formatTitle);
 }
 
 bool
-ImageFile::exportImage (const char* const pszFormat, const char* const pszFilename, int nxcell, int nycell, double densmin, double densmax)
+ImageFile::importImage (const char* const pszFormat, const char* const pszFilename)
 {
-  int iFormatID = convertFormatNameToID (pszFormat);
-  if (iFormatID == FORMAT_INVALID) {
-    sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::exportImage]", pszFormat);
+  int iFormatID = convertImportFormatNameToID (pszFormat);
+  
+  if (iFormatID == IMPORT_FORMAT_PPM)
+    return readImagePPM (pszFilename);
+#ifdef HAVE_PNG
+  else if (iFormatID == IMPORT_FORMAT_PNG)
+    return readImagePNG (pszFilename);
+#endif
+  
+  sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::importImage]", pszFormat);
+  return false;
+}
+
+void
+ImageFile::skipSpacePPM (FILE* fp)
+{
+  int c = fgetc (fp);
+  while (isspace (c) || c == '#') {
+    if (c == '#') {   // comment until end of line
+      c = fgetc(fp);
+      while (c != 13 && c != 10)
+        c = fgetc(fp);
+    }
+    else
+      c = fgetc(fp);
+  }
+  
+  ungetc (c, fp);
+}
+
+bool
+ImageFile::readImagePPM (const char* const pszFile)
+{
+  FILE* fp = fopen (pszFile, "r");
+  if ((fp = fopen (pszFile, "r")) == NULL)
+    return false;
+  char cSignature = toupper(fgetc(fp));
+  if (cSignature != 'P') {
+    fclose(fp);
+    return false;
+  }
+  cSignature = fgetc(fp);
+  if (cSignature == '5' || cSignature == '6') { // binary modes
+    fclose(fp);
+    fp = fopen(pszFile, "rb"); // reopen in binary mode
+    fgetc(fp);
+    fgetc(fp);
+  } else if (cSignature != '2' && cSignature != '3') {
+    fclose(fp);
+    return false;
+  }
+  
+  int nRows, nCols, iMaxValue;
+  skipSpacePPM (fp); 
+  if (fscanf (fp, "%d", &nCols) != 1) {
+    fclose(fp);
+    return false;
+  }
+  skipSpacePPM (fp);
+  if (fscanf (fp, "%d", &nRows) != 1) {
+    fclose(fp);
+    return false;
+  }
+  skipSpacePPM (fp);
+  if (fscanf (fp, "%d", &iMaxValue) != 1) {
+    fclose(fp);
+    return false;
+  }
+  setArraySize (nRows, nCols);
+  
+  if (cSignature == '5' || cSignature == '6') { // binary modes
+    int c = fgetc(fp);
+    if (c == 13) {
+      c = fgetc(fp);
+      if (c != 10)  // read msdos 13-10 newline
+        ungetc(c, fp);
+    }
+  } else
+    skipSpacePPM (fp); // ascii may have comments
+  
+  double dMaxValue = iMaxValue;
+  ImageFileArray v = getArray();
+  for (int iy = nRows - 1; iy >= 0; iy--) {
+    for (int ix = 0; ix < nCols; ix++) {
+      int iGS, iR, iG, iB;
+      double dR, dG, dB;
+      switch (cSignature) {
+      case '2':
+        if (fscanf(fp, "%d ", &iGS) != 1) {
+          fclose(fp);
+          return false;
+        }
+        v[ix][iy] = iGS / dMaxValue;
+        break;
+      case '5':
+        iGS = fgetc(fp);
+        if (iGS == EOF) {
+          fclose(fp);
+          return false;
+        }
+        v[ix][iy] = iGS / dMaxValue;
+        break;
+      case '3':
+        if (fscanf (fp, "%d %d %d ", &iR, &iG, &iB) != 3) {
+          fclose(fp);
+          return false;
+        }
+        dR = iR / dMaxValue;
+        dG = iG / dMaxValue;
+        dB = iB / dMaxValue;
+        v[ix][iy] = colorToGrayscale (dR, dG, dB);
+        break;
+      case '6':
+        iR = fgetc(fp);
+        iG = fgetc(fp);
+        iB = fgetc(fp);
+        if (iB == EOF) {
+          fclose(fp);
+          return false;
+        }
+        dR = iR / dMaxValue;
+        dG = iG / dMaxValue;
+        dB = iB / dMaxValue;
+        v[ix][iy] = colorToGrayscale (dR, dG, dB);
+        break;
+      }
+    }
+  }
+  
+  fclose(fp);
+  return true;
+}
+
+#ifdef HAVE_PNG
+bool
+ImageFile::readImagePNG (const char* const pszFile)
+{
+  FILE* fp = fopen(pszFile, "rb");
+  if (!fp) 
+    return false;
+  unsigned char header[8];
+  fread (header, 1, 8, fp);
+  if (png_sig_cmp (header, 0, 8)) {
+    fclose (fp);
+    return false;
+  }
+  
+  png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+  if (!png_ptr) {
+    fclose(fp);
+    return false;
+  }
+  
+  png_infop info_ptr = png_create_info_struct(png_ptr);
+  if (!info_ptr) {
+    png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
+    fclose(fp);
+    return false;
+  }
+  
+  png_infop end_info = png_create_info_struct(png_ptr);
+  if (!end_info) {
+    png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
+    fclose(fp);
     return false;
   }
   
-  if (iFormatID == FORMAT_PGM)
+  if (setjmp(png_ptr->jmpbuf)) {
+    png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+    fclose(fp);
+    return false;
+  }
+  
+  png_init_io(png_ptr, fp);
+  png_set_sig_bytes(png_ptr, 8);
+  png_read_info(png_ptr, info_ptr);
+  
+  int width = png_get_image_width (png_ptr, info_ptr);
+  int height = png_get_image_height (png_ptr, info_ptr);
+  int bit_depth = png_get_bit_depth (png_ptr, info_ptr);
+  int color_type = png_get_color_type (png_ptr, info_ptr);
+  
+  if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8) 
+    png_set_expand(png_ptr);
+  
+  if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) 
+    png_set_expand(png_ptr);
+  
+  if (bit_depth < 8)
+    png_set_packing(png_ptr);
+  
+  if (color_type & PNG_COLOR_MASK_ALPHA)
+    png_set_strip_alpha(png_ptr);
+  
+  if (bit_depth == 16)
+    png_set_swap(png_ptr); // convert to little-endian format
+  
+  png_read_update_info(png_ptr, info_ptr); // update with transformations
+  int rowbytes = png_get_rowbytes (png_ptr, info_ptr);
+  bit_depth = png_get_bit_depth (png_ptr, info_ptr);
+  color_type = png_get_color_type (png_ptr, info_ptr);
+  
+  png_bytep* row_pointers = new png_bytep [height];
+  int i;
+  for (i = 0; i < height; i++)
+    row_pointers[i] = new unsigned char [rowbytes];
+  
+  png_read_image(png_ptr, row_pointers);
+  
+  setArraySize (width, height);
+  ImageFileArray v = getArray();
+  for (int iy = 0; iy < height; iy++) {
+    for (int ix = 0; ix < width; ix++) {
+      double dV;
+      if (color_type == PNG_COLOR_TYPE_GRAY) {
+        if (bit_depth == 8)
+          dV = row_pointers[iy][ix] / 255.;
+        else if (bit_depth == 16) {
+          int iBase = ix * 2;
+          dV = (row_pointers[iy][iBase] + (row_pointers[iy][iBase+1] << 8)) / 65536.;
+        }
+      } else if (color_type == PNG_COLOR_TYPE_RGB) {
+        if (bit_depth == 8) {
+          int iBase = ix * 3;
+          double dR = row_pointers[iy][iBase] / 255.;
+          double dG = row_pointers[iy][iBase+1] / 255.;
+          double dB = row_pointers[iy][iBase+2] / 255.;
+          dV = colorToGrayscale (dR, dG, dR);
+        }
+      }
+      v[ix][height-iy-1] = dV;
+    }
+  }
+  
+  png_read_end(png_ptr, end_info);
+  png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
+  
+  for (i = 0; i < height; i++)
+    delete row_pointers[i];
+  delete row_pointers;
+  
+  fclose (fp);
+  return true;
+}
+#endif
+
+bool
+ImageFile::exportImage (const char* const pszFormat, const char* const pszFilename, int nxcell, int nycell, double densmin, double densmax)
+{
+  int iFormatID = convertExportFormatNameToID (pszFormat);
+  
+  if (iFormatID == EXPORT_FORMAT_PGM)
     return writeImagePGM (pszFilename, nxcell, nycell, densmin, densmax);
-  else if (iFormatID == FORMAT_PGMASCII)
+  else if (iFormatID == EXPORT_FORMAT_PGMASCII)
     return writeImagePGMASCII (pszFilename, nxcell, nycell, densmin, densmax);
-  else if (iFormatID == FORMAT_PNG)
+  else if (iFormatID == EXPORT_FORMAT_PNG)
     return writeImagePNG (pszFilename, 8, nxcell, nycell, densmin, densmax);
-  else if (iFormatID == FORMAT_PNG16)
+  else if (iFormatID == EXPORT_FORMAT_PNG16)
     return writeImagePNG (pszFilename, 16, nxcell, nycell, densmin, densmax);
   
   sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::exportImage]", pszFormat);
   return false;
 }
 
+
 bool
 ImageFile::writeImagePGM (const char* const outfile, int nxcell, int nycell, double densmin, double densmax)
 {
@@ -1424,7 +1755,7 @@ ImageFile::writeImageGIF (const char* const outfile, int nxcell, int nycell, dou
   
   FILE *out;
   if ((out = fopen (outfile,"w")) == NULL) {
-    sys_error(ERR_FATAL, "Error opening output file %s for writing", outfile);
+    sys_error(ERR_SEVERE, "Error opening output file %s for writing", outfile);
     return false;
   }
   gdImageGif(gif,out);