r244: *** empty log message ***
[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-2000 Kevin Rosenberg
11 **
12 **  $Id: imagefile.cpp,v 1.16 2000/12/04 05:36:57 kevin Exp $
13 **
14 **  This program is free software; you can redistribute it and/or modify
15 **  it under the terms of the GNU General Public License (version 2) as
16 **  published by the Free Software Foundation.
17 **
18 **  This program is distributed in the hope that it will be useful,
19 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
20 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 **  GNU General Public License for more details.
22 **
23 **  You should have received a copy of the GNU General Public License
24 **  along with this program; if not, write to the Free Software
25 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26 ******************************************************************************/
27
28 #include "ct.h"
29
30
31 F32Image::F32Image (int nx, int ny)\r
32       : Array2dFile::Array2dFile (nx, ny, sizeof(kfloat32), Array2dFile::PIXEL_FLOAT32)\r
33   {\r
34   }\r
35 \r
36 F32Image::F32Image (void)[\r
37       : Array2dFile::Array2dFile()\r
38   {\r
39       setPixelFormat (Array2dFile::PIXEL_FLOAT32);\r
40       setPixelSize (sizeof(kfloat32));\r
41   }\r
42 \r
43 F64Image::F64Image (int nx, int ny)\r
44       : Array2dFile::Array2dFile (nx, ny, sizeof(kfloat64), Array2dFile::PIXEL_FLOAT64)\r
45   {\r
46   }\r
47 \r
48 F64Image::F64Image (void)\r
49       : Array2dFile::Array2dFile ()\r
50   {\r
51       setPixelFormat (PIXEL_FLOAT64);\r
52       setPixelSize (sizeof(kfloat64));\r
53   }\r
54
55 void 
56 ImageFile::filterResponse (const char* const domainName, double bw, const char* const filterName, double filt_param)
57 {
58   int hx = (m_nx - 1) / 2;
59   int hy = (m_ny - 1) / 2;
60   ImageFileArray v = getArray();
61   SignalFilter filter (filterName, domainName, bw, filt_param);
62
63   for (int i = -hx; i <= hx; i++) {
64     for (int j = -hy; j <= hy; j++) {
65       double r = sqrt (i * i + j * j);
66       
67       v[i+hx][j+hy] = filter.response (r);
68     }
69   }
70 }
71
72 int
73 ImageFile::display (void) const
74 {
75     double pmin, pmax;
76
77     getMinMax (pmin, pmax);
78
79     return (displayScaling (1, pmin, pmax));
80 }
81
82 int 
83 ImageFile::displayScaling (const int scale, const ImageFileValue pmin, const ImageFileValue pmax) const
84 {
85     int nx = m_nx;
86     int ny = m_ny;
87     ImageFileArrayConst v = getArray();
88     if (v == NULL || nx == 0 || ny == 0)
89       return 0;
90
91 #if HAVE_G2_H
92     int* pPens = new int [nx * ny * scale * scale ];
93
94     double view_scale = 255 / (pmax - pmin);
95     int id_X11 = g2_open_X11 (nx * scale, ny * scale);
96     int grayscale[256];
97     for (int i = 0; i < 256; i++) {
98         double cval = i / 255.;
99         grayscale[i] = g2_ink (id_X11, cval, cval, cval);
100     }
101
102     for (int iy = ny - 1; iy >= 0; iy--) {
103       int iRowPos = ((ny - 1 - iy) * scale) * (nx * scale);
104       for (int ix = 0; ix < nx; ix++) {
105         int cval = static_cast<int>((v[ix][iy] - pmin) * view_scale);
106         if (cval < 0)  
107           cval = 0;
108         else if (cval > 255) 
109           cval = 255;
110         for (int sy = 0; sy < scale; sy++)
111           for (int sx = 0; sx < scale; sx++)
112             pPens[iRowPos+(sy * nx * scale)+(sx + (ix * scale))] = grayscale[cval];
113         }
114     }
115
116     g2_image (id_X11, 0., 0., nx * scale, ny * scale, pPens);
117
118     delete pPens;
119     return (id_X11);
120 #else
121     return 0;
122 #endif
123 }
124
125
126
127 // ImageFile::comparativeStatistics    Calculate comparative stats
128 //
129 // OUTPUT
130 //   d   Normalized root mean squared distance measure
131 //   r   Normalized mean absolute distance measure
132 //   e   Worst case distance measure
133 //
134 // REFERENCES
135 //  G.T. Herman, Image Reconstruction From Projections, 1980
136
137 bool
138 ImageFile::comparativeStatistics (const ImageFile& imComp, double& d, double& r, double& e) const
139 {
140     if (imComp.nx() != m_nx && imComp.ny() != m_ny) {
141         sys_error (ERR_WARNING, "Image sizes differ [ImageFile::comparativeStatistics]");
142         return false;
143     }
144     ImageFileArrayConst v = getArray();
145     if (v == NULL || m_nx == 0 || m_ny == 0)
146       return false;
147
148     ImageFileArrayConst vComp = imComp.getArray();
149
150     double myMean = 0.;
151     for (unsigned int ix = 0; ix < m_nx; ix++) {
152         for (unsigned int iy = 0; iy < m_ny; iy++) {
153             myMean += v[ix][iy];
154         }
155     }
156     myMean /= (m_nx * m_ny);
157
158     double sqErrorSum = 0.;
159     double absErrorSum = 0.;
160     double sqDiffFromMeanSum = 0.;
161     double absValueSum = 0.;
162     for (unsigned int ix = 0; ix < m_nx; ix++) {
163         for (unsigned int iy = 0; iy < m_ny; iy++) {
164             double diff = v[ix][iy] - vComp[ix][iy];
165             sqErrorSum += diff * diff;
166             absErrorSum += fabs(diff);
167             double diffFromMean = v[ix][iy] - myMean;
168             sqDiffFromMeanSum += diffFromMean * diffFromMean;
169             absValueSum += fabs(v[ix][iy]);
170         }
171     }
172
173     d = sqrt (sqErrorSum / sqDiffFromMeanSum);
174     r = absErrorSum / absValueSum;
175
176     int hx = m_nx / 2;
177     int hy = m_ny / 2;
178     double eMax = -1;
179     for (int ix = 0; ix < hx; ix++) {
180       for (int iy = 0; iy < hy; iy++) {
181         double avgPixel = 0.25 * (v[2*ix][2*iy] + v[2*ix+1][2*iy] + v[2*ix][2*iy+1] + v[2*ix+1][2*iy+1]);
182         double avgPixelComp = 0.25 * (vComp[2*ix][2*iy] + vComp[2*ix+1][2*iy] + vComp[2*ix][2*iy+1] + vComp[2*ix+1][2*iy+1]);
183         double error = fabs (avgPixel - avgPixelComp);
184         if (error > eMax)
185           eMax = error;
186       }
187     }
188
189     e = eMax;
190
191     return true;
192 }
193
194
195 bool
196 ImageFile::printComparativeStatistics (const ImageFile& imComp, ostream& os) const
197 {
198   double d, r, e;
199
200   if (comparativeStatistics (imComp, d, r, e)) {
201     os << "  Normalized root mean squared distance (d): " << d << endl;
202     os << "      Normalized mean absolute distance (r): " << r << endl;
203     os << "Worst case distance (2x2 pixel average) (e): " << e << endl;
204     return true;
205   }
206   return false;
207 }
208
209
210 void
211 ImageFile::printStatistics (ostream& os) const
212 {
213     double min, max, mean, mode, median, stddev;
214
215     statistics (min, max, mean, mode, median, stddev);
216
217     os << "   min: " << min << endl;
218     os << "   max: " << max << endl;
219     os << "  mean: " << mean << endl;
220     os << "  mode: " << mode << endl;
221     os << "median: " << median << endl;
222     os << "stddev: " << stddev << endl;
223 }
224
225
226 void
227 ImageFile::statistics (double& min, double& max, double& mean, double& mode, double& median, double& stddev) const
228 {
229     int nx = m_nx;
230     int ny = m_ny;
231     ImageFileArrayConst v = getArray();
232     
233     if (v == NULL || nx == 0 || ny == 0)
234       return;
235
236     mean = 0;
237     min = v[0][0];
238     max = v[0][0];
239     for (int ix = 0; ix < nx; ix++) {
240       for (int iy = 0; iy < ny; iy++) {
241         if (v[ix][iy] > max)
242           max = v[ix][iy];
243         if (v[ix][iy] < min)
244           min = v[ix][iy];
245         mean += v[ix][iy];
246       }
247     }
248     mean /= (nx * ny);
249
250     static const int nbin = 1024;
251     int hist[ nbin ] = {0};
252     double spread = max - min;
253     mode = 0;
254     stddev = 0;
255     for (int ix = 0; ix < nx; ix++) {
256       for (int iy = 0; iy < ny; iy++) {
257         int b = static_cast<int>((((v[ix][iy] - min) / spread) * (nbin - 1)) + 0.5);
258         hist[b]++;
259         double diff = (v[ix][iy] - mean);
260         stddev += diff * diff;
261         }
262     }
263     stddev = sqrt(stddev / (nx * ny));
264
265     int max_binindex = 0;
266     int max_bin = -1;
267     for (int ibin = 0; ibin < nbin; ibin++) {
268       if (hist[ibin] > max_bin) {
269         max_bin = hist[ibin];
270         max_binindex = ibin;
271       }
272     }
273
274     mode = (max_binindex * spread / (nbin - 1)) + min;
275
276     int nPixels = nx * ny;
277     slist<double> vecImage;
278     for (int ix = 0; ix < nx; ix++)
279       for (int iy = 0; iy < ny; iy++)
280         vecImage.push_front (v[ix][iy]);
281     vecImage.sort();
282     slist<double>::const_iterator iter = vecImage.begin();
283     for (int i = 0; i < (nPixels / 2) - 1; i++)
284       iter++; // Advance iterator to (nPixels / 2) - 1;
285
286     if (nPixels % 2) {  // Odd
287       iter++;
288       median = *iter;
289     } else                // Even
290       median = (*iter++ + *iter) / 2;
291 }
292
293
294 void
295 ImageFile::getMinMax (double& min, double& max) const
296 {
297     int nx = m_nx;
298     int ny = m_ny;
299     ImageFileArrayConst v = getArray();
300     
301     if (v == NULL || nx == 0 || ny == 0)
302       return;
303
304     min = v[0][0];
305     max = v[0][0];
306     for (int ix = 0; ix < nx; ix++) {
307       for (int iy = 0; iy < ny; iy++) {
308         if (v[ix][iy] > max)
309           max = v[ix][iy];
310         if (v[ix][iy] < min)
311           min = v[ix][iy];
312       }
313     }
314 }
315
316 void 
317 ImageFile::writeImagePGM (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
318 {
319   FILE *fp;
320   int nx = m_nx;
321   int ny = m_ny;
322   ImageFileArray v = getArray();
323
324   unsigned char rowp [nx * nxcell];
325
326   if ((fp = fopen (outfile, "wb")) == NULL)
327      return;
328
329   fprintf(fp, "P5\n");
330   fprintf(fp, "%d %d\n", nx, ny);
331   fprintf(fp, "255\n");
332
333   for (int irow = ny - 1; irow >= 0; irow--) {
334     for (int icol = 0; icol < nx; icol++) {
335       int pos = icol * nxcell;
336       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
337       dens = clamp (dens, 0., 1.);
338       for (int p = pos; p < pos + nxcell; p++) {
339         rowp[p] = static_cast<unsigned int> (dens * 255.);
340       }
341     }
342     for (int ir = 0; ir < nycell; ir++) {
343       for (int ic = 0; ic < nx * nxcell; ic++) 
344         fputc( rowp[ic], fp );
345     }
346   }
347
348   fclose(fp);
349 }
350
351 void 
352 ImageFile::writeImagePGMASCII (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
353 {
354   FILE *fp;
355   int nx = m_nx;
356   int ny = m_ny;
357   ImageFileArray v = getArray();
358
359   unsigned char rowp [nx * nxcell];
360
361   if ((fp = fopen (outfile, "wb")) == NULL)
362      return;
363
364   fprintf(fp, "P2\n");
365   fprintf(fp, "%d %d\n", nx, ny);
366   fprintf(fp, "255\n");
367
368   for (int irow = ny - 1; irow >= 0; irow--) {
369     for (int icol = 0; icol < nx; icol++) {
370       int pos = icol * nxcell;
371       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
372       dens = clamp (dens, 0., 1.);
373       for (int p = pos; p < pos + nxcell; p++) {
374         rowp[p] = static_cast<unsigned int> (dens * 255.);
375       }
376     }
377     for (int ir = 0; ir < nycell; ir++) {
378       for (int ic = 0; ic < nx * nxcell; ic++) 
379         fprintf(fp, "%d ", rowp[ic]);
380       fprintf(fp, "\n");
381     }
382   }
383
384   fclose(fp);
385 }
386
387
388 #ifdef HAVE_PNG
389 void 
390 ImageFile::writeImagePNG (const char *outfile, int bitdepth, int nxcell, int nycell, double densmin, double densmax)
391 {
392   FILE *fp;
393   png_structp png_ptr;
394   png_infop info_ptr;
395   double max_out_level = (1 << bitdepth) - 1;
396   int nx = m_nx;
397   int ny = m_ny;
398   ImageFileArray v = getArray();
399
400   unsigned char rowp [nx * nxcell * (bitdepth / 8)];
401
402   if ((fp = fopen (outfile, "wb")) == NULL)
403      return;
404
405   png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
406   if (! png_ptr)
407     return;
408
409   info_ptr = png_create_info_struct(png_ptr);
410   if (! info_ptr) {
411     png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
412     fclose(fp);
413     return;
414   }
415
416   if (setjmp(png_ptr->jmpbuf)) {
417     png_destroy_write_struct(&png_ptr, &info_ptr);
418     fclose(fp);
419     return;
420   }
421
422   png_init_io(png_ptr, fp);
423
424   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);
425
426   png_write_info(png_ptr, info_ptr);
427   for (int irow = ny - 1; irow >= 0; irow--) {
428     png_bytep row_pointer = rowp;
429     
430     for (int icol = 0; icol < nx; icol++) {
431       int pos = icol * nxcell;
432       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
433       dens = clamp (dens, 0., 1.);
434       unsigned int outval = static_cast<unsigned int> (dens * max_out_level);
435
436       for (int p = pos; p < pos + nxcell; p++) {
437         if (bitdepth == 8)
438           rowp[p] = outval;
439         else {
440           int rowpos = p * 2;
441           rowp[rowpos] = (outval >> 8) & 0xFF;
442           rowp[rowpos+1] = (outval & 0xFF);
443         }
444       }
445     }
446     for (int ir = 0; ir < nycell; ir++)
447       png_write_rows (png_ptr, &row_pointer, 1);
448   }
449
450   png_write_end(png_ptr, info_ptr);
451   png_destroy_write_struct(&png_ptr, &info_ptr);
452
453   fclose(fp);
454 }
455 #endif
456
457 #ifdef HAVE_GD
458 #include "gd.h"
459 static const int N_GRAYSCALE=256;
460
461 void
462 ImageFile::writeImageGIF (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
463 {
464   gdImagePtr gif;
465   FILE *out;
466   int gs_indices[N_GRAYSCALE];
467   int nx = m_nx;
468   int ny = m_ny;
469   ImageFileArray v = getArray();
470
471   unsigned char rowp [nx * nxcell];
472   if (rowp == NULL)
473     return;
474
475   gif = gdImageCreate(nx * nxcell, ny * nycell);
476   for (int i = 0; i < N_GRAYSCALE; i++)
477     gs_indices[i] = gdImageColorAllocate(gif, i, i, i);
478
479   int lastrow = ny * nycell - 1;
480   for (int irow = 0; irow < ny; irow++) {
481     int rpos = irow * nycell;
482     for (int ir = rpos; ir < rpos + nycell; ir++) {
483       for (int icol = 0; icol < nx; icol++) {
484         int cpos = icol * nxcell;
485         double dens = (v[icol][irow] - densmin) / (densmax - densmin);
486         dens = clamp(dens, 0., 1.);
487         for (int ic = cpos; ic < cpos + nxcell; ic++) {
488           rowp[ic] = (unsigned int) (dens * (double) (N_GRAYSCALE - 1));
489           gdImageSetPixel(gif, ic, lastrow - ir, gs_indices[rowp[ic]]);
490         }
491       }
492     }
493   }
494
495   if ((out = fopen(outfile,"w")) == NULL) {
496     sys_error(ERR_FATAL, "Error opening output file %s for writing", outfile);
497     return (1);
498   }
499   gdImageGif(gif,out);
500   fclose(out);
501   gdImageDestroy(gif);
502 }
503 #endif
504