about summary refs log tree commit diff
path: root/editor/pgmdeshadow.c
blob: 2c3a90f80d03836c3c5678563e12c53b8b4a5aff (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
/*============================================================================
                        pgmdeshadow
==============================================================================
   Read PGM containing scanned black/white text, deshadow, write PGM.
============================================================================*/
/*
    This code is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This code is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this code; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

/*
 * Algorithm reference: Luc Vincent, "Morphological Grayscale Reconstruction
 * in Image Analysis: Applications and Efficient Algorithms," IEEE
 * Transactions on Image Processing, vol. 2, no. 2, April 1993, pp. 176-201.
 *
 * The algorithm used here is "fast hybrid grayscale reruction,"
 * described as follows on pp. 198-199:
 *
 * I: mask image (binary or grayscale)
 * J: marker image, defined on domain D_I, J <= I.
 *    Reruction is determined directly in J.
 *
 * Scan D_I in raster order:
 *   Let p be the current pixel;
 *   J(p) <- (max{J(q),q member_of N_G_plus(p) union {p}}) ^ I(p)
 *       [Note that ^ here refers to "pointwise minimum.]
 *
 * Scan D_I in antiraster order:
 *   Let p be the current pixel;
 *   J(p) <- (max{J(q),q member_of N_G_minus(p) union {p}}) ^ I(p)
 *       [Note that ^ here refers to "pointwise minimum.]
 *   If there exists q member_of N_G_minus(p) such that J(q) < J(p) and
 *       J(q) < I(q), then fifo_add(p)
 *
 * Propagation step:
 *   While fifo_empty() is false
 *   p <- fifo_first()
 *   For every pixel q member_of N_G(p):
 *     If J(q) < J(p) and I(q) ~= J(q), then
 *       J(q) <- min{J(p),I(q)}
 *       fifo_add(q)
 */

#include <stdio.h>

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


struct cmdlineInfo {
    const char * inputFileName;
};



static void
parseCommandLine(int argc, char ** argv,
                 struct cmdlineInfo * const cmdlineP) {
/*----------------------------------------------------------------------------
   Note that the file spec array we return is stored in the storage that
   was passed to us as the argv array.
-----------------------------------------------------------------------------*/
    optEntry * option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int option_def_index;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */

    OPTENTINIT;

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

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

    if (argc-1 < 1)
        cmdlineP->inputFileName = "-";
    else {
        cmdlineP->inputFileName = argv[1];
        if (argc-1 > 1)
            pm_error ("Too many arguments.  The only argument is "
                      "the optional input file name");
    }
}



static void
initializeDeshadowMarker(gray **      const inputPixels,
                         gray **      const markerPixels,
                         unsigned int const cols,
                         unsigned int const rows,
                         gray         const maxval) {
/*----------------------------------------------------------------------------
  Fill the image with maxval and then copy 1-pixel-wide borders
-----------------------------------------------------------------------------*/
    { /* Make middle white */
        unsigned int row;
        
        for (row = 1; row < rows-1; ++row) {
            unsigned int col;
            for (col = 1; col < cols-1; ++col)
                markerPixels[row][col] = maxval;
        }
    }
    { /* Copy top edge */
        unsigned int col;
        for (col = 0; col < cols; ++col)
            markerPixels[0][col] = inputPixels[0][col];
    }
    { /* Copy bottom edge */
        unsigned int col;
        for (col = 0; col < cols; ++col)
            markerPixels[rows-1][col] = inputPixels[rows-1][col];
    }
    { /* Copy left edge */
        unsigned int row;
        for (row = 0; row < rows; ++row)
            markerPixels[row][0] = inputPixels[row][0];
    }
    { /* Copy right edge */
        unsigned int row;
        for (row = 0; row < rows; ++row)
            markerPixels[row][cols-1] = inputPixels[row][cols-1];
    }
}



static gray
min5(gray const a,
     gray const b,
     gray const c,
     gray const d,
     gray const e) {
    
    return MIN(a,MIN(b,MIN(c,MIN(d,e))));
}



static gray
minNortheastPixel(gray **      const pixels,
                  unsigned int const col,
                  unsigned int const row) {
/*----------------------------------------------------------------------------
  Return the minimum pixel value from among the immediate north-east
  neighbors of (col, row) in pixels[][].
-----------------------------------------------------------------------------*/
    return min5(pixels[row][col],
                pixels[row][col-1],
                pixels[row-1][col-1],
                pixels[row-1][col],
                pixels[row-1][col+1]);
}



static gray
minSouthwestPixel(gray **      const pixels,
                  unsigned int const col,
                  unsigned int const row) {
/*----------------------------------------------------------------------------
  Return the minimum pixel value from among the immediate south-west
  neighbors of (col, row) in pixels[][].
-----------------------------------------------------------------------------*/
    return min5(pixels[row][col],
                pixels[row][col+1],
                pixels[row+1][col-1],
                pixels[row+1][col],
                pixels[row+1][col+1]);
}



static void
estimateBackground(gray **      const inputPixels,
                   gray **      const markerPixels,
                   unsigned int const cols,
                   unsigned int const rows,
                   gray         const maxval) {
/*----------------------------------------------------------------------------
   Update markerPixels[].
-----------------------------------------------------------------------------*/
    unsigned int const passes = 2;
        /* make only two passes since the image is not really complicated
           (otherwise could go up to 10)
        */

    unsigned int pass;
    bool stable;

    for (pass = 0, stable = FALSE; pass < passes && !stable; ++pass) {
        int row;

        stable = TRUE;  /* initial assumption */

        /* scan in raster order */

        for (row = 1; row < rows; ++row) {
            unsigned int col;
            for (col = 1; col < cols-1; ++col) {
                gray const minpixel =
                    minNortheastPixel(markerPixels, col, row);

                if (minpixel > inputPixels[row][col]) {
                    markerPixels[row][col] = minpixel;
                    stable = FALSE;
                } else
                    markerPixels[row][col] = inputPixels[row][col];
            }       
        }
        /* scan in anti-raster order */
        
        for (row = rows-2; row >= 0; --row) {
            int col;
            for (col = cols-2; col > 0; --col) {
                gray const minpixel =
                    minSouthwestPixel(markerPixels, col, row);
                
                if (minpixel > inputPixels[row][col]) {
                    markerPixels[row][col] = minpixel;
                    stable = FALSE;
                } else
                    markerPixels[row][col] = inputPixels[row][col];
            }
        }
    }
}



static void
divide(gray **      const dividendPixels,
       gray **      const divisorPixels,
       unsigned int const cols,
       unsigned int const rows,
       gray         const maxval) {
/*----------------------------------------------------------------------------
   Divide each pixel of dividendPixels[][] by the corresponding pixel
   in divisorPixels[], replacing the dividendPixels[][] pixel with the
   quotient.

   But leave a one-pixel border around dividendPixels[][] unmodified.

   Make sure the results are reasonable and not larger than maxval.
-----------------------------------------------------------------------------*/
    unsigned int row;

    for (row = 1; row < rows-1; ++row) {
        unsigned int col;
        for (col = 1; col < cols-1; ++col) {
            gray const divisor  = divisorPixels[row][col];
            gray const dividend = dividendPixels[row][col];

            gray quotient;

            if (divisor == 0)
                quotient = maxval;
            else {
                if (25 * divisor < 3 * maxval && 25 * dividend < 3 * maxval)
                    quotient = maxval;
                else
                    quotient =
                        MIN(maxval,
                            maxval * (dividend + dividend/2) / divisor);
            }        
            dividendPixels[row][col] = quotient;
        }
    }
}



static void
deshadow(gray **      const inputPixels,
         unsigned int const cols,
         unsigned int const rows,
         gray         const maxval) {
/*----------------------------------------------------------------------------
   Deshadow the image described by inputPixels[], 'cols', 'rows', and
   'maxval'.  (Modify inputPixels[][]).
-----------------------------------------------------------------------------*/
    gray ** markerPixels;

    markerPixels = pgm_allocarray(cols, rows);

    initializeDeshadowMarker(inputPixels, markerPixels, cols, rows, maxval);
    
    estimateBackground(inputPixels, markerPixels, cols, rows, maxval);
    
    divide(inputPixels, markerPixels, cols, rows, maxval);

    pgm_freearray(markerPixels, rows);
}



int
main(int argc, char* argv[]) {

    struct cmdlineInfo cmdline;
    FILE * ifP;
    gray maxval;
    gray ** pixels;
    int cols, rows;

    pgm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.inputFileName);
    
    pixels = pgm_readpgm(ifP, &cols, &rows, &maxval);
    pm_close(ifP);
    
    deshadow(pixels, cols, rows, maxval);
    
    pgm_writepgm(stdout, pixels, cols, rows, maxval, 0);

    pgm_freearray(pixels, rows);

    return 0;
}