Debian Codegraph @

converter/other/pgmtopbm.c

raw
1 /* pgmtopbm.c - read a portable graymap and write a portable bitmap
2 **
3 ** Copyright (C) 1989 by Jef Poskanzer.
4 **
5 ** Permission to use, copy, modify, and distribute this software and its
6 ** documentation for any purpose and without fee is hereby granted, provided
7 ** that the above copyright notice appear in all copies and that both that
8 ** copyright notice and this permission notice appear in supporting
9 ** documentation. This software is provided "as is" without express or
10 ** implied warranty.
11 */
12
13 #include <assert.h>
14
15 #include "pm_c_util.h"
16 #include "shhopt.h"
17 #include "pgm.h"
18 #include "dithers.h"
19 #include "mallocvar.h"
20 #include "rand.h"
21
22 enum halftone {QT_FS, QT_THRESH, QT_DITHER8, QT_CLUSTER, QT_HILBERT};
23
24
25 struct CmdlineInfo {
26 /* All the information the user supplied in the command line,
27 in a form easy for the program to use.
28 */
29 const char * inputFilespec;
30 enum halftone halftone;
31 unsigned int clumpSize;
32 unsigned int clusterRadius;
33 /* Defined only for halftone == QT_CLUSTER */
34 unsigned int randomSeed;
35 unsigned int randomSeedSpec;
36 /* Defined only for halftone == QT_FS */
37 float threshval;
38 };
39
40
41
42
43 static void
44 parseCommandLine(int argc, const char ** argv,
45 struct CmdlineInfo *cmdlineP) {
46 /*----------------------------------------------------------------------------
47 Note that the file spec array we return is stored in the storage that
48 was passed to us as the argv array.
49 -----------------------------------------------------------------------------*/
50 optEntry * option_def; /* Used by OPTENT3 */
51 optStruct3 opt;
52
53 unsigned int option_def_index;
54 unsigned int floydOpt, hilbertOpt, thresholdOpt, dither8Opt,
55 cluster3Opt, cluster4Opt, cluster8Opt;
56 unsigned int valueSpec, clumpSpec;
57
58 MALLOCARRAY_NOFAIL(option_def, 100);
59
60 option_def_index = 0; /* incremented by OPTENTRY */
61 OPTENT3(0, "floyd", OPT_FLAG, NULL, &floydOpt, 0);
62 OPTENT3(0, "fs", OPT_FLAG, NULL, &floydOpt, 0);
63 OPTENT3(0, "threshold", OPT_FLAG, NULL, &thresholdOpt, 0);
64 OPTENT3(0, "hilbert", OPT_FLAG, NULL, &hilbertOpt, 0);
65 OPTENT3(0, "dither8", OPT_FLAG, NULL, &dither8Opt, 0);
66 OPTENT3(0, "d8", OPT_FLAG, NULL, &dither8Opt, 0);
67 OPTENT3(0, "cluster3", OPT_FLAG, NULL, &cluster3Opt, 0);
68 OPTENT3(0, "c3", OPT_FLAG, NULL, &cluster3Opt, 0);
69 OPTENT3(0, "cluster4", OPT_FLAG, NULL, &cluster4Opt, 0);
70 OPTENT3(0, "c4", OPT_FLAG, NULL, &cluster4Opt, 0);
71 OPTENT3(0, "cluster8", OPT_FLAG, NULL, &cluster8Opt, 0);
72 OPTENT3(0, "c8", OPT_FLAG, NULL, &cluster8Opt, 0);
73 OPTENT3(0, "value", OPT_FLOAT, &cmdlineP->threshval,
74 &valueSpec, 0);
75 OPTENT3(0, "clump", OPT_UINT, &cmdlineP->clumpSize,
76 &clumpSpec, 0);
77 OPTENT3(0, "randomseed", OPT_UINT, &cmdlineP->randomSeed,
78 &cmdlineP->randomSeedSpec, 0);
79
80 opt.opt_table = option_def;
81 opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */
82 opt.allowNegNum = FALSE; /* We may have parms that are negative numbers */
83
84 pm_optParseOptions4(&argc, argv, opt, sizeof(opt), 0);
85 /* Uses and sets argc, argv, and some of *cmdlineP and others. */
86
87 if (floydOpt + thresholdOpt + hilbertOpt + dither8Opt +
88 cluster3Opt + cluster4Opt + cluster8Opt == 0)
89 cmdlineP->halftone = QT_FS;
90 else if (floydOpt + thresholdOpt + dither8Opt +
91 cluster3Opt + cluster4Opt + cluster8Opt > 1)
92 pm_error("No cannot specify more than one halftoning type");
93 else {
94 if (floydOpt)
95 cmdlineP->halftone = QT_FS;
96 else if (thresholdOpt)
97 cmdlineP->halftone = QT_THRESH;
98 else if (hilbertOpt)
99 cmdlineP->halftone = QT_HILBERT;
100 else if (dither8Opt)
101 cmdlineP->halftone = QT_DITHER8;
102 else if (cluster3Opt) {
103 cmdlineP->halftone = QT_CLUSTER;
104 cmdlineP->clusterRadius = 3;
105 } else if (cluster4Opt) {
106 cmdlineP->halftone = QT_CLUSTER;
107 cmdlineP->clusterRadius = 4;
108 } else if (cluster8Opt) {
109 cmdlineP->halftone = QT_CLUSTER;
110 cmdlineP->clusterRadius = 8;
111 } else
112 pm_error("INTERNAL ERROR. No halftone option");
113 }
114
115 if (!valueSpec)
116 cmdlineP->threshval = 0.5;
117 else {
118 if (cmdlineP->threshval < 0.0)
119 pm_error("-value cannot be negative. You specified %f",
120 cmdlineP->threshval);
121 if (cmdlineP->threshval > 1.0)
122 pm_error("-value cannot be greater than one. You specified %f",
123 cmdlineP->threshval);
124 }
125
126 if (!clumpSpec)
127 cmdlineP->clumpSize = 5;
128 else {
129 if (cmdlineP->clumpSize < 2)
130 pm_error("-clump must be at least 2. You specified %u",
131 cmdlineP->clumpSize);
132 }
133
134 if (cmdlineP->halftone != QT_FS && cmdlineP->randomSeedSpec)
135 pm_message ("Ignoring -randomseed value "
136 "(meaningful only with Floyd-Steinberg)");
137
138 if (argc-1 > 1)
139 pm_error("Too many arguments (%d). There is at most one "
140 "non-option argument: the file name",
141 argc-1);
142 else if (argc-1 == 1)
143 cmdlineP->inputFilespec = argv[1];
144 else
145 cmdlineP->inputFilespec = "-";
146 }
147
148
149
150 /* Hilbert curve tracer */
151
152 #define MAXORD 18
153
154 static int hil_order,hil_ord;
155 static int hil_turn;
156 static int hil_dx,hil_dy;
157 static int hil_x,hil_y;
158 static int hil_stage[MAXORD];
159 static int hil_width,hil_height;
160
161 static void
162 init_hilbert(int const w,
163 int const h) {
164 /*----------------------------------------------------------------------------
165 Initialize the Hilbert curve tracer
166 -----------------------------------------------------------------------------*/
167 int big,ber;
168 hil_width = w;
169 hil_height = h;
170 big = w > h ? w : h;
171 for (ber = 2, hil_order = 1; ber < big; ber <<= 1, hil_order++);
172 if (hil_order > MAXORD)
173 pm_error("Sorry, hilbert order is too large");
174 hil_ord = hil_order;
175 hil_order--;
176 }
177
178
179
180 static int
181 hilbert(int * const px, int * const py) {
182 /*----------------------------------------------------------------------------
183 Return non-zero if got another point
184 -----------------------------------------------------------------------------*/
185 int temp;
186 if (hil_ord > hil_order) {
187 /* have to do first point */
188
189 hil_ord--;
190 hil_stage[hil_ord] = 0;
191 hil_turn = -1;
192 hil_dy = 1;
193 hil_dx = hil_x = hil_y = 0;
194 *px = *py = 0;
195 return 1;
196 }
197
198 /* Operate the state machine */
199 for(;;) {
200 switch (hil_stage[hil_ord]) {
201 case 0:
202 hil_turn = -hil_turn;
203 temp = hil_dy;
204 hil_dy = -hil_turn * hil_dx;
205 hil_dx = hil_turn * temp;
206 if (hil_ord > 0) {
207 hil_stage[hil_ord] = 1;
208 hil_ord--;
209 hil_stage[hil_ord]=0;
210 continue;
211 }
212 case 1:
213 hil_x += hil_dx;
214 hil_y += hil_dy;
215 if (hil_x < hil_width && hil_y < hil_height) {
216 hil_stage[hil_ord] = 2;
217 *px = hil_x;
218 *py = hil_y;
219 return 1;
220 }
221 case 2:
222 hil_turn = -hil_turn;
223 temp = hil_dy;
224 hil_dy = -hil_turn * hil_dx;
225 hil_dx = hil_turn * temp;
226 if (hil_ord > 0) {
227 /* recurse */
228
229 hil_stage[hil_ord] = 3;
230 hil_ord--;
231 hil_stage[hil_ord]=0;
232 continue;
233 }
234 case 3:
235 hil_x += hil_dx;
236 hil_y += hil_dy;
237 if (hil_x < hil_width && hil_y < hil_height) {
238 hil_stage[hil_ord] = 4;
239 *px = hil_x;
240 *py = hil_y;
241 return 1;
242 }
243 case 4:
244 if (hil_ord > 0) {
245 /* recurse */
246 hil_stage[hil_ord] = 5;
247 hil_ord--;
248 hil_stage[hil_ord]=0;
249 continue;
250 }
251 case 5:
252 temp = hil_dy;
253 hil_dy = -hil_turn * hil_dx;
254 hil_dx = hil_turn * temp;
255 hil_turn = -hil_turn;
256 hil_x += hil_dx;
257 hil_y += hil_dy;
258 if (hil_x < hil_width && hil_y < hil_height) {
259 hil_stage[hil_ord] = 6;
260 *px = hil_x;
261 *py = hil_y;
262 return 1;
263 }
264 case 6:
265 if (hil_ord > 0) {
266 /* recurse */
267 hil_stage[hil_ord] = 7;
268 hil_ord--;
269 hil_stage[hil_ord]=0;
270 continue;
271 }
272 case 7:
273 temp = hil_dy;
274 hil_dy = -hil_turn * hil_dx;
275 hil_dx = hil_turn * temp;
276 hil_turn = -hil_turn;
277 /* Return from a recursion */
278 if (hil_ord < hil_order)
279 hil_ord++;
280 else
281 return 0;
282 }
283 }
284 }
285
286
287
288 static void doHilbert(FILE * const ifP,
289 unsigned int const clump_size) {
290 /*----------------------------------------------------------------------------
291 Use hilbert space filling curve dithering
292 -----------------------------------------------------------------------------*/
293 /*
294 * This is taken from the article "Digital Halftoning with
295 * Space Filling Curves" by Luiz Velho, proceedings of
296 * SIGRAPH '91, page 81.
297 *
298 * This is not a terribly efficient or quick version of
299 * this algorithm, but it seems to work. - Graeme Gill.
300 * [email protected]
301 *
302 */
303
304 int cols, rows;
305 gray maxval;
306 gray **grays;
307 bit **bits;
308 int end;
309 int *x,*y;
310 int sum = 0;
311
312 grays = pgm_readpgm(ifP, &cols,&rows, &maxval);
313 bits = pbm_allocarray(cols,rows);
314
315 MALLOCARRAY(x, clump_size);
316 MALLOCARRAY(y, clump_size);
317 if (x == NULL || y == NULL)
318 pm_error("out of memory");
319 init_hilbert(cols,rows);
320
321 end = clump_size;
322 while (end == clump_size) {
323 int i;
324 /* compute the next clust co-ordinates along hilbert path */
325 for (i = 0; i < end; i++) {
326 if (hilbert(&x[i],&y[i])==0)
327 end = i; /* we reached the end */
328 }
329 /* sum levels */
330 for (i = 0; i < end; i++)
331 sum += grays[y[i]][x[i]];
332 /* dither half and half along path */
333 for (i = 0; i < end; i++) {
334 if (sum >= maxval) {
335 bits[y[i]][x[i]] = PBM_WHITE;
336 sum -= maxval;
337 } else
338 bits[y[i]][x[i]] = PBM_BLACK;
339 }
340 }
341 pbm_writepbm(stdout, bits, cols, rows, 0);
342 }
343
344
345
346 struct converter {
347 void (*convertRow)(struct converter * const converterP,
348 unsigned int const row,
349 gray grayrow[],
350 bit bitrow[]);
351 void (*destroy)(struct converter * const converterP);
352 unsigned int cols;
353 gray maxval;
354 void * stateP;
355 };
356
357
358
359 /*=============================================================================
360 Converter: fs
361 =============================================================================*/
362
363 unsigned int const fs_scale = 1024;
364 unsigned int const half_fs_scale = 512;
365
366 struct fsState {
367 long* thiserr;
368 long* nexterr;
369 bool fs_forward;
370 long threshval; /* Threshold gray value, scaled by FS_SCALE */
371 };
372
373
374 static void
375 fsConvertRow(struct converter * const converterP,
376 unsigned int const row,
377 gray grayrow[],
378 bit bitrow[]) {
379
380 struct fsState * const stateP = converterP->stateP;
381
382 long * const thiserr = stateP->thiserr;
383 long * const nexterr = stateP->nexterr;
384
385 bit* bP;
386 gray* gP;
387
388 unsigned int limitcol;
389 unsigned int col;
390
391 for (col = 0; col < converterP->cols + 2; ++col)
392 nexterr[col] = 0;
393 if (stateP->fs_forward) {
394 col = 0;
395 limitcol = converterP->cols;
396 gP = grayrow;
397 bP = bitrow;
398 } else {
399 col = converterP->cols - 1;
400 limitcol = -1;
401 gP = &(grayrow[col]);
402 bP = &(bitrow[col]);
403 }
404 do {
405 long sum;
406 sum = ((long) *gP * fs_scale) / converterP->maxval +
407 thiserr[col + 1];
408 if (sum >= stateP->threshval) {
409 *bP = PBM_WHITE;
410 sum = sum - stateP->threshval - half_fs_scale;
411 } else
412 *bP = PBM_BLACK;
413
414 if (stateP->fs_forward) {
415 thiserr[col + 2] += (sum * 7) / 16;
416 nexterr[col ] += (sum * 3) / 16;
417 nexterr[col + 1] += (sum * 5) / 16;
418 nexterr[col + 2] += (sum ) / 16;
419
420 ++col;
421 ++gP;
422 ++bP;
423 } else {
424 thiserr[col ] += (sum * 7) / 16;
425 nexterr[col + 2] += (sum * 3) / 16;
426 nexterr[col + 1] += (sum * 5) / 16;
427 nexterr[col ] += (sum ) / 16;
428
429 --col;
430 --gP;
431 --bP;
432 }
433 } while (col != limitcol);
434
435 stateP->thiserr = nexterr;
436 stateP->nexterr = thiserr;
437 stateP->fs_forward = ! stateP->fs_forward;
438 }
439
440
441
442 static void
443 fsDestroy(struct converter * const converterP) {
444 free(converterP->stateP);
445 }
446
447
448
449 static struct converter
450 createFsConverter(unsigned int const cols,
451 gray const maxval,
452 float const threshFraction,
453 unsigned int const randomSeedSpec,
454 unsigned int const randomSeed) {
455
456 struct fsState * stateP;
457 struct converter converter;
458
459 MALLOCVAR_NOFAIL(stateP);
460
461 /* Initialize Floyd-Steinberg error vectors. */
462 MALLOCARRAY_NOFAIL(stateP->thiserr, cols + 2);
463 MALLOCARRAY_NOFAIL(stateP->nexterr, cols + 2);
464
465 {
466 /* (random errors in [-fs_scale/8 .. fs_scale/8]) */
467 unsigned int col;
468 struct pm_randSt randSt;
469 pm_randinit(&randSt);
470 pm_srand2(&randSt, randomSeedSpec, randomSeed);
471
472 for (col = 0; col < cols + 2; ++col)
473 stateP->thiserr[col] =
474 (long)(pm_rand(&randSt) % fs_scale - half_fs_scale) / 4;
475
476 pm_randterm(&randSt);
477 }
478
479 stateP->fs_forward = TRUE;
480 stateP->threshval = threshFraction * fs_scale;
481 converter.stateP = stateP;
482 converter.cols = cols;
483 converter.maxval = maxval;
484 converter.convertRow = &fsConvertRow;
485 converter.destroy = &fsDestroy;
486
487 return converter;
488 }
489
490
491
492 /*=============================================================================
493 Converter: thresh
494 =============================================================================*/
495
496 struct threshState {
497 gray threshval;
498 };
499
500
501 static void
502 threshConvertRow(struct converter * const converterP,
503 unsigned int const row,
504 gray grayrow[],
505 bit bitrow[]) {
506
507 struct threshState * const stateP = converterP->stateP;
508
509 unsigned int col;
510 for (col = 0; col < converterP->cols; ++col)
511 if (grayrow[col] >= stateP->threshval)
512 bitrow[col] = PBM_WHITE;
513 else
514 bitrow[col] = PBM_BLACK;
515 }
516
517
518
519 static void
520 threshDestroy(struct converter * const converterP) {
521 free(converterP->stateP);
522 }
523
524
525
526 static struct converter
527 createThreshConverter(unsigned int const cols,
528 gray const maxval,
529 float const threshFraction) {
530
531 struct threshState * stateP;
532 struct converter converter;
533
534 MALLOCVAR_NOFAIL(stateP);
535
536 converter.cols = cols;
537 converter.maxval = maxval;
538 converter.convertRow = &threshConvertRow;
539 converter.destroy = &threshDestroy;
540
541 stateP->threshval = ROUNDU(maxval * threshFraction);
542 converter.stateP = stateP;
543
544 return converter;
545 }
546
547
548
549 /*=============================================================================
550 Converter: dither8
551 =============================================================================*/
552
553 struct dither8State {
554 int dither8[16][16];
555 };
556
557
558
559 static void
560 dither8ConvertRow(struct converter * const converterP,
561 unsigned int const row,
562 gray grayrow[],
563 bit bitrow[]) {
564
565 struct dither8State * const stateP = converterP->stateP;
566
567 unsigned int col;
568
569 for (col = 0; col < converterP->cols; ++col)
570 if (grayrow[col] > stateP->dither8[row % 16][col % 16])
571 bitrow[col] = PBM_WHITE;
572 else
573 bitrow[col] = PBM_BLACK;
574 }
575
576
577
578 static void
579 dither8Destroy(struct converter * const converterP) {
580
581 struct dither8State * const stateP = converterP->stateP;
582
583 free(stateP);
584 }
585
586
587
588 static struct converter
589 createDither8Converter(unsigned int const cols,
590 gray const maxval) {
591
592 struct converter converter;
593 struct dither8State * stateP;
594
595 unsigned int row;
596
597 MALLOCVAR_NOFAIL(stateP);
598
599 converter.cols = cols;
600 converter.convertRow = &dither8ConvertRow;
601 converter.destroy = dither8Destroy;
602 converter.stateP = stateP;
603 converter.maxval = maxval;
604
605 /* Scale dither matrix. */
606 for (row = 0; row < 16; ++row) {
607 unsigned int col;
608 for (col = 0; col < 16; ++col)
609 stateP->dither8[row][col] = dither8[row][col] * maxval / 256;
610 }
611 return converter;
612 }
613
614
615
616 /*=============================================================================
617 Converter: cluster
618 =============================================================================*/
619
620 struct clusterState {
621 unsigned int radius;
622 int ** clusterMatrix;
623 };
624
625
626
627 static void
628 clusterConvertRow(struct converter * const converterP,
629 unsigned int const row,
630 gray grayrow[],
631 bit bitrow[]) {
632
633 struct clusterState * const stateP = converterP->stateP;
634 unsigned int const diameter = 2 * stateP->radius;
635
636 unsigned int col;
637
638 for (col = 0; col < converterP->cols; ++col)
639 if (grayrow[col] >
640 stateP->clusterMatrix[row % diameter][col % diameter])
641 bitrow[col] = PBM_WHITE;
642 else
643 bitrow[col] = PBM_BLACK;
644 }
645
646
647
648 static void
649 clusterDestroy(struct converter * const converterP) {
650
651 struct clusterState * const stateP = converterP->stateP;
652 unsigned int const diameter = 2 * stateP->radius;
653
654 unsigned int row;
655
656 for (row = 0; row < diameter; ++row)
657 free(stateP->clusterMatrix[row]);
658
659 free(stateP->clusterMatrix);
660
661 free(stateP);
662 }
663
664
665
666 static struct converter
667 createClusterConverter(unsigned int const radius,
668 unsigned int const cols,
669 gray const maxval) {
670
671 int const clusterNormalizer = radius * radius * 2;
672 unsigned int const diameter = 2 * radius;
673
674 struct converter converter;
675 struct clusterState * stateP;
676 unsigned int row;
677
678 converter.cols = cols;
679 converter.maxval = maxval;
680 converter.convertRow = &clusterConvertRow;
681 converter.destroy = &clusterDestroy;
682
683 MALLOCVAR_NOFAIL(stateP);
684
685 stateP->radius = radius;
686
687 MALLOCARRAY_NOFAIL(stateP->clusterMatrix, diameter);
688 for (row = 0; row < diameter; ++row) {
689 unsigned int col;
690
691 MALLOCARRAY_NOFAIL(stateP->clusterMatrix[row], diameter);
692
693 for (col = 0; col < diameter; ++col) {
694 int val;
695 switch (radius) {
696 case 3: val = cluster3[row][col]; break;
697 case 4: val = cluster4[row][col]; break;
698 case 8: val = cluster8[row][col]; break;
699 default:
700 pm_error("INTERNAL ERROR: invalid radius");
701 }
702 stateP->clusterMatrix[row][col] = val * maxval / clusterNormalizer;
703 }
704 }
705
706 converter.stateP = stateP;
707
708 return converter;
709 }
710
711
712
713 int
714 main(int argc, const char *argv[]) {
715
716 struct CmdlineInfo cmdline;
717 FILE * ifP;
718 gray * grayrow;
719 bit * bitrow;
720
721 pm_proginit(&argc, argv);
722
723 parseCommandLine(argc, argv, &cmdline);
724
725 ifP = pm_openr(cmdline.inputFilespec);
726
727 if (cmdline.halftone == QT_HILBERT)
728 doHilbert(ifP, cmdline.clumpSize);
729 else {
730 struct converter converter;
731 int cols, rows;
732 gray maxval;
733 int format;
734 int row;
735
736 pgm_readpgminit(ifP, &cols, &rows, &maxval, &format);
737
738 pbm_writepbminit(stdout, cols, rows, 0);
739
740 switch (cmdline.halftone) {
741 case QT_FS:
742 converter = createFsConverter(cols, maxval, cmdline.threshval,
743 cmdline.randomSeedSpec,
744 cmdline.randomSeed);
745 break;
746 case QT_THRESH:
747 converter = createThreshConverter(cols, maxval, cmdline.threshval);
748 break;
749 case QT_DITHER8:
750 converter = createDither8Converter(cols, maxval);
751 break;
752 case QT_CLUSTER:
753 converter =
754 createClusterConverter(cmdline.clusterRadius, cols, maxval);
755 break;
756 case QT_HILBERT:
757 pm_error("INTERNAL ERROR: halftone is QT_HILBERT where it "
758 "shouldn't be.");
759 break;
760 }
761
762 grayrow = pgm_allocrow(cols);
763 bitrow = pbm_allocrow(cols);
764
765 for (row = 0; row < rows; ++row) {
766 pgm_readpgmrow(ifP, grayrow, cols, maxval, format);
767
768 converter.convertRow(&converter, row, grayrow, bitrow);
769
770 pbm_writepbmrow(stdout, bitrow, cols, 0);
771 }
772 pbm_freerow(bitrow);
773 pgm_freerow(grayrow);
774
775 if (converter.destroy)
776 converter.destroy(&converter);
777 }
778
779 pm_close(ifP);
780
781 return 0;
782 }
783
784
785