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