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