about summary refs log tree commit diff
path: root/generator/pamgauss.c
blob: 9656708ba60b8028c020a0b116ba9edbf38a4651 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#include "pm_c_util.h"
#include "shhopt.h"
#include "mallocvar.h"
#include "pam.h"



struct CmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    unsigned int width;
    unsigned int height;
    unsigned int maxval;
    float        sigma;
    unsigned int oversample;
    unsigned int maximize;
    const char * tupletype;
};



static void
parseCommandLine(int argc, const char ** argv,
                 struct CmdlineInfo * const cmdlineP) {
/*----------------------------------------------------------------------------
  Convert program invocation arguments (argc,argv) into a format the 
  program can use easily, struct cmdlineInfo.  Validate arguments along
  the way and exit program with message if invalid.

  Note that some string information we return as *cmdlineP is in the storage 
  argv[] points to.
-----------------------------------------------------------------------------*/
    optEntry * option_def;
        /* Instructions to OptParseOptions2 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int tupletypeSpec, maxvalSpec, sigmaSpec, oversampleSpec;
    unsigned int option_def_index;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENTRY */
    OPTENT3(0,   "tupletype",  OPT_STRING, &cmdlineP->tupletype, 
            &tupletypeSpec,      0);
    OPTENT3(0,   "maxval",     OPT_UINT,   &cmdlineP->maxval, 
            &maxvalSpec,         0);
    OPTENT3(0,   "sigma",      OPT_FLOAT,  &cmdlineP->sigma, 
            &sigmaSpec,          0);
    OPTENT3(0,   "maximize",   OPT_FLAG,   NULL,
            &cmdlineP->maximize, 0);
    OPTENT3(0,   "oversample", OPT_UINT,   &cmdlineP->oversample,
            &oversampleSpec,     0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */

    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
        /* Uses and sets argc, argv, and some of *cmdlineP and others. */

    if (!tupletypeSpec)
        cmdlineP->tupletype = "";
    else {
        struct pam pam;
        if (strlen(cmdlineP->tupletype)+1 > sizeof(pam.tuple_type))
            pm_error("The tuple type you specified is too long.  "
                     "Maximum %u characters.",
                     (unsigned)sizeof(pam.tuple_type)-1);
    }        

    if (!sigmaSpec)
        pm_error("You must specify the -sigma option.");
    else if (cmdlineP->sigma <= 0.0)
        pm_error("-sigma must be positive.  You specified %f", 
                 cmdlineP->sigma);

    if (!maxvalSpec)
        cmdlineP->maxval = PNM_MAXMAXVAL;
    else {
        if (cmdlineP->maxval > PNM_OVERALLMAXVAL)
            pm_error("The maxval you specified (%u) is too big.  "
                     "Maximum is %u", cmdlineP->maxval, PNM_OVERALLMAXVAL);
        if (cmdlineP->maxval < 1)
            pm_error("-maxval must be at least 1");
    }    

    if (oversampleSpec) {
        if (cmdlineP->oversample < 1)
            pm_error("The oversample factor (-oversample) "
                     "must be at least 1.");
    } else
        cmdlineP->oversample = ceil(5.0 / cmdlineP->sigma);

    if (argc-1 < 2)
        pm_error("Need two arguments: width and height.");
    else if (argc-1 > 2)
        pm_error("Only two arguments allowed: width and height.  "
                 "You specified %d", argc-1);
    else {
        cmdlineP->width = atoi(argv[1]);
        cmdlineP->height = atoi(argv[2]);
        if (cmdlineP->width <= 0)
            pm_error("width argument must be a positive number.  You "
                     "specified '%s'", argv[1]);
        if (cmdlineP->height <= 0)
            pm_error("height argument must be a positive number.  You "
                     "specified '%s'", argv[2]);
    }
    free(option_def);
}



static double
distFromCenter(unsigned int const width,
               unsigned int const height,
               double       const x,
               double       const y)
{
    return sqrt(SQR(x - (double)width  / 2) +
                SQR(y - (double)height / 2));
}



static double
gauss(double const arg,
      double const sigma) {
/*----------------------------------------------------------------------------
   Compute the value of the gaussian function centered at zero with
   standard deviation 'sigma' and amplitude 1, at 'arg'.
-----------------------------------------------------------------------------*/
    double const exponent = - SQR(arg) / (2 * SQR(sigma));

    return exp(exponent);
}



static double
pixelValue(unsigned int const width,
           unsigned int const height,
           unsigned int const row,
           unsigned int const col,
           unsigned int const subpixDivision,
           double       const sigma) {
/*----------------------------------------------------------------------------
  The gaussian value for the pixel at row 'row', column 'col' in an image
  described by *pamP.

  This is the mean of the values of the gaussian function computed at
  all the subpixel locations within the pixel when it is divided into
  subpixels 'subpixDivision' times horizontally and vertically.

  The gaussian function has standard deviation 'sigma' and amplitude 1.
-----------------------------------------------------------------------------*/
    double const offset = 1.0 / (subpixDivision * 2);
    double const y0     = (double)row + offset; 
    double const x0     = (double)col + offset;

    double const subpixSize = 1.0 / subpixDivision;

    unsigned int i;
    double total;
        /* Running total of the gaussian values at all subpixel locations */

    for (i = 0, total = 0.0; i < subpixDivision; ++i) {
        /* Sum up one column of subpixels */

        unsigned int j;

        for (j = 0; j < subpixDivision; ++j) {
            double const dist =
                distFromCenter(width, height,
                               x0 + i * subpixSize,
                               y0 + j * subpixSize);

            total += gauss(dist, sigma);
        }
    }

    return total / SQR(subpixDivision);
}



static double **
gaussianKernel(unsigned int const width,
               unsigned int const height,
               unsigned int const subpixDivision,
               double       const sigma) {
/*----------------------------------------------------------------------------
   A Gaussian matrix 'width' by 'height', with each value being the mean
   of a Gaussian function evaluated at 'subpixDivision' x 'subpixDivision'
   locations.

   Return value is newly malloc'ed storage that Caller must free.
-----------------------------------------------------------------------------*/
    double ** kernel;
    unsigned int row;

    MALLOCARRAY2(kernel, height, width);

    if (!kernel)
        pm_error("Unable to allocate %u x %u array in which to build kernel",
                 height, width);

    for (row = 0; row < height; ++row) {
        unsigned int col;
        for (col = 0; col < width; ++col) {
            double const gaussval =
                pixelValue(width, height, row, col, subpixDivision, sigma);
            kernel[row][col] = gaussval;
        }
    }
    return kernel;
}



static double
maximumKernelValue(double **    const kernel,
                   unsigned int const width,
                   unsigned int const height) {

    /* As this is Gaussian in both directions, centered at the center,
       we know the maximum value is at the center.
    */
    return kernel[height/2][width/2];
}        



static double
totalKernelValue(double **    const kernel,
                 unsigned int const width,
                 unsigned int const height) {

    double total;
    unsigned int row;

    for (row = 0, total = 0.0; row < height; ++row) {
        unsigned int col;
        
        for (col = 0; col < width; ++col)
            total += kernel[row][col];
    }

    return total;
}        



static void
initpam(struct pam * const pamP,
        unsigned int const width,
        unsigned int const height,
        sample       const maxval,
        const char * const tupleType,
        FILE *       const ofP) {

    pamP->size        = sizeof(*pamP);
    pamP->len         = PAM_STRUCT_SIZE(tuple_type);
    pamP->file        = ofP;
    pamP->format      = PAM_FORMAT;
    pamP->plainformat = 0;
    pamP->width       = width;
    pamP->height      = height;
    pamP->depth       = 1;
    pamP->maxval      = maxval;
    strcpy(pamP->tuple_type, tupleType);
}



static void
writePam(double **    const kernel,
         unsigned int const width,
         unsigned int const height,
         sample       const maxval,
         const char * const tupleType,
         double       const normalizer,
         FILE *       const ofP) {
/*----------------------------------------------------------------------------
   Write the kernel 'kernel', which is 'width' by 'height', as a PAM image
   with maxval 'maxval' and tuple type 'tupleType' to file *ofP.

   Divide the kernel values by 'normalizer' to get the normalized PAM sample
   value.  Assume that no value in 'kernel' is greater that 'normalizer'.
-----------------------------------------------------------------------------*/
    struct pam pam;
    unsigned int row;
    tuplen * tuplerown;

    initpam(&pam, width, height, maxval, tupleType, ofP);

    pnm_writepaminit(&pam);

    tuplerown = pnm_allocpamrown(&pam);

    for (row = 0; row < pam.height; ++row) {
        unsigned int col;
        for (col = 0; col < pam.width; ++col) {
            tuplerown[col][0] = kernel[row][col] / normalizer;
        
            assert(tuplerown[col][0] <= 1.0);
        }
        pnm_writepamrown(&pam, tuplerown);
    }

    pnm_freepamrown(tuplerown);
}
    


int
main(int argc, const char **argv) {
    struct CmdlineInfo cmdline;
    double ** kernel;
    double    normalizer;
    
    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    kernel = gaussianKernel(cmdline.width, cmdline.height, cmdline.oversample,
                            cmdline.sigma);

    normalizer = cmdline.maximize ?
        maximumKernelValue(kernel, cmdline.width, cmdline.height) :
        totalKernelValue(kernel, cmdline.width, cmdline.height);

    writePam(kernel,
             cmdline.width, cmdline.height, cmdline.maxval, cmdline.tupletype,
             normalizer, stdout);

    pm_freearray2((void **)kernel);
    
    return 0;
}