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