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