File Coverage

lib/PDL/ImageRGB/ppm_quant.c
Criterion Covered Total %
statement 0 217 0.0
branch 0 140 0.0
condition n/a
subroutine n/a
pod n/a
total 0 357 0.0


line stmt bran cond sub pod time code
1             /* going to turn it into a standalone module (cut out of xv24to8.c)
2             * final goal: turn into call_external module for idl
3             */
4              
5             #include
6             #include /* qsort */
7              
8              
9             #ifdef DEBUG_OUT
10             #define StartCursor() fprintf(stderr,"%%idlppm_quant: choosing colors")
11             #define WaitCursor() fputc('.',stderr)
12             #define FinishCursor() fputc('\n',stderr)
13             #define FatalError(x) { fprintf(stderr,x); return(NULL); }
14             #else
15             #define StartCursor()
16             #define WaitCursor()
17             #define FinishCursor()
18             #define FatalError(x) return(0)
19             #endif
20              
21             typedef unsigned char byte;
22              
23              
24             /***************************************************************/
25             /* The following code based on code from the 'pbmplus' package */
26             /* written by Jef Poskanzer */
27             /***************************************************************/
28              
29              
30             /* ppmquant.c - quantize the colors in a pixmap down to a specified number
31             **
32             ** Copyright (C) 1989, 1991 by Jef Poskanzer.
33             **
34             ** Permission to use, copy, modify, and distribute this software and its
35             ** documentation for any purpose and without fee is hereby granted, provided
36             ** that the above copyright notice appear in all copies and that both that
37             ** copyright notice and this permission notice appear in supporting
38             ** documentation. This software is provided "as is" without express or
39             ** implied warranty.
40             */
41              
42              
43             typedef unsigned char pixval;
44              
45             #define PPM_MAXMAXVAL 255
46             typedef struct { pixval r, g, b; } pixel;
47              
48             #define PPM_GETR(p) ((p).r)
49             #define PPM_GETG(p) ((p).g)
50             #define PPM_GETB(p) ((p).b)
51              
52             #define PPM_ASSIGN(p,red,grn,blu) \
53             { (p).r = (red); (p).g = (grn); (p).b = (blu); }
54              
55             #define PPM_EQUAL(p,q) ( (p).r == (q).r && (p).g == (q).g && (p).b == (q).b )
56              
57              
58             /* Color scaling macro -- to make writing ppmtowhatever easier. */
59              
60             #define PPM_DEPTH(newp,p,oldmaxval,newmaxval) \
61             PPM_ASSIGN( (newp), \
62             (int) PPM_GETR(p) * (newmaxval) / ((int)oldmaxval), \
63             (int) PPM_GETG(p) * (newmaxval) / ((int)oldmaxval), \
64             (int) PPM_GETB(p) * (newmaxval) / ((int)oldmaxval) )
65              
66              
67             /* Luminance macro. */
68              
69             /*
70             * #define PPM_LUMIN(p) \
71             * ( 0.299 * PPM_GETR(p) + 0.587 * PPM_GETG(p) + 0.114 * PPM_GETB(p) )
72             */
73              
74             /* Luminance macro, using only integer ops. Returns an int (*256) JHB */
75             #define PPM_LUMIN(p) \
76             ( 77 * PPM_GETR(p) + 150 * PPM_GETG(p) + 29 * PPM_GETB(p) )
77              
78             /* Color histogram stuff. */
79              
80             typedef struct chist_item* chist_vec;
81             struct chist_item { pixel color;
82             int value;
83             };
84              
85             typedef struct chist_list_item* chist_list;
86             struct chist_list_item { struct chist_item ch;
87             chist_list next;
88             };
89              
90             typedef chist_list* chash_table;
91              
92             typedef struct box* box_vector;
93             struct box {
94             int index;
95             int colors;
96             int sum;
97             };
98              
99              
100             #define MAXCOLORS 32767
101             #define CLUSTER_MAXVAL 63
102              
103             #define LARGE_LUM
104             #define REP_AVERAGE_PIXELS
105              
106             #define FS_SCALE 1024
107              
108             #define HASH_SIZE 6553
109              
110             #define ppm_hashpixel(p) ((((int) PPM_GETR(p) * 33023 + \
111             (int) PPM_GETG(p) * 30013 + \
112             (int) PPM_GETB(p) * 27011) & 0x7fffffff) \
113             % HASH_SIZE)
114              
115              
116              
117             /*** function defs ***/
118             #define PARM(x) x
119             static chist_vec mediancut PARM((chist_vec, int, int, int, int));
120             static int redcompare PARM((const void *, const void *));
121             static int greencompare PARM((const void *, const void *));
122             static int bluecompare PARM((const void *, const void *));
123             static int sumcompare PARM((const void *, const void *));
124             static chist_vec ppm_computechist PARM((pixel **, int,int,int,int *));
125             static chash_table ppm_computechash PARM((pixel **, int,int,int,int *));
126             static chist_vec ppm_chashtochist PARM((chash_table, int));
127             static chash_table ppm_allocchash PARM((void));
128             static void ppm_freechist PARM((chist_vec));
129             static void ppm_freechash PARM((chash_table));
130              
131             int ppm_quant(byte *rin, byte *gin, byte *bin, int cols, int rows,
132             byte *pic8, byte *imap, byte *omap,
133             int len, int newcolors, int mode);
134              
135             static int DEBUG=0;
136              
137             #define SEPARATE 0
138             #define PACKED 1
139             #define PALETTE 2
140              
141             /* rmap, gmap, bmap 256 byte arrays
142             ** pic24 rows*cols*3 size byte array
143             ** pic8 rows*cols byte array
144             ** newcolors number of new colors to put into look-up table
145             */
146              
147             /****************************************************************************/
148 0           int ppm_quant(byte *rin, byte *gin, byte *bin, int cols, int rows, byte *pic8, byte *imap,
149             byte *omap, int len, int newcolors, int mode)
150             {
151             byte *map;
152             pixel** pixels;
153             register pixel* pP;
154             int row;
155             register int col, limitcol;
156             pixval maxval, newmaxval;
157             int colors;
158             register int index;
159             chist_vec chv, colormap;
160             chash_table cht;
161             int i;
162             unsigned char *picptr;
163             static char *fn = "ppmquant()";
164              
165 0           index = 0;
166 0           maxval = 255;
167              
168             /*
169             * reformat 24-bit image (3 bytes per pixel) into 2-dimensional
170             * array of pixel structures
171             */
172              
173 0 0         if (DEBUG) fprintf(stderr,"%s: remapping to ppm-style internal fmt\n", fn);
174             WaitCursor();
175              
176 0           pixels = (pixel **) malloc(rows * sizeof(pixel *));
177 0 0         if (!pixels) FatalError("couldn't allocate 'pixels' array");
178 0 0         for (row=0; row
179 0           pixels[row] = (pixel *) malloc(cols * sizeof(pixel));
180 0 0         if (!pixels[row]) FatalError("couldn't allocate a row of pixels array");
181 0           switch (mode) {
182 0           case SEPARATE:
183 0 0         for (col=0, pP=pixels[row]; col
184 0           pP->r = *rin++;
185 0           pP->g = *gin++;
186 0           pP->b = *bin++;
187             }
188 0           break;
189 0           case PACKED:
190 0 0         for (col=0, pP=pixels[row]; col
191 0           pP->r = *rin++;
192 0           pP->g = *rin++;
193 0           pP->b = *rin++;
194             }
195 0           break;
196 0           case PALETTE:
197 0 0         for (col=0, pP=pixels[row]; col
198 0           pP->r = imap[*rin*3];
199 0           pP->g = imap[*rin*3+1];
200 0           pP->b = imap[*rin*3+2];
201             }
202 0           break;
203 0           default:
204 0           return 0;
205             break;
206             }
207              
208             }
209 0 0         if (DEBUG) fprintf(stderr,"%s: done format remapping\n", fn);
210              
211              
212              
213              
214             /*
215             * attempt to make a histogram of the colors, unclustered.
216             * If at first we don't succeed, lower maxval to increase color
217             * coherence and try again. This will eventually terminate, with
218             * maxval at worst 15, since 32^3 is approximately MAXCOLORS.
219             */
220              
221             WaitCursor();
222             for ( ; ; ) {
223 0 0         if (DEBUG) fprintf(stderr, "%s: making histogram\n", fn);
224              
225 0           chv = ppm_computechist(pixels, cols, rows, MAXCOLORS, &colors);
226 0 0         if (chv != (chist_vec) 0) break;
227              
228 0 0         if (DEBUG) fprintf(stderr, "%s: too many colors!\n", fn);
229 0           newmaxval = maxval / 2;
230 0 0         if (DEBUG) fprintf(stderr, "%s: rescaling colors (maxval=%d) %s\n",
231             fn, newmaxval, "to improve clustering");
232              
233 0 0         for (row=0; row
234 0 0         for (col=0, pP=pixels[row]; col
235 0           PPM_DEPTH( *pP, *pP, maxval, newmaxval );
236 0           maxval = newmaxval;
237             }
238              
239 0 0         if (DEBUG) fprintf(stderr,"%s: %d colors found\n", fn, colors);
240              
241              
242              
243             /*
244             * Step 3: apply median-cut to histogram, making the new colormap.
245             */
246              
247             WaitCursor();
248 0 0         if (DEBUG) fprintf(stderr, "%s: choosing %d colors\n", fn, newcolors);
249 0           colormap = mediancut(chv, colors, rows * cols, maxval, newcolors);
250 0           ppm_freechist(chv);
251              
252              
253              
254             /*
255             * Step 4: map the colors in the image to their closest match in the
256             * new colormap, and write 'em out.
257             */
258              
259 0 0         if (DEBUG) fprintf(stderr,"%s: mapping image to new colors\n", fn);
260 0           cht = ppm_allocchash();
261              
262 0           picptr = pic8;
263 0 0         for (row = 0; row < rows; ++row) {
264 0           col = 0; limitcol = cols; pP = pixels[row];
265              
266 0           if ((row & 0x1f) == 0) WaitCursor();
267             do {
268             int hash;
269             chist_list chl;
270              
271             /* Check hash table to see if we have already matched this color. */
272              
273 0           hash = ppm_hashpixel(*pP);
274 0 0         for (chl = cht[hash]; chl; chl = chl->next)
275 0 0         if (PPM_EQUAL(chl->ch.color, *pP)) {index = chl->ch.value; break;}
    0          
    0          
276              
277 0 0         if (!chl /*index = -1*/) {/* No; search colormap for closest match. */
278             register int i, r1, g1, b1, r2, g2, b2;
279             register long dist, newdist;
280              
281 0           r1 = PPM_GETR( *pP );
282 0           g1 = PPM_GETG( *pP );
283 0           b1 = PPM_GETB( *pP );
284 0           dist = 2000000000;
285              
286 0 0         for (i=0; i
287 0           r2 = PPM_GETR( colormap[i].color );
288 0           g2 = PPM_GETG( colormap[i].color );
289 0           b2 = PPM_GETB( colormap[i].color );
290              
291 0           newdist = ( r1 - r2 ) * ( r1 - r2 ) +
292 0           ( g1 - g2 ) * ( g1 - g2 ) +
293 0           ( b1 - b2 ) * ( b1 - b2 );
294              
295 0 0         if (newdist
296             }
297              
298 0           hash = ppm_hashpixel(*pP);
299 0           chl = (chist_list) malloc(sizeof(struct chist_list_item));
300 0 0         if (!chl) FatalError("ran out of memory adding to hash table");
301              
302 0           chl->ch.color = *pP;
303 0           chl->ch.value = index;
304 0           chl->next = cht[hash];
305 0           cht[hash] = chl;
306             }
307              
308 0           *picptr++ = index;
309              
310 0           ++col;
311 0           ++pP;
312             }
313 0 0         while (col != limitcol);
314             }
315              
316             /* rescale the colormap */
317 0           map = omap;
318 0 0         for (i=0; i
319 0           PPM_DEPTH(colormap[i].color, colormap[i].color, maxval, 255);
320 0           *map++ = PPM_GETR( colormap[i].color );
321 0           *map++ = PPM_GETG( colormap[i].color );
322 0           *map++ = PPM_GETB( colormap[i].color );
323             }
324              
325             /* free the pixels array */
326 0 0         for (i=0; i
327 0           free(pixels);
328              
329             /* free cht and colormap */
330 0           ppm_freechist(colormap);
331 0           ppm_freechash(cht);
332              
333 0           return 1;
334             }
335              
336              
337              
338             /*
339             ** Here is the fun part, the median-cut colormap generator. This is based
340             ** on Paul Heckbert's paper "Color Image Quantization for Frame Buffer
341             ** Display", SIGGRAPH '82 Proceedings, page 297.
342             */
343              
344              
345              
346             /****************************************************************************/
347 0           static chist_vec mediancut( chist_vec chv, int colors, int sum, int maxval, int newcolors )
348             {
349             chist_vec colormap;
350             box_vector bv;
351             register int bi, i;
352             int boxes;
353              
354 0           bv = (box_vector) malloc(sizeof(struct box) * newcolors);
355             colormap = (chist_vec)
356 0           malloc(sizeof(struct chist_item) * newcolors );
357              
358 0 0         if (!bv || !colormap) FatalError("unable to malloc in mediancut()");
    0          
359              
360 0 0         for (i=0; i
361 0           PPM_ASSIGN(colormap[i].color, 0, 0, 0);
362              
363             /*
364             * Set up the initial box.
365             */
366 0           bv[0].index = 0;
367 0           bv[0].colors = colors;
368 0           bv[0].sum = sum;
369 0           boxes = 1;
370              
371              
372             /*
373             ** Main loop: split boxes until we have enough.
374             */
375              
376 0 0         while ( boxes < newcolors ) {
377             register int indx, clrs;
378             int sm;
379             register int minr, maxr, ming, maxg, minb, maxb, v;
380             int halfsum, lowersum;
381              
382             /*
383             ** Find the first splittable box.
384             */
385 0 0         for (bi=0; bv[bi].colors<2 && bi
    0          
386 0 0         if (bi == boxes) break; /* ran out of colors! */
387              
388 0           indx = bv[bi].index;
389 0           clrs = bv[bi].colors;
390 0           sm = bv[bi].sum;
391              
392             /*
393             ** Go through the box finding the minimum and maximum of each
394             ** component - the boundaries of the box.
395             */
396 0           minr = maxr = PPM_GETR( chv[indx].color );
397 0           ming = maxg = PPM_GETG( chv[indx].color );
398 0           minb = maxb = PPM_GETB( chv[indx].color );
399              
400 0 0         for (i=1; i
401 0           v = PPM_GETR( chv[indx + i].color );
402 0 0         if (v < minr) minr = v;
403 0 0         if (v > maxr) maxr = v;
404              
405 0           v = PPM_GETG( chv[indx + i].color );
406 0 0         if (v < ming) ming = v;
407 0 0         if (v > maxg) maxg = v;
408              
409 0           v = PPM_GETB( chv[indx + i].color );
410 0 0         if (v < minb) minb = v;
411 0 0         if (v > maxb) maxb = v;
412             }
413              
414             /*
415             ** Find the largest dimension, and sort by that component. I have
416             ** included two methods for determining the "largest" dimension;
417             ** first by simply comparing the range in RGB space, and second
418             ** by transforming into luminosities before the comparison. You
419             ** can switch which method is used by switching the commenting on
420             ** the LARGE_ defines at the beginning of this source file.
421             */
422             {
423             /* LARGE_LUM version */
424              
425             pixel p;
426             int rl, gl, bl;
427              
428 0           PPM_ASSIGN(p, maxr - minr, 0, 0);
429 0           rl = PPM_LUMIN(p);
430              
431 0           PPM_ASSIGN(p, 0, maxg - ming, 0);
432 0           gl = PPM_LUMIN(p);
433              
434 0           PPM_ASSIGN(p, 0, 0, maxb - minb);
435 0           bl = PPM_LUMIN(p);
436              
437 0 0         if (rl >= gl && rl >= bl)
    0          
438 0           qsort((char*) &(chv[indx]), (size_t) clrs, sizeof(struct chist_item),
439             redcompare );
440 0 0         else if (gl >= bl)
441 0           qsort((char*) &(chv[indx]), (size_t) clrs, sizeof(struct chist_item),
442             greencompare );
443             else
444 0           qsort((char*) &(chv[indx]), (size_t) clrs, sizeof(struct chist_item),
445             bluecompare );
446             }
447              
448             /*
449             ** Now find the median based on the counts, so that about half the
450             ** pixels (not colors, pixels) are in each subdivision.
451             */
452 0           lowersum = chv[indx].value;
453 0           halfsum = sm / 2;
454 0 0         for (i=1; i
455 0 0         if (lowersum >= halfsum) break;
456 0           lowersum += chv[indx + i].value;
457             }
458              
459             /*
460             ** Split the box, and sort to bring the biggest boxes to the top.
461             */
462 0           bv[bi].colors = i;
463 0           bv[bi].sum = lowersum;
464 0           bv[boxes].index = indx + i;
465 0           bv[boxes].colors = clrs - i;
466 0           bv[boxes].sum = sm - lowersum;
467 0           ++boxes;
468 0           qsort((char*) bv, (size_t) boxes, sizeof(struct box), sumcompare);
469             } /* while (boxes ... */
470              
471             /*
472             ** Ok, we've got enough boxes. Now choose a representative color for
473             ** each box. There are a number of possible ways to make this choice.
474             ** One would be to choose the center of the box; this ignores any structure
475             ** within the boxes. Another method would be to average all the colors in
476             ** the box - this is the method specified in Heckbert's paper. A third
477             ** method is to average all the pixels in the box. You can switch which
478             ** method is used by switching the commenting on the REP_ defines at
479             ** the beginning of this source file.
480             */
481              
482 0 0         for (bi=0; bi
483             /* REP_AVERAGE_PIXELS version */
484 0           register int indx = bv[bi].index;
485 0           register int clrs = bv[bi].colors;
486 0           register long r = 0, g = 0, b = 0, sum = 0;
487              
488 0 0         for (i=0; i
489 0           r += PPM_GETR( chv[indx + i].color ) * chv[indx + i].value;
490 0           g += PPM_GETG( chv[indx + i].color ) * chv[indx + i].value;
491 0           b += PPM_GETB( chv[indx + i].color ) * chv[indx + i].value;
492 0           sum += chv[indx + i].value;
493             }
494              
495 0 0         r = r / sum; if (r>maxval) r = maxval; /* avoid math errors */
496 0 0         g = g / sum; if (g>maxval) g = maxval;
497 0 0         b = b / sum; if (b>maxval) b = maxval;
498              
499 0           PPM_ASSIGN( colormap[bi].color, r, g, b );
500             }
501              
502 0           free(bv);
503 0           return colormap;
504             }
505              
506              
507             /**********************************/
508 0           static int redcompare(const void *p1, const void *p2)
509             {
510 0           return (int) PPM_GETR( ((chist_vec)p1)->color ) -
511 0           (int) PPM_GETR( ((chist_vec)p2)->color );
512             }
513              
514             /**********************************/
515 0           static int greencompare(const void *p1, const void *p2)
516             {
517 0           return (int) PPM_GETG( ((chist_vec)p1)->color ) -
518 0           (int) PPM_GETG( ((chist_vec)p2)->color );
519             }
520              
521             /**********************************/
522 0           static int bluecompare(const void *p1, const void *p2)
523             {
524 0           return (int) PPM_GETB( ((chist_vec)p1)->color ) -
525 0           (int) PPM_GETB( ((chist_vec)p2)->color );
526             }
527              
528             /**********************************/
529 0           static int sumcompare(const void *p1, const void *p2)
530             {
531 0           return ((box_vector) p2)->sum - ((box_vector) p1)->sum;
532             }
533              
534              
535              
536             /****************************************************************************/
537             static chist_vec
538 0           ppm_computechist(pixel** pixels, int cols, int rows, int maxcolors, int* colorsP)
539             {
540             chash_table cht;
541             chist_vec chv;
542              
543 0           cht = ppm_computechash(pixels, cols, rows, maxcolors, colorsP);
544 0 0         if (!cht) return (chist_vec) 0;
545              
546 0           chv = ppm_chashtochist(cht, maxcolors);
547 0           ppm_freechash(cht);
548 0           return chv;
549             }
550              
551              
552             /****************************************************************************/
553 0           static chash_table ppm_computechash(pixel** pixels, int cols, int rows,
554             int maxcolors, int* colorsP )
555             {
556             chash_table cht;
557             register pixel* pP;
558             chist_list chl;
559             int col, row, hash;
560              
561 0           cht = ppm_allocchash( );
562 0           *colorsP = 0;
563              
564             /* Go through the entire image, building a hash table of colors. */
565 0 0         for (row=0; row
566 0 0         for (col=0, pP=pixels[row]; col
567 0           hash = ppm_hashpixel(*pP);
568              
569 0 0         for (chl = cht[hash]; chl != (chist_list) 0; chl = chl->next)
570 0 0         if (PPM_EQUAL(chl->ch.color, *pP)) break;
    0          
    0          
571              
572 0 0         if (chl != (chist_list) 0) ++(chl->ch.value);
573             else {
574 0 0         if ((*colorsP)++ > maxcolors) {
575 0           ppm_freechash(cht);
576 0           return (chash_table) 0;
577             }
578              
579 0           chl = (chist_list) malloc(sizeof(struct chist_list_item));
580 0 0         if (!chl) FatalError("ran out of memory computing hash table");
581              
582 0           chl->ch.color = *pP;
583 0           chl->ch.value = 1;
584 0           chl->next = cht[hash];
585 0           cht[hash] = chl;
586             }
587             }
588              
589 0           return cht;
590             }
591              
592              
593             /****************************************************************************/
594 0           static chash_table ppm_allocchash(void)
595             {
596             chash_table cht;
597             int i;
598              
599 0           cht = (chash_table) malloc( HASH_SIZE * sizeof(chist_list) );
600 0 0         if (!cht) FatalError("ran out of memory allocating hash table");
601              
602 0 0         for (i=0; i
603 0           cht[i] = (chist_list) 0;
604              
605 0           return cht;
606             }
607              
608              
609             /****************************************************************************/
610 0           static chist_vec ppm_chashtochist( chash_table cht, int maxcolors )
611             {
612             chist_vec chv;
613             chist_list chl;
614             int i, j;
615              
616             /* Now collate the hash table into a simple chist array. */
617 0           chv = (chist_vec) malloc( maxcolors * sizeof(struct chist_item) );
618              
619             /* (Leave room for expansion by caller.) */
620 0 0         if (!chv) FatalError("ran out of memory generating histogram");
621              
622             /* Loop through the hash table. */
623 0           j = 0;
624 0 0         for (i=0; i
625 0 0         for (chl = cht[i]; chl != (chist_list) 0; chl = chl->next) {
626             /* Add the new entry. */
627 0           chv[j] = chl->ch;
628 0           ++j;
629             }
630              
631 0           return chv;
632             }
633              
634              
635             /****************************************************************************/
636 0           static void ppm_freechist( chist_vec chv )
637             {
638 0           free( (char*) chv );
639 0           }
640              
641              
642             /****************************************************************************/
643 0           static void ppm_freechash( chash_table cht )
644             {
645             int i;
646             chist_list chl, chlnext;
647              
648 0 0         for (i=0; i
649 0 0         for (chl = cht[i]; chl != (chist_list) 0; chl = chlnext) {
650 0           chlnext = chl->next;
651 0           free( (char*) chl );
652             }
653              
654 0           free( (char*) cht );
655 0           }