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