1b1660dc0375653a4665d990612a11fc89e76140
[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.9 2000/07/15 08:36: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 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 = 256;
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     median = 0.;
249 }
250
251
252 void
253 ImageFile::getMinMax (double& min, double& max) const
254 {
255     int nx = m_nx;
256     int ny = m_ny;
257     ImageFileArrayConst v = getArray();
258     
259     if (v == NULL || nx == 0 || ny == 0)
260       return;
261
262     min = v[0][0];
263     max = v[0][0];
264     for (int ix = 0; ix < nx; ix++) {
265       for (int iy = 0; iy < ny; iy++) {
266         if (v[ix][iy] > max)
267           max = v[ix][iy];
268         if (v[ix][iy] < min)
269           min = v[ix][iy];
270       }
271     }
272 }
273
274 void 
275 ImageFile::writeImagePGM (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
276 {
277   FILE *fp;
278   int nx = m_nx;
279   int ny = m_ny;
280   ImageFileArray v = getArray();
281
282   unsigned char rowp [nx * nxcell];
283
284   if ((fp = fopen (outfile, "wb")) == NULL)
285      return;
286
287   fprintf(fp, "P5\n");
288   fprintf(fp, "%d %d\n", nx, ny);
289   fprintf(fp, "255\n");
290
291   for (int irow = ny - 1; irow >= 0; irow--) {
292     for (int icol = 0; icol < nx; icol++) {
293       int pos = icol * nxcell;
294       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
295       dens = clamp (dens, 0., 1.);
296       for (int p = pos; p < pos + nxcell; p++) {
297         rowp[p] = static_cast<unsigned int> (dens * 255.);
298       }
299     }
300     for (int ir = 0; ir < nycell; ir++) {
301       for (int ic = 0; ic < nx * nxcell; ic++) 
302         fprintf(fp, "%c ", rowp[ic]);
303     }
304   }
305
306   fclose(fp);
307 }
308
309 void 
310 ImageFile::writeImagePGMASCII (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
311 {
312   FILE *fp;
313   int nx = m_nx;
314   int ny = m_ny;
315   ImageFileArray v = getArray();
316
317   unsigned char rowp [nx * nxcell];
318   if (rowp == NULL)
319     return;
320
321   if ((fp = fopen (outfile, "wb")) == NULL)
322      return;
323
324   fprintf(fp, "P2\n");
325   fprintf(fp, "%d %d\n", nx, ny);
326   fprintf(fp, "255\n");
327
328   for (int irow = ny - 1; irow >= 0; irow--) {
329     for (int icol = 0; icol < nx; icol++) {
330       int pos = icol * nxcell;
331       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
332       dens = clamp (dens, 0., 1.);
333       for (int p = pos; p < pos + nxcell; p++) {
334         rowp[p] = static_cast<unsigned int> (dens * 255.);
335       }
336     }
337     for (int ir = 0; ir < nycell; ir++) {
338       for (int ic = 0; ic < nx * nxcell; ic++) 
339         fprintf(fp, "%d ", rowp[ic]);
340       fprintf(fp, "\n");
341     }
342   }
343
344   fclose(fp);
345 }
346
347
348 #ifdef HAVE_PNG
349 void 
350 ImageFile::writeImagePNG (const char *outfile, int bitdepth, int nxcell, int nycell, double densmin, double densmax)
351 {
352   FILE *fp;
353   png_structp png_ptr;
354   png_infop info_ptr;
355   double max_out_level = (1 << bitdepth) - 1;
356   int nx = m_nx;
357   int ny = m_ny;
358   ImageFileArray v = getArray();
359
360   unsigned char rowp [nx * nxcell * (bitdepth / 8)];
361
362   if ((fp = fopen (outfile, "wb")) == NULL)
363      return;
364
365   png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
366   if (! png_ptr)
367     return;
368
369   info_ptr = png_create_info_struct(png_ptr);
370   if (! info_ptr) {
371     png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
372     fclose(fp);
373     return;
374   }
375
376   if (setjmp(png_ptr->jmpbuf)) {
377     png_destroy_write_struct(&png_ptr, &info_ptr);
378     fclose(fp);
379     return;
380   }
381
382   png_init_io(png_ptr, fp);
383
384   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);
385
386   png_write_info(png_ptr, info_ptr);
387   for (int irow = ny - 1; irow >= 0; irow--) {
388     png_bytep row_pointer = rowp;
389     
390     for (int icol = 0; icol < nx; icol++) {
391       int pos = icol * nxcell;
392       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
393       dens = clamp (dens, 0., 1.);
394       unsigned int outval = static_cast<unsigned int> (dens * max_out_level);
395
396       for (int p = pos; p < pos + nxcell; p++) {
397         if (bitdepth == 8)
398           rowp[p] = outval;
399         else {
400           int rowpos = p * 2;
401           rowp[rowpos] = (outval >> 8) & 0xFF;
402           rowp[rowpos+1] = (outval & 0xFF);
403         }
404       }
405     }
406     for (int ir = 0; ir < nycell; ir++)
407       png_write_rows (png_ptr, &row_pointer, 1);
408   }
409
410   png_write_end(png_ptr, info_ptr);
411   png_destroy_write_struct(&png_ptr, &info_ptr);
412
413   fclose(fp);
414 }
415 #endif
416
417 #ifdef HAVE_GD
418 #include "gd.h"
419 static const int N_GRAYSCALE=256;
420
421 void
422 ImageFile::writeImageGIF (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
423 {
424   gdImagePtr gif;
425   FILE *out;
426   int gs_indices[N_GRAYSCALE];
427   int nx = m_nx;
428   int ny = m_ny;
429   ImageFileArray v = getArray();
430
431   unsigned char rowp [nx * nxcell];
432   if (rowp == NULL)
433     return;
434
435   gif = gdImageCreate(nx * nxcell, ny * nycell);
436   for (int i = 0; i < N_GRAYSCALE; i++)
437     gs_indices[i] = gdImageColorAllocate(gif, i, i, i);
438
439   int lastrow = ny * nycell - 1;
440   for (int irow = 0; irow < ny; irow++) {
441     int rpos = irow * nycell;
442     for (int ir = rpos; ir < rpos + nycell; ir++) {
443       for (int icol = 0; icol < nx; icol++) {
444         int cpos = icol * nxcell;
445         double dens = (v[icol][irow] - densmin) / (densmax - densmin);
446         dens = clamp(dens, 0., 1.);
447         for (int ic = cpos; ic < cpos + nxcell; ic++) {
448           rowp[ic] = (unsigned int) (dens * (double) (N_GRAYSCALE - 1));
449           gdImageSetPixel(gif, ic, lastrow - ir, gs_indices[rowp[ic]]);
450         }
451       }
452     }
453   }
454
455   if ((out = fopen(outfile,"w")) == NULL) {
456     sys_error(ERR_FATAL, "Error opening output file %s for writing", outfile);
457     return (1);
458   }
459   gdImageGif(gif,out);
460   fclose(out);
461   gdImageDestroy(gif);
462 }
463 #endif
464