Debian Codegraph @

editor/specialty/pampaintspill.c

raw
1 /* ----------------------------------------------------------------------
2 *
3 * Bleed colors from non-background colors into the background
4 *
5 * By Scott Pakin <[email protected]>
6 *
7 * ----------------------------------------------------------------------
8 *
9 * Copyright (C) 2010-2021 Scott Pakin <[email protected]>
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or (at
14 * your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see http://www.gnu.org/licenses/.
23 *
24 * ----------------------------------------------------------------------
25 */
26
27 /*
28 This program contains code to work with Openmp, so that it can process
29 multiple columns at once, using multiple threads on multiple CPU cores,
30 and thus take less elapsed time to run.
31
32 But that code is dead in a normal Netpbm build, as it does not use the
33 required compiler options or link with the required library in any
34 conventional environment we know of. One can exploit this code with a
35 modified build, e.g. with CADD and LADD make variables.
36
37 10.04.14
38 */
39
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <string.h>
43 #include <math.h>
44 #include <time.h>
45
46 #include "mallocvar.h"
47 #include "nstring.h"
48 #include "rand.h"
49 #include "shhopt.h"
50 #include "pam.h"
51 #include "pammap.h"
52
53 static time_t const timeUpdateDelta = 30;
54 /* Seconds between progress updates */
55 static int const minUpdates = 4;
56 /* Minimum number of progress updates to output */
57
58
59 struct cmdlineInfo {
60 /* This structure represents all of the information the user
61 supplied in the command line but in a form that's easy for the
62 program to use.
63 */
64 const char * inputFilename; /* '-' if stdin */
65 const char * bgcolor;
66 unsigned int wrap;
67 unsigned int all;
68 float power;
69 unsigned int downsample;
70 unsigned int randomseedSpec;
71 unsigned int randomseed;
72 unsigned int nearSpec;
73 unsigned int near;
74 };
75
76 struct coords {
77 /* This structure represents an (x,y) coordinate within an image and
78 the color at that coordinate. */
79 unsigned int x;
80 unsigned int y;
81 tuple color;
82 };
83
84 typedef double distFunc_t(const struct coords * const p0,
85 const struct coords * const p1,
86 unsigned int const width,
87 unsigned int const height);
88 /* Distance function */
89
90
91
92 static void
93 parseCommandLine(int argc, const char ** const argv,
94 struct cmdlineInfo * const cmdlineP ) {
95
96 optEntry * option_def;
97 /* Instructions to OptParseOptions3 on how to parse our options */
98 optStruct3 opt;
99 unsigned int option_def_index;
100 unsigned int bgcolorSpec, powerSpec, downsampleSpec;
101
102 MALLOCARRAY_NOFAIL(option_def, 100);
103 option_def_index = 0; /* Incremented by OPTENTRY */
104
105 OPTENT3(0, "bgcolor", OPT_STRING, &cmdlineP->bgcolor,
106 &bgcolorSpec, 0);
107 OPTENT3(0, "wrap", OPT_FLAG, NULL,
108 &cmdlineP->wrap, 0);
109 OPTENT3(0, "all", OPT_FLAG, NULL,
110 &cmdlineP->all, 0);
111 OPTENT3(0, "power", OPT_FLOAT, &cmdlineP->power,
112 &powerSpec, 0);
113 OPTENT3(0, "downsample", OPT_UINT, &cmdlineP->downsample,
114 &downsampleSpec, 0);
115 OPTENT3(0, "randomseed", OPT_UINT, &cmdlineP->randomseed,
116 &cmdlineP->randomseedSpec, 0);
117 OPTENT3(0, "near", OPT_UINT, &cmdlineP->near,
118 &cmdlineP->nearSpec, 0);
119
120 opt.opt_table = option_def;
121 opt.short_allowed = 0;
122 opt.allowNegNum = 1;
123
124 pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 );
125
126 if (!bgcolorSpec)
127 cmdlineP->bgcolor = NULL;
128
129 if (!powerSpec)
130 cmdlineP->power = -2.0;
131
132 if (!downsampleSpec)
133 cmdlineP->downsample = 0;
134
135 if (cmdlineP->nearSpec) {
136 if (cmdlineP->near == 0)
137 pm_error("The -near option requires a positive argument");
138 }
139
140 if (argc-1 < 1)
141 cmdlineP->inputFilename = "-";
142 else {
143 cmdlineP->inputFilename = argv[1];
144 if (argc-1 > 1)
145 pm_error("Too many arguments: %u. The only argument is the "
146 "optional input file name", argc-1);
147 }
148 }
149
150
151 static bool
152 tupleEqualColor(const struct pam * const pamP,
153 tuple const comparand,
154 tuple const comparator) {
155 /*----------------------------------------------------------------------------
156 Report whether two tuples have equal color, regardless of alpha.
157 ----------------------------------------------------------------------------*/
158 unsigned int const nColorPlanes = pamP->depth >= 3 ? 3 : 1;
159
160 unsigned int plane;
161
162 for (plane = 0; plane < nColorPlanes; ++plane)
163 if (comparand[plane] != comparator[plane])
164 return false;
165
166 return true;
167 }
168
169
170
171 struct paintSourceSet {
172 struct coords * list; /* malloc'ed */
173 /* The list of places in the image from which paint comes */
174 unsigned int size;
175 /* Number of entries in sources[] */
176 unsigned int alloc;
177 /* Number of slots for entries of allocated memory */
178 };
179
180
181
182 static void
183 setPaintSourceColors(struct pam * const pamP,
184 tuple ** const tuples,
185 struct paintSourceSet const paintSources) {
186 /*----------------------------------------------------------------------------
187 Set the 'color' member of each source in 'paintSources'.
188
189 Set it to the color of the source pixel in tuples[][], indicated by
190 'paintSources'.
191
192 Malloc memory to store these colors -- a contiguous block of memory for all
193 of them.
194 -----------------------------------------------------------------------------*/
195 struct pam pamPaint;
196 /* numPaintSources-wide PAM for use by pnm_allocpamrow() */
197 tuple * paintColor;
198 /* Points to storage for the color tuples */
199 unsigned int i;
200
201 pamPaint = *pamP;
202 pamPaint.width = paintSources.size;
203 paintColor = pnm_allocpamrow(&pamPaint);
204
205 for (i = 0; i < paintSources.size; ++i) {
206 struct coords * const thisSourceP = &paintSources.list[i];
207
208 thisSourceP->color = paintColor[i];
209 pnm_assigntuple(pamP, thisSourceP->color,
210 tuples[thisSourceP->y][thisSourceP->x]);
211 }
212 }
213
214
215
216 static void
217 addPaintSource(unsigned int const row,
218 unsigned int const col,
219 struct paintSourceSet * const paintSourcesP) {
220
221 if (paintSourcesP->size == paintSourcesP->alloc) {
222 paintSourcesP->alloc += 1024;
223 REALLOCARRAY(paintSourcesP->list, paintSourcesP->alloc);
224 if (!paintSourcesP->list)
225 pm_error("Out of memory");
226 }
227 paintSourcesP->list[paintSourcesP->size].x = col;
228 paintSourcesP->list[paintSourcesP->size].y = row;
229 ++paintSourcesP->size;
230 }
231
232
233
234 static void
235 locatePaintSources(struct pam * const pamP,
236 tuple ** const tuples,
237 tuple const bgColor,
238 unsigned int const downsample,
239 struct paintSourceSet * const paintSourcesP,
240 bool const randomseedSpec,
241 unsigned int const randomseed) {
242 /*--------------------------------------------------------------------
243 Construct a list of all pixel coordinates in the input image that
244 represent a non-background color.
245 ----------------------------------------------------------------------*/
246 struct paintSourceSet paintSources;
247 int row; /* signed so it works with Openmp */
248
249 paintSources.list = NULL;
250 paintSources.size = 0;
251 paintSources.alloc = 0;
252
253 #pragma omp parallel for
254 for (row = 0; row < pamP->height; ++row) {
255 unsigned int col;
256 for (col = 0; col < pamP->width; ++col) {
257 if (!tupleEqualColor(pamP, tuples[row][col], bgColor))
258 #pragma omp critical (addPaintSource)
259 addPaintSource(row, col, &paintSources);
260 }
261 }
262
263 pm_message("Image contains %u background + %u non-background pixels",
264 pamP->width * pamP->height - paintSources.size,
265 paintSources.size);
266
267 /* Reduce the number of paint sources to reduce execution time. */
268 if (downsample > 0 && downsample < paintSources.size) {
269 struct pm_randSt randSt;
270 unsigned int i;
271
272 pm_randinit(&randSt);
273 pm_srand2(&randSt, randomseedSpec, randomseed);
274
275 for (i = 0; i < downsample; ++i) {
276 unsigned int const swapIdx =
277 i + pm_rand(&randSt) % (paintSources.size - i);
278 struct coords const swapVal = paintSources.list[i];
279
280 paintSources.list[i] = paintSources.list[swapIdx];
281 paintSources.list[swapIdx] = swapVal;
282 }
283 pm_randterm(&randSt);
284 paintSources.size = downsample;
285 }
286
287 setPaintSourceColors(pamP, tuples, paintSources);
288
289 *paintSourcesP = paintSources;
290 }
291
292
293
294 static distFunc_t euclideanDistanceSqr;
295
296 static double
297 euclideanDistanceSqr(const struct coords * const p0,
298 const struct coords * const p1,
299 unsigned int const width,
300 unsigned int const height) {
301 /*----------------------------------------------------------------------------
302 Return the square of the Euclidean distance between p0 and p1.
303 -----------------------------------------------------------------------------*/
304 double const deltax = (double) (int) (p1->x - p0->x);
305 double const deltay = (double) (int) (p1->y - p0->y);
306
307 return SQR(deltax) + SQR(deltay);
308 }
309
310
311
312 static distFunc_t euclideanDistanceTorusSqr;
313
314 static double
315 euclideanDistanceTorusSqr(const struct coords * const p0,
316 const struct coords * const p1,
317 unsigned int const width,
318 unsigned int const height) {
319 /*----------------------------------------------------------------------------
320 Return the square of the Euclidean distance between p0 and p1, assuming
321 it's a toroidal surface on which the top row curves around to meet the
322 bottom and the left column to the right.
323 -----------------------------------------------------------------------------*/
324 struct coords p0Adj, p1Adj;
325
326 if (p1->x >= p0->x + width / 2) {
327 p0Adj.x = p0->x + width;
328 p1Adj.x = p1->x;
329 } else if (p0->x >= p1->x + width / 2) {
330 p0Adj.x = p0->x;
331 p1Adj.x = p1->x + width;
332 } else {
333 p0Adj.x = p0->x;
334 p1Adj.x = p1->x;
335 }
336 if (p1->y >= p0->y + height / 2) {
337 p0Adj.y = p0->y + height;
338 p1Adj.y = p1->y;
339 } else if (p0->y >= p1->y + height / 2) {
340 p0Adj.y = p0->y;
341 p1Adj.y = p1->y + height;
342 } else {
343 p0Adj.y = p0->y;
344 p1Adj.y = p1->y;
345 }
346
347 return euclideanDistanceSqr(&p0Adj, &p1Adj, 0, 0);
348 }
349
350
351
352 static void
353 reportProgress(unsigned int const rowsComplete,
354 unsigned int const height) {
355
356 static time_t prevOutputTime = 0;
357 time_t now; /* Current time in seconds */
358
359 if (prevOutputTime == 0)
360 prevOutputTime = time(NULL);
361
362 /* Output our progress only every timeUpdateDelta seconds. */
363 now = time(NULL);
364 if (prevOutputTime) {
365 if (now - prevOutputTime >= timeUpdateDelta
366 || rowsComplete % (height/minUpdates) == 0) {
367 pm_message("%5.1f%% complete",
368 rowsComplete * 100.0 / height);
369 prevOutputTime = now;
370 }
371 } else
372 prevOutputTime = now;
373 }
374
375
376
377 struct distanceList {
378 struct coords * sources; /* malloc'ed */
379 /* The list of places in the image from which paint comes */
380 double * distSqrs; /* malloc'ed */
381 /* The list of squared distances from the current point */
382 unsigned int size;
383 /* Number of entries in sources[] */
384 };
385
386
387
388 static void
389 computeDistances(struct pam * const pamP,
390 struct coords const target,
391 struct paintSourceSet const paintSources,
392 distFunc_t * const distFunc,
393 bool const nearOnly,
394 unsigned int const numNear,
395 struct distanceList * const distancesP) {
396
397 unsigned int ps;
398
399 /* Acquire a list of all distances. */
400 distancesP->size = 0;
401 for (ps = 0; ps < paintSources.size; ++ps) {
402 struct coords const source = paintSources.list[ps];
403 double const distSqr =
404 (*distFunc)(&target, &source,
405 pamP->width, pamP->height);
406 distancesP->sources[distancesP->size] = source;
407 distancesP->distSqrs[distancesP->size] = distSqr;
408 ++distancesP->size;
409 }
410
411 /* If requested, truncate the list to the smallest numNear distances. */
412 if (nearOnly && numNear < distancesP->size) {
413 unsigned int i;
414
415 /* Perform a partial sort -- just enough to identify the numNear
416 smallest distances. For performance reasons we assume that
417 numNear is much less than paintSources.size (say, less than
418 log2(paintSources.size)).
419 */
420 for (i = 0; i < numNear; ++i) {
421 unsigned int j;
422 for (j = i + 1; j < distancesP->size; ++j) {
423 if (distancesP->distSqrs[i] > distancesP->distSqrs[j]) {
424 /* Swap elements i and j. */
425 struct coords const src = distancesP->sources[i];;
426 double const dist2 = distancesP->distSqrs[i];
427
428 distancesP->sources[i] = distancesP->sources[j];
429 distancesP->distSqrs[i] = distancesP->distSqrs[j];
430 distancesP->sources[j] = src;
431 distancesP->distSqrs[j] = dist2;
432 }
433 }
434 }
435 distancesP->size = numNear;
436 }
437 }
438
439
440
441 static void
442 spillOnePixel(struct pam * const pamP,
443 struct coords const target,
444 struct paintSourceSet const paintSources,
445 distFunc_t * const distFunc,
446 double const distPower,
447 tuple const outTuple,
448 double * const newColor,
449 bool const nearOnly,
450 unsigned int const numNear,
451 struct distanceList * const distancesP) {
452
453 unsigned int plane;
454 unsigned int d;
455 double totalWeight;
456
457 for (plane = 0; plane < pamP->depth; ++plane)
458 newColor[plane] = 0.0;
459 computeDistances(pamP, target, paintSources, distFunc,
460 nearOnly, numNear, distancesP);
461 totalWeight = 0.0;
462 for (d = 0; d < distancesP->size; ++d) {
463 double const distSqr = distancesP->distSqrs[d];
464 struct coords const source = distancesP->sources[d];
465
466 /* We do special cases for some common cases with code
467 that is much faster than pow().
468 */
469 double const weight =
470 distPower == -2.0 ? 1.0 / distSqr :
471 distPower == -1.0 ? 1.0 / sqrt(distSqr):
472 pow(distSqr, distPower/2);
473
474 unsigned int plane;
475
476 for (plane = 0; plane < pamP->depth; ++plane)
477 newColor[plane] += weight * source.color[plane];
478
479 totalWeight += weight;
480 }
481 for (plane = 0; plane < pamP->depth; ++plane)
482 outTuple[plane] = (sample) (newColor[plane] / totalWeight);
483 }
484
485
486
487 static void
488 produceOutputImage(struct pam * const pamP,
489 tuple ** const intuples,
490 tuple const bgColor,
491 struct paintSourceSet const paintSources,
492 distFunc_t * const distFunc,
493 double const distPower,
494 bool const all,
495 bool const nearOnly,
496 unsigned int const numNear,
497 tuple *** const outtuplesP) {
498 /*--------------------------------------------------------------------
499 Color each background pixel (or, if allPixels is 1, all pixels)
500 using a fraction of each paint source as determined by its distance
501 to the background pixel.
502 ----------------------------------------------------------------------*/
503 int row; /* signed so it works with Openmp */
504 unsigned int rowsComplete;
505 tuple ** outtuples;
506
507 outtuples = pnm_allocpamarray(pamP);
508
509 rowsComplete = 0;
510 #pragma omp parallel for
511 for (row = 0; row < pamP->height; ++row) {
512 struct coords target;
513 double * newColor; /* malloc'ed */
514 struct distanceList * distancesP; /* malloc'ed */
515
516 MALLOCARRAY(newColor, pamP->depth);
517 MALLOCVAR_NOFAIL(distancesP);
518 MALLOCARRAY_NOFAIL(distancesP->sources, paintSources.size);
519 MALLOCARRAY_NOFAIL(distancesP->distSqrs, paintSources.size);
520
521 target.y = row;
522 for (target.x = 0; target.x < pamP->width; ++target.x) {
523 tuple const targetTuple = intuples[target.y][target.x];
524 tuple const outputTuple = outtuples[target.y][target.x];
525
526 if (all || tupleEqualColor(pamP, targetTuple, bgColor))
527 spillOnePixel(pamP, target, paintSources, distFunc, distPower,
528 outputTuple, newColor, nearOnly, numNear,
529 distancesP);
530 else
531 pnm_assigntuple(pamP, outputTuple, targetTuple);
532 }
533 #pragma omp critical (rowTally)
534 reportProgress(++rowsComplete, pamP->height);
535
536 free(distancesP->distSqrs);
537 free(distancesP->sources);
538 free(distancesP);
539 free(newColor);
540 }
541 *outtuplesP = outtuples;
542 }
543
544
545
546 int
547 main(int argc, const char *argv[]) {
548 FILE * ifP;
549 struct cmdlineInfo cmdline; /* Command-line parameters */
550 tuple bgColor; /* Input image's background color */
551 struct paintSourceSet paintSources;
552 /* The set of paint-source indexes into 'tuples' */
553 distFunc_t * distFunc; /* The distance function */
554 struct pam inPam;
555 struct pam outPam;
556 tuple ** inTuples;
557 tuple ** outTuples;
558
559 pm_proginit(&argc, argv);
560
561 parseCommandLine(argc, argv, &cmdline);
562
563 ifP = pm_openr(cmdline.inputFilename);
564
565 inTuples = pnm_readpam(ifP, &inPam, PAM_STRUCT_SIZE(allocation_depth));
566
567 pm_close(ifP);
568
569 distFunc = cmdline.wrap ? euclideanDistanceTorusSqr : euclideanDistanceSqr;
570
571 if (cmdline.bgcolor)
572 bgColor = pnm_parsecolor(cmdline.bgcolor, inPam.maxval) ;
573 else
574 bgColor = pnm_backgroundtuple(&inPam, inTuples);
575
576 pm_message("Treating %s as the background color",
577 pnm_colorname(&inPam, bgColor, PAM_COLORNAME_HEXOK));
578
579 locatePaintSources(&inPam, inTuples, bgColor, cmdline.downsample,
580 &paintSources,
581 cmdline.randomseedSpec, cmdline.randomseed);
582
583 produceOutputImage(&inPam, inTuples, bgColor, paintSources, distFunc,
584 cmdline.power, cmdline.all,
585 cmdline.nearSpec, cmdline.near, &outTuples);
586
587 outPam = inPam;
588 outPam.file = stdout;
589 pnm_writepam(&outPam, outTuples);
590
591 pnm_freepamarray(outTuples, &inPam);
592 pnm_freepamarray(inTuples, &outPam);
593
594 return 0;
595 }
596
597
598