r207: *** 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.14 2000/11/22 07:17:06 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
338   if ((fp = fopen (outfile, "wb")) == NULL)
339      return;
340
341   fprintf(fp, "P2\n");
342   fprintf(fp, "%d %d\n", nx, ny);
343   fprintf(fp, "255\n");
344
345   for (int irow = ny - 1; irow >= 0; irow--) {
346     for (int icol = 0; icol < nx; icol++) {
347       int pos = icol * nxcell;
348       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
349       dens = clamp (dens, 0., 1.);
350       for (int p = pos; p < pos + nxcell; p++) {
351         rowp[p] = static_cast<unsigned int> (dens * 255.);
352       }
353     }
354     for (int ir = 0; ir < nycell; ir++) {
355       for (int ic = 0; ic < nx * nxcell; ic++) 
356         fprintf(fp, "%d ", rowp[ic]);
357       fprintf(fp, "\n");
358     }
359   }
360
361   fclose(fp);
362 }
363
364
365 #ifdef HAVE_PNG
366 void 
367 ImageFile::writeImagePNG (const char *outfile, int bitdepth, int nxcell, int nycell, double densmin, double densmax)
368 {
369   FILE *fp;
370   png_structp png_ptr;
371   png_infop info_ptr;
372   double max_out_level = (1 << bitdepth) - 1;
373   int nx = m_nx;
374   int ny = m_ny;
375   ImageFileArray v = getArray();
376
377   unsigned char rowp [nx * nxcell * (bitdepth / 8)];
378
379   if ((fp = fopen (outfile, "wb")) == NULL)
380      return;
381
382   png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
383   if (! png_ptr)
384     return;
385
386   info_ptr = png_create_info_struct(png_ptr);
387   if (! info_ptr) {
388     png_destroy_write_struct(&png_ptr, (png_infopp) NULL);
389     fclose(fp);
390     return;
391   }
392
393   if (setjmp(png_ptr->jmpbuf)) {
394     png_destroy_write_struct(&png_ptr, &info_ptr);
395     fclose(fp);
396     return;
397   }
398
399   png_init_io(png_ptr, fp);
400
401   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);
402
403   png_write_info(png_ptr, info_ptr);
404   for (int irow = ny - 1; irow >= 0; irow--) {
405     png_bytep row_pointer = rowp;
406     
407     for (int icol = 0; icol < nx; icol++) {
408       int pos = icol * nxcell;
409       double dens = (v[icol][irow] - densmin) / (densmax - densmin);
410       dens = clamp (dens, 0., 1.);
411       unsigned int outval = static_cast<unsigned int> (dens * max_out_level);
412
413       for (int p = pos; p < pos + nxcell; p++) {
414         if (bitdepth == 8)
415           rowp[p] = outval;
416         else {
417           int rowpos = p * 2;
418           rowp[rowpos] = (outval >> 8) & 0xFF;
419           rowp[rowpos+1] = (outval & 0xFF);
420         }
421       }
422     }
423     for (int ir = 0; ir < nycell; ir++)
424       png_write_rows (png_ptr, &row_pointer, 1);
425   }
426
427   png_write_end(png_ptr, info_ptr);
428   png_destroy_write_struct(&png_ptr, &info_ptr);
429
430   fclose(fp);
431 }
432 #endif
433
434 #ifdef HAVE_GD
435 #include "gd.h"
436 static const int N_GRAYSCALE=256;
437
438 void
439 ImageFile::writeImageGIF (const char *outfile, int nxcell, int nycell, double densmin, double densmax)
440 {
441   gdImagePtr gif;
442   FILE *out;
443   int gs_indices[N_GRAYSCALE];
444   int nx = m_nx;
445   int ny = m_ny;
446   ImageFileArray v = getArray();
447
448   unsigned char rowp [nx * nxcell];
449   if (rowp == NULL)
450     return;
451
452   gif = gdImageCreate(nx * nxcell, ny * nycell);
453   for (int i = 0; i < N_GRAYSCALE; i++)
454     gs_indices[i] = gdImageColorAllocate(gif, i, i, i);
455
456   int lastrow = ny * nycell - 1;
457   for (int irow = 0; irow < ny; irow++) {
458     int rpos = irow * nycell;
459     for (int ir = rpos; ir < rpos + nycell; ir++) {
460       for (int icol = 0; icol < nx; icol++) {
461         int cpos = icol * nxcell;
462         double dens = (v[icol][irow] - densmin) / (densmax - densmin);
463         dens = clamp(dens, 0., 1.);
464         for (int ic = cpos; ic < cpos + nxcell; ic++) {
465           rowp[ic] = (unsigned int) (dens * (double) (N_GRAYSCALE - 1));
466           gdImageSetPixel(gif, ic, lastrow - ir, gs_indices[rowp[ic]]);
467         }
468       }
469     }
470   }
471
472   if ((out = fopen(outfile,"w")) == NULL) {
473     sys_error(ERR_FATAL, "Error opening output file %s for writing", outfile);
474     return (1);
475   }
476   gdImageGif(gif,out);
477   fclose(out);
478   gdImageDestroy(gif);
479 }
480 #endif
481