r592: Added PPM & PNG File importing
[ctsim.git] / libctsim / imagefile.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **      Name:           imagefile.cpp
5 **  Purpose:      Imagefile classes
6 **      Programmer:   Kevin Rosenberg
7 **      Date Started: June 2000
8 **
9 **  This is part of the CTSim program
10 **  Copyright (c) 1983-2001 Kevin Rosenberg
11 **
12 **  $Id: imagefile.cpp,v 1.38 2001/03/01 20:02:18 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 #include "ct.h"
29
30 const double ImageFile::s_dRedGrayscaleFactor = 0.299;
31 const double ImageFile::s_dGreenGrayscaleFactor = 0.587;
32 const double ImageFile::s_dBlueGrayscaleFactor = 0.114;
33
34
35 const int ImageFile::EXPORT_FORMAT_INVALID = -1;
36 const int ImageFile::EXPORT_FORMAT_PGM = 0;
37 const int ImageFile::EXPORT_FORMAT_PGMASCII = 1;
38 #ifdef HAVE_PNG
39 const int ImageFile::EXPORT_FORMAT_PNG = 2;
40 const int ImageFile::EXPORT_FORMAT_PNG16 = 3;
41 #endif
42 #ifdef HAVE_CTN_DICOM
43 const int ImageFile::EXPORT_FORMAT_DICOM = 4;
44 #endif
45
46 const char* ImageFile::s_aszExportFormatName[] = 
47 {
48   {"pgm"},
49   {"pgmascii"},
50 #ifdef HAVE_PNG
51   {"png"},
52   {"png16"},
53 #endif
54 #ifdef HAVE_CTN_DICOM
55   {"dicom"},
56 #endif
57 };
58
59 const char* ImageFile::s_aszExportFormatTitle[] = 
60 {
61   {"PGM"},
62   {"PGM ASCII"},
63   {"PNG"},
64   {"PNG 16-bit"},
65 #ifdef HAVE_CTN_DICOM
66   {"Dicom"},
67 #endif
68 };
69 const int ImageFile::s_iExportFormatCount = sizeof(s_aszExportFormatName) / sizeof(const char*);
70
71
72 const int ImageFile::IMPORT_FORMAT_INVALID = -1;
73 const int ImageFile::IMPORT_FORMAT_PPM = 0;
74 #ifdef HAVE_PNG
75 const int ImageFile::IMPORT_FORMAT_PNG = 1;
76 #endif
77 #ifdef HAVE_CTN_DICOM
78 const int ImageFile::IMPORT_FORMAT_DICOM = 2;
79 #endif
80
81
82 const char* ImageFile::s_aszImportFormatName[] = 
83 {
84   {"ppm"},
85 #ifdef HAVE_PNG
86   {"png"},
87 #endif
88 #ifdef HAVE_CTN_DICOM
89   {"dicom"},
90 #endif
91 };
92
93 const char* ImageFile::s_aszImportFormatTitle[] = 
94 {
95   {"PPM"},
96   {"PNG"},
97 #ifdef HAVE_CTN_DICOM
98   {"Dicom"},
99 #endif
100 };
101 const int ImageFile::s_iImportFormatCount = sizeof(s_aszImportFormatName) / sizeof(const char*);
102
103
104
105 F32Image::F32Image (int nx, int ny, int dataType)
106 : Array2dFile (nx, ny, sizeof(kfloat32), Array2dFile::PIXEL_FLOAT32, dataType)
107 {
108 }
109
110 F32Image::F32Image (void)
111 : Array2dFile()
112 {
113   setPixelFormat (Array2dFile::PIXEL_FLOAT32);
114   setPixelSize (sizeof(kfloat32));
115   setDataType (Array2dFile::DATA_TYPE_REAL);
116 }
117
118 F64Image::F64Image (int nx, int ny, int dataType)
119 : Array2dFile (nx, ny, sizeof(kfloat64), Array2dFile::PIXEL_FLOAT64, dataType)
120 {
121 }
122
123 F64Image::F64Image (void)
124 : Array2dFile ()
125 {
126   setPixelFormat (PIXEL_FLOAT64);
127   setPixelSize (sizeof(kfloat64));
128   setDataType (Array2dFile::DATA_TYPE_REAL);
129 }
130
131 void 
132 ImageFile::getCenterCoordinates (unsigned int& iXCenter, unsigned int& iYCenter)
133 {
134   if (isEven (m_nx))
135     iXCenter = m_nx / 2;
136   else
137     iXCenter = (m_nx - 1) / 2;
138   
139   if (isEven (m_ny))
140     iYCenter = m_ny / 2;
141   else
142     iYCenter = (m_ny - 1) / 2;
143 }
144
145
146 void 
147 ImageFile::filterResponse (const char* const domainName, double bw, const char* const filterName, double filt_param, double dInputScale, double dOutputScale)
148 {
149   ImageFileArray v = getArray();
150   SignalFilter filter (filterName, domainName, bw, filt_param);
151   
152   unsigned int iXCenter, iYCenter;
153   getCenterCoordinates (iXCenter, iYCenter);
154   
155   for (unsigned int ix = 0; ix < m_nx; ix++)
156     for (unsigned int iy = 0; iy < m_ny; iy++) {
157       long lD2 = ((ix - iXCenter) * (ix - iXCenter)) + ((iy - iYCenter) * (iy - iYCenter));
158       double r = ::sqrt (static_cast<double>(lD2)) * dInputScale;
159       v[ix][iy] = filter.response (r) * dOutputScale;
160     }
161 }
162
163 int
164 ImageFile::display (void) const
165 {
166   double pmin, pmax;
167   
168   getMinMax (pmin, pmax);
169   
170   return (displayScaling (1, pmin, pmax));
171 }
172
173 int 
174 ImageFile::displayScaling (const int scale, const ImageFileValue pmin, const ImageFileValue pmax) const
175 {
176   int nx = m_nx;
177   int ny = m_ny;
178   ImageFileArrayConst v = getArray();
179   if (v == NULL || nx == 0 || ny == 0)
180     return 0;
181   
182 #if HAVE_G2_H
183   int* pPens = new int [nx * ny * scale * scale ];
184   
185   double view_scale = 255 / (pmax - pmin);
186   int id_X11 = g2_open_X11 (nx * scale, ny * scale);
187   int grayscale[256];
188   for (int i = 0; i < 256; i++) {
189     double cval = i / 255.;
190     grayscale[i] = g2_ink (id_X11, cval, cval, cval);
191   }
192   
193   for (int iy = ny - 1; iy >= 0; iy--) {
194     int iRowPos = ((ny - 1 - iy) * scale) * (nx * scale);
195     for (int ix = 0; ix < nx; ix++) {
196       int cval = static_cast<int>((v[ix][iy] - pmin) * view_scale);
197       if (cval < 0)  
198         cval = 0;
199       else if (cval > 255) 
200         cval = 255;
201       for (int sy = 0; sy < scale; sy++)
202         for (int sx = 0; sx < scale; sx++)
203           pPens[iRowPos+(sy * nx * scale)+(sx + (ix * scale))] = grayscale[cval];
204     }
205   }
206   
207   g2_image (id_X11, 0., 0., nx * scale, ny * scale, pPens);
208   
209   delete pPens;
210   return (id_X11);
211 #else
212   return 0;
213 #endif
214 }
215
216
217
218 // ImageFile::comparativeStatistics    Calculate comparative stats
219 //
220 // OUTPUT
221 //   d   Normalized root mean squared distance measure
222 //   r   Normalized mean absolute distance measure
223 //   e   Worst case distance measure
224 //
225 // REFERENCES
226 //  G.T. Herman, Image Reconstruction From Projections, 1980
227
228 bool
229 ImageFile::comparativeStatistics (const ImageFile& imComp, double& d, double& r, double& e) const
230 {
231   if (imComp.nx() != m_nx && imComp.ny() != m_ny) {
232     sys_error (ERR_WARNING, "Image sizes differ [ImageFile::comparativeStatistics]");
233     return false;
234   }
235   ImageFileArrayConst v = getArray();
236   if (v == NULL || m_nx == 0 || m_ny == 0)
237     return false;
238   
239   ImageFileArrayConst vComp = imComp.getArray();
240   
241   double myMean = 0.;
242   for (unsigned int ix = 0; ix < m_nx; ix++) {
243     for (unsigned int iy = 0; iy < m_ny; iy++) {
244       myMean += v[ix][iy];
245     }
246   }
247   myMean /= (m_nx * m_ny);
248   
249   double sqErrorSum = 0.;
250   double absErrorSum = 0.;
251   double sqDiffFromMeanSum = 0.;
252   double absValueSum = 0.;
253   for (unsigned int ix2 = 0; ix2 < m_nx; ix2++) {
254     for (unsigned int iy = 0; iy < m_ny; iy++) {
255       double diff = v[ix2][iy] - vComp[ix2][iy];
256       sqErrorSum += diff * diff;
257       absErrorSum += fabs(diff);
258       double diffFromMean = v[ix2][iy] - myMean;
259       sqDiffFromMeanSum += diffFromMean * diffFromMean;
260       absValueSum += fabs(v[ix2][iy]);
261     }
262   }
263   
264   d = ::sqrt (sqErrorSum / sqDiffFromMeanSum);
265   r = absErrorSum / absValueSum;
266   
267   int hx = m_nx / 2;
268   int hy = m_ny / 2;
269   double eMax = -1;
270   for (int ix3 = 0; ix3 < hx; ix3++) {
271     for (int iy = 0; iy < hy; iy++) {
272       double avgPixel = 0.25 * (v[2*ix3][2*iy] + v[2*ix3+1][2*iy] + v[2*ix3][2*iy+1] + v[2*ix3+1][2*iy+1]);
273       double avgPixelComp = 0.25 * (vComp[2*ix3][2*iy] + vComp[2*ix3+1][2*iy] + vComp[2*ix3][2*iy+1] + vComp[2*ix3+1][2*iy+1]);
274       double error = fabs (avgPixel - avgPixelComp);
275       if (error > eMax)
276         eMax = error;
277     }
278   }
279   
280   e = eMax;
281   
282   return true;
283 }
284
285
286 bool
287 ImageFile::printComparativeStatistics (const ImageFile& imComp, std::ostream& os) const
288 {
289   double d, r, e;
290   
291   if (comparativeStatistics (imComp, d, r, e)) {
292     os << "  Normalized root mean squared distance (d): " << d << std::endl;
293     os << "      Normalized mean absolute distance (r): " << r << std::endl;
294     os << "Worst case distance (2x2 pixel average) (e): " << e << std::endl;
295     return true;
296   }
297   return false;
298 }
299
300
301 void
302 ImageFile::printStatistics (std::ostream& os) const
303 {
304   double min, max, mean, mode, median, stddev;
305   
306   statistics (min, max, mean, mode, median, stddev);
307   if (isComplex())
308     os << "Real Component Statistics" << std::endl;
309   
310   os << "   min: " << min << std::endl;
311   os << "   max: " << max << std::endl;
312   os << "  mean: " << mean << std::endl;
313   os << "  mode: " << mode << std::endl;
314   os << "median: " << median << std::endl;
315   os << "stddev: " << stddev << std::endl;
316   
317   if (isComplex()) {
318     statistics (getImaginaryArray(), min, max, mean, mode, median, stddev);
319     os << std::endl << "Imaginary Component Statistics" << std::endl;
320     os << "   min: " << min << std::endl;
321     os << "   max: " << max << std::endl;
322     os << "  mean: " << mean << std::endl;
323     os << "  mode: " << mode << std::endl;
324     os << "median: " << median << std::endl;
325     os << "stddev: " << stddev << std::endl;
326   }
327 }
328
329
330 void
331 ImageFile::statistics (double& min, double& max, double& mean, double& mode, double& median, double& stddev) const
332 {
333   ImageFileArrayConst v = getArray();
334   statistics (v, min, max, mean, mode, median, stddev);
335 }
336
337
338 void
339 ImageFile::statistics (ImageFileArrayConst v, double& min, double& max, double& mean, double& mode, double& median, double& stddev) const
340 {
341   int nx = m_nx;
342   int ny = m_ny;
343   
344   if (v == NULL || nx == 0 || ny == 0)
345     return;
346   
347   std::vector<double> vecImage;
348   int iVec = 0;
349   vecImage.resize (nx * ny);
350   for (int ix = 0; ix < nx; ix++) {
351     for (int iy = 0; iy < ny; iy++)
352       vecImage[iVec++] = v[ix][iy];
353   }
354   
355   vectorNumericStatistics (vecImage, nx * ny, min, max, mean, mode, median, stddev);
356 }
357
358 void
359 ImageFile::getMinMax (double& min, double& max) const
360 {
361   int nx = m_nx;
362   int ny = m_ny;
363   ImageFileArrayConst v = getArray();
364   
365   if (v == NULL || nx == 0 || ny == 0)
366     return;
367   
368   min = v[0][0];
369   max = v[0][0];
370   for (int ix = 0; ix < nx; ix++) {
371     for (int iy = 0; iy < ny; iy++) {
372       if (v[ix][iy] > max)
373         max = v[ix][iy];
374       if (v[ix][iy] < min)
375         min = v[ix][iy];
376     }
377   }
378 }
379
380 bool
381 ImageFile::convertRealToComplex ()
382 {
383   if (dataType() != Array2dFile::DATA_TYPE_REAL)
384     return false;
385   
386   if (! reallocRealToComplex())
387     return false;
388   
389   ImageFileArray vImag = getImaginaryArray();
390   for (unsigned int ix = 0; ix < m_nx; ix++) {
391     ImageFileColumn vCol = vImag[ix];
392     for (unsigned int iy = 0; iy < m_ny; iy++)
393       *vCol++ = 0;
394   }
395   
396   return true;
397 }
398
399 bool
400 ImageFile::convertComplexToReal ()
401 {
402   if (dataType() != Array2dFile::DATA_TYPE_COMPLEX)
403     return false;
404   
405   ImageFileArray vReal = getArray();
406   ImageFileArray vImag = getImaginaryArray();
407   for (unsigned int ix = 0; ix < m_nx; ix++) {
408     ImageFileColumn vRealCol = vReal[ix];
409     ImageFileColumn vImagCol = vImag[ix];
410     for (unsigned int iy = 0; iy < m_ny; iy++) {
411       CTSimComplex c (*vRealCol, *vImagCol);
412       *vRealCol++ = std::abs (c);
413       vImagCol++;
414     }
415   }
416   
417   return reallocComplexToReal();
418 }
419
420 bool
421 ImageFile::subtractImages (const ImageFile& rRHS, ImageFile& result) const
422 {
423   if (m_nx != rRHS.nx() || m_ny != rRHS.ny() || m_nx != result.nx() || m_ny != result.ny()) {
424     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
425     return false;
426   }
427   
428   if (isComplex() || rRHS.isComplex() && ! result.isComplex())
429     result.convertRealToComplex();
430   
431   ImageFileArrayConst vLHS = getArray();
432   ImageFileArrayConst vLHSImag = getImaginaryArray();
433   ImageFileArrayConst vRHS = rRHS.getArray();
434   ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
435   ImageFileArray vResult = result.getArray();
436   ImageFileArray vResultImag = result.getImaginaryArray();
437   
438   for (unsigned int ix = 0; ix < m_nx; ix++) {
439     for (unsigned int iy = 0; iy < m_ny; iy++) {
440       vResult[ix][iy] = vLHS[ix][iy] - vRHS[ix][iy];
441       if (result.isComplex()) {
442         vResultImag[ix][iy] = 0;
443         if (isComplex())
444           vResultImag[ix][iy] += vLHSImag[ix][iy];
445         if (rRHS.isComplex())
446           vResultImag[ix][iy] -= vRHSImag[ix][iy];
447       }
448     }
449   }
450   
451   return true;
452 }
453
454 bool
455 ImageFile::addImages (const ImageFile& rRHS, ImageFile& result) const
456 {
457   if (m_nx != rRHS.nx() || m_ny != rRHS.ny() || m_nx != result.nx() || m_ny != result.ny()) {
458     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
459     return false;
460   }
461   
462   if (isComplex() || rRHS.isComplex() && ! result.isComplex())
463     result.convertRealToComplex();
464   
465   ImageFileArrayConst vLHS = getArray();
466   ImageFileArrayConst vLHSImag = getImaginaryArray();
467   ImageFileArrayConst vRHS = rRHS.getArray();
468   ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
469   ImageFileArray vResult = result.getArray();
470   ImageFileArray vResultImag = result.getImaginaryArray();
471   
472   for (unsigned int ix = 0; ix < m_nx; ix++) {
473     for (unsigned int iy = 0; iy < m_ny; iy++) {
474       vResult[ix][iy] = vLHS[ix][iy] + vRHS[ix][iy];
475       if (result.isComplex()) {
476         vResultImag[ix][iy] = 0;
477         if (isComplex())
478           vResultImag[ix][iy] += vLHSImag[ix][iy];
479         if (rRHS.isComplex())
480           vResultImag[ix][iy] += vRHSImag[ix][iy];
481       }
482     }
483   }
484   
485   return true;
486 }
487
488 bool
489 ImageFile::multiplyImages (const ImageFile& rRHS, ImageFile& result) const
490 {
491   if (m_nx != rRHS.nx() || m_ny != rRHS.ny() || m_nx != result.nx() || m_ny != result.ny()) {
492     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
493     return false;
494   }
495   
496   if (isComplex() || rRHS.isComplex() && ! result.isComplex())
497     result.convertRealToComplex();
498   
499   ImageFileArrayConst vLHS = getArray();
500   ImageFileArrayConst vLHSImag = getImaginaryArray();
501   ImageFileArrayConst vRHS = rRHS.getArray();
502   ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
503   ImageFileArray vResult = result.getArray();
504   ImageFileArray vResultImag = result.getImaginaryArray();
505   
506   for (unsigned int ix = 0; ix < m_nx; ix++) {
507     for (unsigned int iy = 0; iy < m_ny; iy++) {
508       if (result.isComplex()) {
509         double dImag = 0;
510         if (isComplex())
511           dImag = vLHSImag[ix][iy];
512         std::complex<double> cLHS (vLHS[ix][iy], dImag);
513         dImag = 0;
514         if (rRHS.isComplex())
515           dImag = vRHSImag[ix][iy];
516         std::complex<double> cRHS (vRHS[ix][iy], dImag);
517         std::complex<double> cResult = cLHS * cRHS;
518         vResult[ix][iy] = cResult.real();
519         vResultImag[ix][iy] = cResult.imag();
520       } else
521         vResult[ix][iy] = vLHS[ix][iy] * vRHS[ix][iy];
522     }
523   }
524   
525   
526   return true;
527 }
528
529 bool
530 ImageFile::divideImages (const ImageFile& rRHS, ImageFile& result) const
531 {
532   if (m_nx != rRHS.nx() || m_ny != rRHS.ny() || m_nx != result.nx() || m_ny != result.ny()) {
533     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::subtractImage]");
534     return false;
535   }
536   
537   if (isComplex() || rRHS.isComplex() && ! result.isComplex())
538     result.convertRealToComplex();
539   
540   ImageFileArrayConst vLHS = getArray();
541   ImageFileArrayConst vLHSImag = getImaginaryArray();
542   ImageFileArrayConst vRHS = rRHS.getArray();
543   ImageFileArrayConst vRHSImag = rRHS.getImaginaryArray();
544   ImageFileArray vResult = result.getArray();
545   ImageFileArray vResultImag = result.getImaginaryArray();
546   
547   for (unsigned int ix = 0; ix < m_nx; ix++) {
548     for (unsigned int iy = 0; iy < m_ny; iy++) {
549       if (result.isComplex()) {
550         double dImag = 0;
551         if (isComplex())
552           dImag = vLHSImag[ix][iy];
553         std::complex<double> cLHS (vLHS[ix][iy], dImag);
554         dImag = 0;
555         if (rRHS.isComplex())
556           dImag = vRHSImag[ix][iy];
557         std::complex<double> cRHS (vRHS[ix][iy], dImag);
558         std::complex<double> cResult = cLHS / cRHS;
559         vResult[ix][iy] = cResult.real();
560         vResultImag[ix][iy] = cResult.imag();
561       } else {
562         if (vRHS != 0)
563           vResult[ix][iy] = vLHS[ix][iy] / vRHS[ix][iy];
564         else
565           vResult[ix][iy] = 0;
566       }
567     }
568   }
569   
570   return true;
571 }
572
573
574 bool
575 ImageFile::invertPixelValues (ImageFile& result) const
576 {
577   if (m_nx != result.nx() || m_ny != result.ny()) {
578     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
579     return false;
580   }
581   
582   if (isComplex() && ! result.isComplex())
583     result.convertRealToComplex();
584   
585   ImageFileArrayConst vLHS = getArray();
586   ImageFileArray vResult = result.getArray();
587   
588   for (unsigned int ix = 0; ix < m_nx; ix++) {
589     ImageFileColumnConst in = vLHS[ix];
590     ImageFileColumn out = vResult[ix];
591     for (unsigned int iy = 0; iy < m_ny; iy++)
592       *out++ = - *in++;
593   }
594   
595   return true;
596 }
597
598 bool
599 ImageFile::sqrt (ImageFile& result) const
600 {
601   if (m_nx != result.nx() || m_ny != result.ny()) {
602     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
603     return false;
604   }
605   
606   if (isComplex() && ! result.isComplex())
607     result.convertRealToComplex();
608   
609   bool bComplexOutput = result.isComplex();
610   ImageFileArrayConst vLHS = getArray();
611   if (! bComplexOutput)   // check if should convert to complex output
612     for (unsigned int ix = 0; ix < m_nx; ix++)
613       for (unsigned int iy = 0; iy < m_ny; iy++)
614         if (! bComplexOutput && vLHS[ix][iy] < 0) {
615           result.convertRealToComplex();
616           bComplexOutput = true;
617           break;
618         }
619         
620         ImageFileArrayConst vLHSImag = getImaginaryArray();
621         ImageFileArray vResult = result.getArray();
622         ImageFileArray vResultImag = result.getImaginaryArray();
623         
624         for (unsigned int ix = 0; ix < m_nx; ix++) {
625           for (unsigned int iy = 0; iy < m_ny; iy++) {
626             if (result.isComplex()) {
627               double dImag = 0;
628               if (isComplex())
629                 dImag = vLHSImag[ix][iy];
630               std::complex<double> cLHS (vLHS[ix][iy], dImag);
631               std::complex<double> cResult = std::sqrt(cLHS);
632               vResult[ix][iy] = cResult.real();
633               vResultImag[ix][iy] = cResult.imag();
634             } else
635               vResult[ix][iy] = ::sqrt (vLHS[ix][iy]);
636           }
637         }
638         
639         
640         return true;
641 }
642
643 bool
644 ImageFile::log (ImageFile& result) const
645 {
646   if (m_nx != result.nx() || m_ny != result.ny()) {
647     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
648     return false;
649   }
650   
651   if (isComplex() && ! result.isComplex())
652     result.convertRealToComplex();
653   
654   ImageFileArrayConst vLHS = getArray();
655   ImageFileArrayConst vLHSImag = getImaginaryArray();
656   ImageFileArray vResult = result.getArray();
657   ImageFileArray vResultImag = result.getImaginaryArray();
658   
659   for (unsigned int ix = 0; ix < m_nx; ix++) {
660     for (unsigned int iy = 0; iy < m_ny; iy++) {
661       if (result.isComplex()) {
662         double dImag = 0;
663         if (isComplex())
664           dImag = vLHSImag[ix][iy];
665         std::complex<double> cLHS (vLHS[ix][iy], dImag);
666         std::complex<double> cResult = std::log (cLHS);
667         vResult[ix][iy] = cResult.real();
668         vResultImag[ix][iy] = cResult.imag();
669       } else
670         vResult[ix][iy] = ::log (vLHS[ix][iy]);
671     }
672   }
673   
674   
675   return true;
676 }
677
678 bool
679 ImageFile::exp (ImageFile& result) const
680 {
681   if (m_nx != result.nx() || m_ny != result.ny()) {
682     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
683     return false;
684   }
685   
686   if (isComplex() && ! result.isComplex())
687     result.convertRealToComplex();
688   
689   ImageFileArrayConst vLHS = getArray();
690   ImageFileArrayConst vLHSImag = getImaginaryArray();
691   ImageFileArray vResult = result.getArray();
692   ImageFileArray vResultImag = result.getImaginaryArray();
693   
694   for (unsigned int ix = 0; ix < m_nx; ix++) {
695     for (unsigned int iy = 0; iy < m_ny; iy++) {
696       if (result.isComplex()) {
697         double dImag = 0;
698         if (isComplex())
699           dImag = vLHSImag[ix][iy];
700         std::complex<double> cLHS (vLHS[ix][iy], dImag);
701         std::complex<double> cResult = std::exp (cLHS);
702         vResult[ix][iy] = cResult.real();
703         vResultImag[ix][iy] = cResult.imag();
704       } else
705         vResult[ix][iy] = ::exp (vLHS[ix][iy]);
706     }
707   }
708   
709   
710   return true;
711 }
712
713 bool
714 ImageFile::scaleImage (ImageFile& result) const
715 {
716   unsigned int nx = m_nx;
717   unsigned int ny = m_ny;
718   unsigned int newNX = result.nx();
719   unsigned int newNY = result.ny();
720   
721   double dXScale = static_cast<double>(newNX) / static_cast<double>(nx);
722   double dYScale = static_cast<double>(newNY) / static_cast<double>(ny);
723   
724   if (isComplex() && ! result.isComplex())
725     result.convertRealToComplex();
726   
727   ImageFileArrayConst vReal = getArray();
728   ImageFileArrayConst vImag = getImaginaryArray();
729   ImageFileArray vResult = result.getArray();
730   ImageFileArray vResultImag = result.getImaginaryArray();
731   
732   for (unsigned int ix = 0; ix < newNX; ix++) {
733     for (unsigned int iy = 0; iy < newNY; iy++) {
734       double dXPos = ix / dXScale;
735       double dYPos = iy / dYScale;
736       unsigned int scaleNX = static_cast<unsigned int> (dXPos);
737       unsigned int scaleNY = static_cast<unsigned int> (dYPos);
738       double dXFrac = dXPos - scaleNX;
739       double dYFrac = dYPos - scaleNY;
740       if (scaleNX >= nx - 1 || scaleNY >= ny - 1) {
741         vResult[ix][iy] = vReal[scaleNX][scaleNY];
742         if (result.isComplex()) {
743           if (isComplex())
744             vResultImag[ix][iy] = vImag[scaleNX][scaleNY];
745           else
746             vResultImag[ix][iy] = 0;
747         }
748       } else {
749         vResult[ix][iy] = (1 - dXFrac) * (1 - dYFrac) * vReal[scaleNX][scaleNY] + 
750           dXFrac * (1 - dYFrac) * vReal[scaleNX+1][scaleNY] + 
751           dYFrac * (1 - dXFrac) * vReal[scaleNX][scaleNY+1] +
752           dXFrac * dYFrac * vReal[scaleNX+1][scaleNY+1];
753         if (result.isComplex()) {
754           if (isComplex())
755             vResultImag[ix][iy] = (1 - dXFrac) * (1 - dYFrac) * vImag[scaleNX][scaleNY] + 
756             dXFrac * (1 - dYFrac) * vImag[scaleNX+1][scaleNY] + 
757             dYFrac * (1 - dXFrac) * vImag[scaleNX][scaleNY+1] +
758             dXFrac * dYFrac * vImag[scaleNX+1][scaleNY+1];
759           else
760             vResultImag[ix][iy] = 0;
761         }
762       }
763     }
764   }
765   
766   return true;
767 }
768
769 #ifdef HAVE_FFTW
770 bool
771 ImageFile::fft (ImageFile& result) const
772 {
773   if (m_nx != result.nx() || m_ny != result.ny()) {
774     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
775     return false;
776   }
777   
778   if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
779     if (! result.convertRealToComplex ())
780       return false;
781   }
782   
783   fftw_complex* in = new fftw_complex [m_nx * m_ny];
784   
785   ImageFileArrayConst vReal = getArray();
786   ImageFileArrayConst vImag = getImaginaryArray();
787   
788   unsigned int ix, iy;
789   unsigned int iArray = 0;
790   for (ix = 0; ix < m_nx; ix++)
791     for (iy = 0; iy < m_ny; iy++) {
792       in[iArray].re = vReal[ix][iy];
793       if (isComplex())
794         in[iArray].im = vImag[ix][iy];
795       else
796         in[iArray].im = 0;
797       iArray++;
798     }
799     
800     fftwnd_plan plan = fftw2d_create_plan (m_nx, m_ny, FFTW_FORWARD, FFTW_IN_PLACE);
801     
802     fftwnd_one (plan, in, NULL);
803     
804     ImageFileArray vRealResult = result.getArray();
805     ImageFileArray vImagResult = result.getImaginaryArray();
806     iArray = 0;
807     unsigned int iScale = m_nx * m_ny;
808     for (ix = 0; ix < m_nx; ix++)
809       for (iy = 0; iy < m_ny; iy++) {
810         vRealResult[ix][iy] = in[iArray].re / iScale;
811         vImagResult[ix][iy] = in[iArray].im / iScale;
812         iArray++;
813       }
814       
815       fftwnd_destroy_plan (plan);
816       delete in;
817       
818       
819       Fourier::shuffleFourierToNaturalOrder (result);
820       
821       return true;
822 }
823
824
825 bool
826 ImageFile::ifft (ImageFile& result) const
827 {
828   if (m_nx != result.nx() || m_ny != result.ny()) {
829     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
830     return false;
831   }
832   
833   if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
834     if (! result.convertRealToComplex ())
835       return false;
836   }
837   
838   ImageFileArrayConst vReal = getArray();
839   ImageFileArrayConst vImag = getImaginaryArray();
840   ImageFileArray vRealResult = result.getArray();
841   ImageFileArray vImagResult = result.getImaginaryArray();
842   unsigned int ix, iy;
843   for (ix = 0; ix < m_nx; ix++)
844     for (iy = 0; iy < m_ny; iy++) {
845       vRealResult[ix][iy] = vReal[ix][iy];
846       if (isComplex()) 
847         vImagResult[ix][iy] = vImag[ix][iy];
848       else
849         vImagResult[ix][iy] = 0;
850     }
851     
852     Fourier::shuffleNaturalToFourierOrder (result);
853     
854     fftw_complex* in = new fftw_complex [m_nx * m_ny];
855     
856     unsigned int iArray = 0;
857     for (ix = 0; ix < m_nx; ix++)
858       for (iy = 0; iy < m_ny; iy++) {
859         in[iArray].re = vRealResult[ix][iy];
860         in[iArray].im = vImagResult[ix][iy];
861         iArray++;
862       }
863       
864       fftwnd_plan plan = fftw2d_create_plan (m_nx, m_ny, FFTW_BACKWARD, FFTW_IN_PLACE);
865       
866       fftwnd_one (plan, in, NULL);
867       
868       iArray = 0;
869       for (ix = 0; ix < m_nx; ix++)
870         for (iy = 0; iy < m_ny; iy++) {
871           vRealResult[ix][iy] = in[iArray].re;
872           vImagResult[ix][iy] = in[iArray].im;
873           iArray++;
874         }
875         
876         fftwnd_destroy_plan (plan);
877         
878         delete in;
879         
880         return true;
881 }
882
883 bool
884 ImageFile::fftRows (ImageFile& result) const
885 {
886   if (m_nx != result.nx() || m_ny != result.ny()) {
887     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::fftRows]");
888     return false;
889   }
890   
891   if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
892     if (! result.convertRealToComplex ())
893       return false;
894   }
895   
896   fftw_complex* in = new fftw_complex [m_nx];
897   
898   ImageFileArrayConst vReal = getArray();
899   ImageFileArrayConst vImag = getImaginaryArray();
900   
901   fftw_plan plan = fftw_create_plan (m_nx, FFTW_FORWARD, FFTW_IN_PLACE);
902   std::complex<double>* pcRow = new std::complex<double> [m_nx];
903   
904   unsigned int ix, iy;
905   unsigned int iArray = 0;
906   for (iy = 0; iy < m_ny; iy++) {
907     for (ix = 0; ix < m_nx; ix++) {
908       in[ix].re = vReal[ix][iy];
909       if (isComplex())
910         in[ix].im = vImag[ix][iy];
911       else
912         in[ix].im = 0;
913     }
914     
915     fftw_one (plan, in, NULL);
916     
917     for (ix = 0; ix < m_nx; ix++)
918       pcRow[ix] = std::complex<double>(in[ix].re, in[ix].im);
919     
920     Fourier::shuffleFourierToNaturalOrder (pcRow, m_nx);
921     for (ix = 0; ix < m_nx; ix++) {
922       vReal[ix][iy] = pcRow[ix].real();
923       vImag[ix][iy] = pcRow[ix].imag();
924     }
925   }
926   delete [] pcRow;
927   
928   fftw_destroy_plan (plan);
929   delete in;
930   
931   return true;
932 }     
933
934 bool
935 ImageFile::ifftRows (ImageFile& result) const
936 {
937   if (m_nx != result.nx() || m_ny != result.ny()) {
938     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::fftRows]");
939     return false;
940   }
941   
942   if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
943     if (! result.convertRealToComplex ())
944       return false;
945   }
946   
947   fftw_complex* in = new fftw_complex [m_nx];
948   
949   ImageFileArrayConst vReal = getArray();
950   ImageFileArrayConst vImag = getImaginaryArray();
951   
952   fftw_plan plan = fftw_create_plan (m_nx, FFTW_BACKWARD, FFTW_IN_PLACE);
953   std::complex<double>* pcRow = new std::complex<double> [m_nx];
954   
955   unsigned int ix, iy;
956   unsigned int iArray = 0;
957   for (iy = 0; iy < m_ny; iy++) {
958     for (ix = 0; ix < m_nx; ix++) {
959       double dImag = 0;
960       if (isComplex())
961         dImag = vImag[ix][iy];
962       pcRow[ix] = std::complex<double> (vReal[ix][iy], dImag);
963     }
964     
965     Fourier::shuffleNaturalToFourierOrder (pcRow, m_nx);
966     
967     for (ix = 0; ix < m_nx; ix++) {
968       in[ix].re = pcRow[ix].real();
969       in[ix].im = pcRow[ix].imag();
970     }
971     
972     fftw_one (plan, in, NULL);
973     
974     for (ix = 0; ix < m_nx; ix++) {
975       vReal[ix][iy] = in[ix].re;
976       vImag[ix][iy] = in[ix].im;
977     }
978   }
979   delete [] pcRow;
980   
981   fftw_destroy_plan (plan);
982   delete in;
983   
984   return true;
985 }
986
987 bool
988 ImageFile::fftCols (ImageFile& result) const
989 {
990   return false;
991 }
992
993 bool
994 ImageFile::ifftCols (ImageFile& result) const
995 {
996   return false;
997 }
998
999 #endif // HAVE_FFTW
1000
1001
1002
1003 bool
1004 ImageFile::fourier (ImageFile& result) const
1005 {
1006   if (m_nx != result.nx() || m_ny != result.ny()) {
1007     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
1008     return false;
1009   }
1010   
1011   if (! result.isComplex())
1012     if (! result.convertRealToComplex ())
1013       return false;
1014     
1015     ImageFileArrayConst vLHS = getArray();
1016     ImageFileArrayConst vLHSImag = getImaginaryArray();
1017     ImageFileArray vRealResult = result.getArray();
1018     ImageFileArray vImagResult = result.getImaginaryArray();
1019     
1020     unsigned int ix, iy;
1021     
1022     // alloc output matrix
1023     CTSimComplex** complexOut = new CTSimComplex* [m_nx];
1024     for (ix = 0; ix < m_nx; ix++)
1025       complexOut[ix] = new CTSimComplex [m_ny];
1026     
1027     // fourier each x column
1028     CTSimComplex* pY = new CTSimComplex [m_ny];
1029     for (ix = 0; ix < m_nx; ix++) {
1030       for (iy = 0; iy < m_ny; iy++) {
1031         double dImag = 0;
1032         if (isComplex())
1033           dImag = vLHSImag[ix][iy];
1034         pY[iy] = std::complex<double>(vLHS[ix][iy], dImag);
1035       } 
1036       ProcessSignal::finiteFourierTransform (pY, complexOut[ix], m_ny,  ProcessSignal::FORWARD);
1037     }
1038     delete [] pY;
1039     
1040     // fourier each y row
1041     CTSimComplex* pX = new CTSimComplex [m_nx];
1042     CTSimComplex* complexOutRow = new CTSimComplex [m_nx];
1043     for (iy = 0; iy < m_ny; iy++) {
1044       for (ix = 0; ix < m_nx; ix++)
1045         pX[ix] = complexOut[ix][iy];
1046       ProcessSignal::finiteFourierTransform (pX, complexOutRow, m_nx, ProcessSignal::FORWARD);
1047       for (ix = 0; ix < m_nx; ix++)
1048         complexOut[ix][iy] = complexOutRow[ix];
1049     }
1050     delete [] pX;
1051     delete [] complexOutRow;
1052     
1053     for (ix = 0; ix < m_nx; ix++)
1054       for (iy = 0; iy < m_ny; iy++) {
1055         vRealResult[ix][iy] = complexOut[ix][iy].real();
1056         vImagResult[ix][iy] = complexOut[ix][iy].imag();
1057       }
1058       
1059       Fourier::shuffleFourierToNaturalOrder (result);
1060       
1061       // delete complexOut matrix
1062       for (ix = 0; ix < m_nx; ix++)
1063         delete [] complexOut[ix];
1064       delete [] complexOut;
1065       
1066       return true;
1067 }
1068
1069 bool
1070 ImageFile::inverseFourier (ImageFile& result) const
1071 {
1072   if (m_nx != result.nx() || m_ny != result.ny()) {
1073     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
1074     return false;
1075   }
1076   
1077   if (result.dataType() == Array2dFile::DATA_TYPE_REAL) {
1078     if (! result.convertRealToComplex ())
1079       return false;
1080   }
1081   
1082   ImageFileArrayConst vLHSReal = getArray();
1083   ImageFileArrayConst vLHSImag = getImaginaryArray();
1084   ImageFileArray vRealResult = result.getArray();
1085   ImageFileArray vImagResult = result.getImaginaryArray();
1086   
1087   unsigned int ix, iy;
1088   // alloc 2d complex output matrix
1089   CTSimComplex** complexOut = new CTSimComplex* [m_nx];
1090   for (ix = 0; ix < m_nx; ix++)
1091     complexOut[ix] = new CTSimComplex [m_ny];
1092   
1093   // put input image into result
1094   for (ix = 0; ix < m_nx; ix++)
1095     for (iy = 0; iy < m_ny; iy++) {
1096       vRealResult[ix][iy] = vLHSReal[ix][iy];
1097       if (isComplex())
1098         vImagResult[ix][iy] = vLHSImag[ix][iy];
1099       else
1100         vImagResult[ix][iy] = 0;
1101     }
1102     
1103     Fourier::shuffleNaturalToFourierOrder (result);
1104     
1105     // ifourier each x column
1106     CTSimComplex* pCol = new CTSimComplex [m_ny];
1107     for (ix = 0; ix < m_nx; ix++) {
1108       for (iy = 0; iy < m_ny; iy++) {
1109         pCol[iy] = std::complex<double> (vRealResult[ix][iy], vImagResult[ix][iy]);
1110       }
1111       ProcessSignal::finiteFourierTransform (pCol, complexOut[ix], m_ny,  ProcessSignal::BACKWARD);
1112     }
1113     delete [] pCol;
1114     
1115     // ifourier each y row
1116     CTSimComplex* complexInRow = new CTSimComplex [m_nx];
1117     CTSimComplex* complexOutRow = new CTSimComplex [m_nx];
1118     for (iy = 0; iy < m_ny; iy++) {
1119       for (ix = 0; ix < m_nx; ix++)
1120         complexInRow[ix] = complexOut[ix][iy];
1121       ProcessSignal::finiteFourierTransform (complexInRow, complexOutRow, m_nx, ProcessSignal::BACKWARD);
1122       for (ix = 0; ix < m_nx; ix++)
1123         complexOut[ix][iy] = complexOutRow[ix];
1124     }
1125     delete [] complexInRow;
1126     delete [] complexOutRow;
1127     
1128     for (ix = 0; ix < m_nx; ix++)
1129       for (iy = 0; iy < m_ny; iy++) {
1130         vRealResult[ix][iy] = complexOut[ix][iy].real();
1131         vImagResult[ix][iy] = complexOut[ix][iy].imag();
1132       }
1133       
1134       // delete complexOut matrix
1135       for (ix = 0; ix < m_nx; ix++)
1136         delete [] complexOut[ix];
1137       delete [] complexOut;
1138       
1139       return true;
1140 }
1141
1142
1143 bool
1144 ImageFile::magnitude (ImageFile& result) const
1145 {
1146   if (m_nx != result.nx() || m_ny != result.ny()) {
1147     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
1148     return false;
1149   }
1150   
1151   ImageFileArray vReal = getArray();
1152   ImageFileArray vImag = getImaginaryArray();
1153   ImageFileArray vRealResult = result.getArray();
1154   
1155   for (unsigned int ix = 0; ix < m_nx; ix++)
1156     for (unsigned int iy = 0; iy < m_ny; iy++) {
1157       if (isComplex()) 
1158         vRealResult[ix][iy] = ::sqrt (vReal[ix][iy] * vReal[ix][iy] + vImag[ix][iy] * vImag[ix][iy]);
1159       else
1160         vRealResult[ix][iy] = vReal[ix][iy];
1161     }
1162     
1163     if (result.isComplex())
1164       result.convertComplexToReal();
1165     
1166     return true;
1167 }
1168
1169 bool
1170 ImageFile::phase (ImageFile& result) const
1171 {
1172   if (m_nx != result.nx() || m_ny != result.ny()) {
1173     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
1174     return false;
1175   }
1176   
1177   ImageFileArray vReal = getArray();
1178   ImageFileArray vImag = getImaginaryArray();
1179   ImageFileArray vRealResult = result.getArray();
1180   
1181   for (unsigned int ix = 0; ix < m_nx; ix++)
1182     for (unsigned int iy = 0; iy < m_ny; iy++) {
1183       if (isComplex())
1184         vRealResult[ix][iy] = ::atan2 (vImag[ix][iy], vReal[ix][iy]);
1185       else
1186         vRealResult[ix][iy] = 0;
1187     }
1188     
1189     if (result.isComplex())
1190       result.convertComplexToReal();
1191     
1192     return true;
1193 }
1194
1195 bool
1196 ImageFile::square (ImageFile& result) const
1197 {
1198   if (m_nx != result.nx() || m_ny != result.ny()) {
1199     sys_error (ERR_WARNING, "Difference sizes of images [ImageFile::invertPixelValues]");
1200     return false;
1201   }
1202   
1203   if (isComplex() && ! result.isComplex())
1204     result.convertRealToComplex();
1205   
1206   ImageFileArrayConst vLHS = getArray();
1207   ImageFileArrayConst vLHSImag = getImaginaryArray();
1208   ImageFileArray vResult = result.getArray();
1209   ImageFileArray vResultImag = result.getImaginaryArray();
1210   
1211   for (unsigned int ix = 0; ix < m_nx; ix++) {
1212     for (unsigned int iy = 0; iy < m_ny; iy++) {
1213       if (result.isComplex()) {
1214         double dImag = 0;
1215         if (isComplex())
1216           dImag = vLHSImag[ix][iy];
1217         std::complex<double> cLHS (vLHS[ix][iy], dImag);
1218         std::complex<double> cResult = cLHS * cLHS;
1219         vResult[ix][iy] = cResult.real();
1220         vResultImag[ix][iy] = cResult.imag();
1221       } else
1222         vResult[ix][iy] = vLHS[ix][iy] * vLHS[ix][iy];
1223     }
1224   }
1225   
1226   
1227   return true;
1228 }
1229
1230 int
1231 ImageFile::convertExportFormatNameToID (const char* const formatName)
1232 {
1233   int formatID = EXPORT_FORMAT_INVALID;
1234   
1235   for (int i = 0; i < s_iExportFormatCount; i++)
1236     if (strcasecmp (formatName, s_aszExportFormatName[i]) == 0) {
1237       formatID = i;
1238       break;
1239     }
1240     
1241     return (formatID);
1242 }
1243
1244 const char*
1245 ImageFile::convertExportFormatIDToName (int formatID)
1246 {
1247   static const char *formatName = "";
1248   
1249   if (formatID >= 0 && formatID < s_iExportFormatCount)
1250     return (s_aszExportFormatName[formatID]);
1251   
1252   return (formatName);
1253 }
1254
1255 const char*
1256 ImageFile::convertExportFormatIDToTitle (const int formatID)
1257 {
1258   static const char *formatTitle = "";
1259   
1260   if (formatID >= 0 && formatID < s_iExportFormatCount)
1261     return (s_aszExportFormatTitle[formatID]);
1262   
1263   return (formatTitle);
1264 }
1265
1266 int
1267 ImageFile::convertImportFormatNameToID (const char* const formatName)
1268 {
1269   int formatID = IMPORT_FORMAT_INVALID;
1270   
1271   for (int i = 0; i < s_iImportFormatCount; i++)
1272     if (strcasecmp (formatName, s_aszImportFormatName[i]) == 0) {
1273       formatID = i;
1274       break;
1275     }
1276     
1277     return (formatID);
1278 }
1279
1280 const char*
1281 ImageFile::convertImportFormatIDToName (int formatID)
1282 {
1283   static const char *formatName = "";
1284   
1285   if (formatID >= 0 && formatID < s_iImportFormatCount)
1286     return (s_aszImportFormatName[formatID]);
1287   
1288   return (formatName);
1289 }
1290
1291 const char*
1292 ImageFile::convertImportFormatIDToTitle (const int formatID)
1293 {
1294   static const char *formatTitle = "";
1295   
1296   if (formatID >= 0 && formatID < s_iImportFormatCount)
1297     return (s_aszImportFormatTitle[formatID]);
1298   
1299   return (formatTitle);
1300 }
1301
1302 bool
1303 ImageFile::importImage (const char* const pszFormat, const char* const pszFilename)
1304 {
1305   int iFormatID = convertImportFormatNameToID (pszFormat);
1306   
1307   if (iFormatID == IMPORT_FORMAT_PPM)
1308     return readImagePPM (pszFilename);
1309 #ifdef HAVE_PNG
1310   else if (iFormatID == IMPORT_FORMAT_PNG)
1311     return readImagePNG (pszFilename);
1312 #endif
1313 #ifdef HAVE_CTN_DICOM
1314   else if (iFormatID == IMPORT_FORMAT_DICOM)
1315     return readImageDicom (pszFilename);
1316 #endif
1317   
1318   sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::importImage]", pszFormat);
1319   return false;
1320 }
1321
1322 bool
1323 ImageFile::readImageDicom (const char* const pszFile)
1324 {
1325   return false;
1326 }
1327
1328 void
1329 ImageFile::skipSpacePPM (FILE* fp)
1330 {
1331   int c = fgetc (fp);
1332   while (isspace (c) || c == '#') {
1333     if (c == '#') {   // comment until end of line
1334       c = fgetc(fp);
1335       while (c != 13 && c != 10)
1336         c = fgetc(fp);
1337     }
1338     else
1339       c = fgetc(fp);
1340   }
1341   
1342   ungetc (c, fp);
1343 }
1344
1345 bool
1346 ImageFile::readImagePPM (const char* const pszFile)
1347 {
1348   FILE* fp = fopen (pszFile, "r");
1349   if ((fp = fopen (pszFile, "r")) == NULL)
1350     return false;
1351   char cSignature = toupper(fgetc(fp));
1352   if (cSignature != 'P') {
1353     fclose(fp);
1354     return false;
1355   }
1356   cSignature = fgetc(fp);
1357   if (cSignature == '5' || cSignature == '6') { // binary modes
1358     fclose(fp);
1359     fp = fopen(pszFile, "rb"); // reopen in binary mode
1360     fgetc(fp);
1361     fgetc(fp);
1362   } else if (cSignature != '2' && cSignature != '3') {
1363     fclose(fp);
1364     return false;
1365   }
1366   
1367   int nRows, nCols, iMaxValue;
1368   skipSpacePPM (fp); 
1369   if (fscanf (fp, "%d", &nCols) != 1) {
1370     fclose(fp);
1371     return false;
1372   }
1373   skipSpacePPM (fp);
1374   if (fscanf (fp, "%d", &nRows) != 1) {
1375     fclose(fp);
1376     return false;
1377   }
1378   skipSpacePPM (fp);
1379   if (fscanf (fp, "%d", &iMaxValue) != 1) {
1380     fclose(fp);
1381     return false;
1382   }
1383   setArraySize (nRows, nCols);
1384   
1385   if (cSignature == '5' || cSignature == '6') { // binary modes
1386     int c = fgetc(fp);
1387     if (c == 13) {
1388       c = fgetc(fp);
1389       if (c != 10)  // read msdos 13-10 newline
1390         ungetc(c, fp);
1391     }
1392   } else
1393     skipSpacePPM (fp); // ascii may have comments
1394   
1395   double dMaxValue = iMaxValue;
1396   ImageFileArray v = getArray();
1397   for (int iy = nRows - 1; iy >= 0; iy--) {
1398     for (int ix = 0; ix < nCols; ix++) {
1399       int iGS, iR, iG, iB;
1400       double dR, dG, dB;
1401       switch (cSignature) {
1402       case '2':
1403         if (fscanf(fp, "%d ", &iGS) != 1) {
1404           fclose(fp);
1405           return false;
1406         }
1407         v[ix][iy] = iGS / dMaxValue;
1408         break;
1409       case '5':
1410         iGS = fgetc(fp);
1411         if (iGS == EOF) {
1412           fclose(fp);
1413           return false;
1414         }
1415         v[ix][iy] = iGS / dMaxValue;
1416         break;
1417       case '3':
1418         if (fscanf (fp, "%d %d %d ", &iR, &iG, &iB) != 3) {
1419           fclose(fp);
1420           return false;
1421         }
1422         dR = iR / dMaxValue;
1423         dG = iG / dMaxValue;
1424         dB = iB / dMaxValue;
1425         v[ix][iy] = colorToGrayscale (dR, dG, dB);
1426         break;
1427       case '6':
1428         iR = fgetc(fp);
1429         iG = fgetc(fp);
1430         iB = fgetc(fp);
1431         if (iB == EOF) {
1432           fclose(fp);
1433           return false;
1434         }
1435         dR = iR / dMaxValue;
1436         dG = iG / dMaxValue;
1437         dB = iB / dMaxValue;
1438         v[ix][iy] = colorToGrayscale (dR, dG, dB);
1439         break;
1440       }
1441     }
1442   }
1443   
1444   fclose(fp);
1445   return true;
1446 }
1447
1448 #ifdef HAVE_PNG
1449 bool
1450 ImageFile::readImagePNG (const char* const pszFile)
1451 {
1452   FILE* fp = fopen(pszFile, "rb");
1453   if (!fp) 
1454     return false;
1455   unsigned char header[8];
1456   fread (header, 1, 8, fp);
1457   if (png_sig_cmp (header, 0, 8)) {
1458     fclose (fp);
1459     return false;
1460   }
1461   
1462   png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1463   if (!png_ptr) {
1464     fclose(fp);
1465     return false;
1466   }
1467   
1468   png_infop info_ptr = png_create_info_struct(png_ptr);
1469   if (!info_ptr) {
1470     png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
1471     fclose(fp);
1472     return false;
1473   }
1474   
1475   png_infop end_info = png_create_info_struct(png_ptr);
1476   if (!end_info) {
1477     png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
1478     fclose(fp);
1479     return false;
1480   }
1481   
1482   if (setjmp(png_ptr->jmpbuf)) {
1483     png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
1484     fclose(fp);
1485     return false;
1486   }
1487   
1488   png_init_io(png_ptr, fp);
1489   png_set_sig_bytes(png_ptr, 8);
1490   png_read_info(png_ptr, info_ptr);
1491   
1492   int width = png_get_image_width (png_ptr, info_ptr);
1493   int height = png_get_image_height (png_ptr, info_ptr);
1494   int bit_depth = png_get_bit_depth (png_ptr, info_ptr);
1495   int color_type = png_get_color_type (png_ptr, info_ptr);
1496   
1497   if (color_type == PNG_COLOR_TYPE_PALETTE && bit_depth <= 8) 
1498     png_set_expand(png_ptr);
1499   
1500   if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) 
1501     png_set_expand(png_ptr);
1502   
1503   if (bit_depth < 8)
1504     png_set_packing(png_ptr);
1505   
1506   if (color_type & PNG_COLOR_MASK_ALPHA)
1507     png_set_strip_alpha(png_ptr);
1508   
1509   if (bit_depth == 16)
1510     png_set_swap(png_ptr); // convert to little-endian format
1511   
1512   png_read_update_info(png_ptr, info_ptr); // update with transformations
1513   int rowbytes = png_get_rowbytes (png_ptr, info_ptr);
1514   bit_depth = png_get_bit_depth (png_ptr, info_ptr);
1515   color_type = png_get_color_type (png_ptr, info_ptr);
1516   
1517   png_bytep* row_pointers = new png_bytep [height];
1518   int i;
1519   for (i = 0; i < height; i++)
1520     row_pointers[i] = new unsigned char [rowbytes];
1521   
1522   png_read_image(png_ptr, row_pointers);
1523   
1524   setArraySize (width, height);
1525   ImageFileArray v = getArray();
1526   for (int iy = 0; iy < height; iy++) {
1527     for (int ix = 0; ix < width; ix++) {
1528       double dV;
1529       if (color_type == PNG_COLOR_TYPE_GRAY) {
1530         if (bit_depth == 8)
1531           dV = row_pointers[iy][ix] / 255.;
1532         else if (bit_depth == 16) {
1533           int iBase = ix * 2;
1534           dV = (row_pointers[iy][iBase] + (row_pointers[iy][iBase+1] << 8)) / 65536.;
1535         }
1536       } else if (color_type == PNG_COLOR_TYPE_RGB) {
1537         if (bit_depth == 8) {
1538           int iBase = ix * 3;
1539           double dR = row_pointers[iy][iBase] / 255.;
1540           double dG = row_pointers[iy][iBase+1] / 255.;
1541           double dB = row_pointers[iy][iBase+2] / 255.;
1542           dV = colorToGrayscale (dR, dG, dR);
1543         }
1544       }
1545       v[ix][height-iy-1] = dV;
1546     }
1547   }
1548   
1549   png_read_end(png_ptr, end_info);
1550   png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
1551   
1552   for (i = 0; i < height; i++)
1553     delete row_pointers[i];
1554   delete row_pointers;
1555   
1556   fclose (fp);
1557   return true;
1558 }
1559 #endif
1560
1561 bool
1562 ImageFile::exportImage (const char* const pszFormat, const char* const pszFilename, int nxcell, int nycell, double densmin, double densmax)
1563 {
1564   int iFormatID = convertExportFormatNameToID (pszFormat);
1565   
1566   if (iFormatID == EXPORT_FORMAT_PGM)
1567     return writeImagePGM (pszFilename, nxcell, nycell, densmin, densmax);
1568   else if (iFormatID == EXPORT_FORMAT_PGMASCII)
1569     return writeImagePGMASCII (pszFilename, nxcell, nycell, densmin, densmax);
1570   else if (iFormatID == EXPORT_FORMAT_PNG)
1571     return writeImagePNG (pszFilename, 8, nxcell, nycell, densmin, densmax);
1572   else if (iFormatID == EXPORT_FORMAT_PNG16)
1573     return writeImagePNG (pszFilename, 16, nxcell, nycell, densmin, densmax);
1574   
1575   sys_error (ERR_SEVERE, "Invalid format %s [ImageFile::exportImage]", pszFormat);
1576   return false;
1577 }
1578
1579
1580 bool
1581 ImageFile::writeImagePGM (const char* const outfile, int nxcell, int nycell, double densmin, double densmax)
1582 {
1583   FILE *fp;
1584   int nx = m_nx;
1585   int ny = m_ny;
1586   ImageFileArray v = getArray();
1587   
1588   unsigned char* rowp = new unsigned char [nx * nxcell];
1589   
1590   if ((fp = fopen (outfile, "wb")) == NULL)
1591     return false;
1592   
1593   fprintf(fp, "P5\n");
1594   fprintf(fp, "%d %d\n", nx, ny);
1595   fprintf(fp, "255\n");
1596   
1597   for (int irow = ny - 1; irow >= 0; irow--) {
1598     for (int icol = 0; icol < nx; icol++) {
1599       int pos = icol * nxcell;
1600       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
1601       dens = clamp (dens, 0., 1.);
1602       for (int p = pos; p < pos + nxcell; p++) {
1603         rowp[p] = static_cast<unsigned int> (dens * 255.);
1604       }
1605     }
1606     for (int ir = 0; ir < nycell; ir++) {
1607       for (int ic = 0; ic < nx * nxcell; ic++) 
1608         fputc( rowp[ic], fp );
1609     }
1610   }
1611   
1612   delete rowp;
1613   fclose(fp);
1614   
1615   return true;
1616 }
1617
1618 bool
1619 ImageFile::writeImagePGMASCII (const char* const outfile, int nxcell, int nycell, double densmin, double densmax)
1620 {
1621   FILE *fp;
1622   int nx = m_nx;
1623   int ny = m_ny;
1624   ImageFileArray v = getArray();
1625   
1626   unsigned char* rowp = new unsigned char [nx * nxcell];
1627   
1628   if ((fp = fopen (outfile, "wb")) == NULL)
1629     return false;
1630   
1631   fprintf(fp, "P2\n");
1632   fprintf(fp, "%d %d\n", nx, ny);
1633   fprintf(fp, "255\n");
1634   
1635   for (int irow = ny - 1; irow >= 0; irow--) {
1636     for (int icol = 0; icol < nx; icol++) {
1637       int pos = icol * nxcell;
1638       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
1639       dens = clamp (dens, 0., 1.);
1640       for (int p = pos; p < pos + nxcell; p++) {
1641         rowp[p] = static_cast<unsigned int> (dens * 255.);
1642       }
1643     }
1644     for (int ir = 0; ir < nycell; ir++) {
1645       for (int ic = 0; ic < nx * nxcell; ic++) 
1646         fprintf(fp, "%d ", rowp[ic]);
1647       fprintf(fp, "\n");
1648     }
1649   }
1650   
1651   delete rowp;
1652   fclose(fp);
1653   
1654   return true;
1655 }
1656
1657
1658 #ifdef HAVE_PNG
1659 bool
1660 ImageFile::writeImagePNG (const char* const outfile, int bitdepth, int nxcell, int nycell, double densmin, double densmax)
1661 {
1662   double max_out_level = (1 << bitdepth) - 1;
1663   int nx = m_nx;
1664   int ny = m_ny;
1665   ImageFileArray v = getArray();
1666   
1667   unsigned char* rowp = new unsigned char [nx * nxcell * (bitdepth / 8)];
1668   
1669   FILE *fp = fopen (outfile, "wb");
1670   if (! fp)
1671     return false;
1672   
1673   png_structp png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1674   if (! png_ptr)
1675     return false;
1676   
1677   png_infop info_ptr = png_create_info_struct (png_ptr);
1678   if (! info_ptr) {
1679     png_destroy_write_struct (&png_ptr, (png_infopp) NULL);
1680     fclose (fp);
1681     return false;
1682   }
1683   
1684   if (setjmp (png_ptr->jmpbuf)) {
1685     png_destroy_write_struct (&png_ptr, &info_ptr);
1686     fclose (fp);
1687     return false;
1688   }
1689   
1690   png_init_io(png_ptr, fp);
1691   
1692   png_set_IHDR (png_ptr, info_ptr, nx * nxcell, ny * nycell, bitdepth, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_DEFAULT);
1693   
1694   png_write_info(png_ptr, info_ptr);
1695   for (int irow = ny - 1; irow >= 0; irow--) {
1696     png_bytep row_pointer = rowp;
1697     
1698     for (int icol = 0; icol < nx; icol++) {
1699       int pos = icol * nxcell;
1700       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
1701       dens = clamp (dens, 0., 1.);
1702       unsigned int outval = static_cast<unsigned int> (dens * max_out_level);
1703       
1704       for (int p = pos; p < pos + nxcell; p++) {
1705         if (bitdepth == 8)
1706           rowp[p] = outval;
1707         else {
1708           int rowpos = p * 2;
1709           rowp[rowpos+1] = (outval >> 8) & 0xFF;
1710           rowp[rowpos] = (outval & 0xFF);
1711         }
1712       }
1713     }
1714     for (int ir = 0; ir < nycell; ir++)
1715       png_write_rows (png_ptr, &row_pointer, 1);
1716   }
1717   
1718   png_write_end (png_ptr, info_ptr);
1719   png_destroy_write_struct (&png_ptr, &info_ptr);
1720   delete rowp;
1721   
1722   fclose(fp);
1723   
1724   return true;
1725 }
1726 #endif
1727
1728 #ifdef HAVE_GD
1729 #include "gd.h"
1730 static const int N_GRAYSCALE=256;
1731
1732 bool
1733 ImageFile::writeImageGIF (const char* const outfile, int nxcell, int nycell, double densmin, double densmax)
1734 {
1735   int gs_indices[N_GRAYSCALE];
1736   int nx = m_nx;
1737   int ny = m_ny;
1738   ImageFileArray v = getArray();
1739   
1740   unsigned char* rowp = new unsigned char [nx * nxcell];
1741   
1742   gdImagePtr gif = gdImageCreate(nx * nxcell, ny * nycell);
1743   for (int i = 0; i < N_GRAYSCALE; i++)
1744     gs_indices[i] = gdImageColorAllocate(gif, i, i, i);
1745   
1746   int lastrow = ny * nycell - 1;
1747   for (int irow = 0; irow < ny; irow++) {
1748     int rpos = irow * nycell;
1749     for (int ir = rpos; ir < rpos + nycell; ir++) {
1750       for (int icol = 0; icol < nx; icol++) {
1751         int cpos = icol * nxcell;
1752         double dens = (v[icol][irow] - densmin) / (densmax - densmin);
1753         dens = clamp(dens, 0., 1.);
1754         for (int ic = cpos; ic < cpos + nxcell; ic++) {
1755           rowp[ic] = (unsigned int) (dens * (double) (N_GRAYSCALE - 1));
1756           gdImageSetPixel(gif, ic, lastrow - ir, gs_indices[rowp[ic]]);
1757         }
1758       }
1759     }
1760   }
1761   
1762   FILE *out;
1763   if ((out = fopen (outfile,"w")) == NULL) {
1764     sys_error(ERR_SEVERE, "Error opening output file %s for writing", outfile);
1765     return false;
1766   }
1767   gdImageGif(gif,out);
1768   fclose(out);
1769   gdImageDestroy(gif);
1770   
1771   delete rowp;
1772   
1773   return true;
1774 }
1775 #endif
1776