blob: 749359271b05d068dd10c73e910e638786628743 [file] [log] [blame]
cristy3ed852e2009-09-05 21:47:34 +00001/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% %
6% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
7% Q Q U U A A NN N T I ZZ E %
8% Q Q U U AAAAA N N N T I ZZZ EEEEE %
9% Q QQ U U A A N NN T I ZZ E %
10% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
11% %
12% %
13% MagickCore Methods to Reduce the Number of Unique Colors in an Image %
14% %
15% Software Design %
16% John Cristy %
17% July 1992 %
18% %
19% %
cristy16af1cb2009-12-11 21:38:29 +000020% Copyright 1999-2010 ImageMagick Studio LLC, a non-profit organization %
cristy3ed852e2009-09-05 21:47:34 +000021% dedicated to making software imaging solutions freely available. %
22% %
23% You may not use this file except in compliance with the License. You may %
24% obtain a copy of the License at %
25% %
26% http://www.imagemagick.org/script/license.php %
27% %
28% Unless required by applicable law or agreed to in writing, software %
29% distributed under the License is distributed on an "AS IS" BASIS, %
30% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31% See the License for the specific language governing permissions and %
32% limitations under the License. %
33% %
34%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35%
36% Realism in computer graphics typically requires using 24 bits/pixel to
37% generate an image. Yet many graphic display devices do not contain the
38% amount of memory necessary to match the spatial and color resolution of
39% the human eye. The Quantize methods takes a 24 bit image and reduces
40% the number of colors so it can be displayed on raster device with less
41% bits per pixel. In most instances, the quantized image closely
42% resembles the original reference image.
43%
44% A reduction of colors in an image is also desirable for image
45% transmission and real-time animation.
46%
47% QuantizeImage() takes a standard RGB or monochrome images and quantizes
48% them down to some fixed number of colors.
49%
50% For purposes of color allocation, an image is a set of n pixels, where
51% each pixel is a point in RGB space. RGB space is a 3-dimensional
52% vector space, and each pixel, Pi, is defined by an ordered triple of
53% red, green, and blue coordinates, (Ri, Gi, Bi).
54%
55% Each primary color component (red, green, or blue) represents an
56% intensity which varies linearly from 0 to a maximum value, Cmax, which
57% corresponds to full saturation of that color. Color allocation is
58% defined over a domain consisting of the cube in RGB space with opposite
59% vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
60% 255.
61%
62% The algorithm maps this domain onto a tree in which each node
63% represents a cube within that domain. In the following discussion
64% these cubes are defined by the coordinate of two opposite vertices:
65% The vertex nearest the origin in RGB space and the vertex farthest from
66% the origin.
67%
68% The tree's root node represents the entire domain, (0,0,0) through
69% (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70% subdividing one node's cube into eight smaller cubes of equal size.
71% This corresponds to bisecting the parent cube with planes passing
72% through the midpoints of each edge.
73%
74% The basic algorithm operates in three phases: Classification,
75% Reduction, and Assignment. Classification builds a color description
76% tree for the image. Reduction collapses the tree until the number it
77% represents, at most, the number of colors desired in the output image.
78% Assignment defines the output image's color map and sets each pixel's
79% color by restorage_class in the reduced tree. Our goal is to minimize
80% the numerical discrepancies between the original colors and quantized
81% colors (quantization error).
82%
83% Classification begins by initializing a color description tree of
84% sufficient depth to represent each possible input color in a leaf.
85% However, it is impractical to generate a fully-formed color description
86% tree in the storage_class phase for realistic values of Cmax. If
87% colors components in the input image are quantized to k-bit precision,
88% so that Cmax= 2k-1, the tree would need k levels below the root node to
89% allow representing each possible input color in a leaf. This becomes
90% prohibitive because the tree's total number of nodes is 1 +
91% sum(i=1, k, 8k).
92%
93% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95% Initializes data structures for nodes only as they are needed; (2)
96% Chooses a maximum depth for the tree as a function of the desired
97% number of colors in the output image (currently log2(colormap size)).
98%
99% For each pixel in the input image, storage_class scans downward from
100% the root of the color description tree. At each level of the tree it
101% identifies the single node which represents a cube in RGB space
102% containing the pixel's color. It updates the following data for each
103% such node:
104%
105% n1: Number of pixels whose color is contained in the RGB cube which
106% this node represents;
107%
108% n2: Number of pixels whose color is not represented in a node at
109% lower depth in the tree; initially, n2 = 0 for all nodes except
110% leaves of the tree.
111%
112% Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113% pixels not classified at a lower depth. The combination of these sums
114% and n2 will ultimately characterize the mean color of a set of
115% pixels represented by this node.
116%
117% E: the distance squared in RGB space between each pixel contained
118% within a node and the nodes' center. This represents the
119% quantization error for a node.
120%
121% Reduction repeatedly prunes the tree until the number of nodes with n2
122% > 0 is less than or equal to the maximum number of colors allowed in
123% the output image. On any given iteration over the tree, it selects
124% those nodes whose E count is minimal for pruning and merges their color
125% statistics upward. It uses a pruning threshold, Ep, to govern node
126% selection as follows:
127%
128% Ep = 0
129% while number of nodes with (n2 > 0) > required maximum number of colors
130% prune all nodes such that E <= Ep
131% Set Ep to minimum E in remaining nodes
132%
133% This has the effect of minimizing any quantization error when merging
134% two nodes together.
135%
136% When a node to be pruned has offspring, the pruning procedure invokes
137% itself recursively in order to prune the tree from the leaves upward.
138% n2, Sr, Sg, and Sb in a node being pruned are always added to the
139% corresponding data in that node's parent. This retains the pruned
140% node's color characteristics for later averaging.
141%
142% For each node, n2 pixels exist for which that node represents the
143% smallest volume in RGB space containing those pixel's colors. When n2
144% > 0 the node will uniquely define a color in the output image. At the
145% beginning of reduction, n2 = 0 for all nodes except a the leaves of
146% the tree which represent colors present in the input image.
147%
148% The other pixel count, n1, indicates the total number of colors within
149% the cubic volume which the node represents. This includes n1 - n2
150% pixels whose colors should be defined by nodes at a lower level in the
151% tree.
152%
153% Assignment generates the output image from the pruned tree. The output
154% image consists of two parts: (1) A color map, which is an array of
155% color descriptions (RGB triples) for each color present in the output
156% image; (2) A pixel array, which represents each pixel as an index
157% into the color map array.
158%
159% First, the assignment phase makes one pass over the pruned color
160% description tree to establish the image's color map. For each node
161% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162% color of all pixels that classify no lower than this node. Each of
163% these colors becomes an entry in the color map.
164%
165% Finally, the assignment phase reclassifies each pixel in the pruned
166% tree to identify the deepest node containing the pixel's color. The
167% pixel's value in the pixel array becomes the index of this node's mean
168% color in the color map.
169%
170% This method is based on a similar algorithm written by Paul Raveling.
171%
172*/
173
174/*
175 Include declarations.
176*/
177#include "magick/studio.h"
178#include "magick/cache-view.h"
179#include "magick/color.h"
180#include "magick/color-private.h"
181#include "magick/colorspace.h"
182#include "magick/enhance.h"
183#include "magick/exception.h"
184#include "magick/exception-private.h"
cristyf2e11662009-10-14 01:24:43 +0000185#include "magick/histogram.h"
cristy3ed852e2009-09-05 21:47:34 +0000186#include "magick/image.h"
187#include "magick/image-private.h"
188#include "magick/list.h"
189#include "magick/memory_.h"
190#include "magick/monitor.h"
191#include "magick/monitor-private.h"
192#include "magick/option.h"
193#include "magick/pixel-private.h"
194#include "magick/quantize.h"
195#include "magick/quantum.h"
196#include "magick/string_.h"
197
198/*
199 Define declarations.
200*/
201#define CacheShift 2
202#define ErrorQueueLength 16
203#define MaxNodes 266817
204#define MaxTreeDepth 8
205#define NodesInAList 1920
206
207/*
208 Typdef declarations.
209*/
210typedef struct _RealPixelPacket
211{
212 MagickRealType
213 red,
214 green,
215 blue,
216 opacity;
217} RealPixelPacket;
218
219typedef struct _NodeInfo
220{
221 struct _NodeInfo
222 *parent,
223 *child[16];
224
225 MagickSizeType
226 number_unique;
227
228 RealPixelPacket
229 total_color;
230
231 MagickRealType
232 quantize_error;
233
234 unsigned long
235 color_number,
236 id,
237 level;
238} NodeInfo;
239
240typedef struct _Nodes
241{
242 NodeInfo
243 *nodes;
244
245 struct _Nodes
246 *next;
247} Nodes;
248
249typedef struct _CubeInfo
250{
251 NodeInfo
252 *root;
253
254 unsigned long
255 colors,
256 maximum_colors;
257
258 long
259 transparent_index;
260
261 MagickSizeType
262 transparent_pixels;
263
264 RealPixelPacket
265 target;
266
267 MagickRealType
268 distance,
269 pruning_threshold,
270 next_threshold;
271
272 unsigned long
273 nodes,
274 free_nodes,
275 color_number;
276
277 NodeInfo
278 *next_node;
279
280 Nodes
281 *node_queue;
282
283 long
284 *cache;
285
286 RealPixelPacket
287 error[ErrorQueueLength];
288
289 MagickRealType
290 weights[ErrorQueueLength];
291
292 QuantizeInfo
293 *quantize_info;
294
295 MagickBooleanType
296 associate_alpha;
297
298 long
299 x,
300 y;
301
302 unsigned long
303 depth;
304
305 MagickOffsetType
306 offset;
307
308 MagickSizeType
309 span;
310} CubeInfo;
311
312/*
313 Method prototypes.
314*/
315static CubeInfo
316 *GetCubeInfo(const QuantizeInfo *,const unsigned long,const unsigned long);
317
318static NodeInfo
319 *GetNodeInfo(CubeInfo *,const unsigned long,const unsigned long,NodeInfo *);
320
321static MagickBooleanType
322 AssignImageColors(Image *,CubeInfo *),
323 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
324 DitherImage(Image *,CubeInfo *),
325 SetGrayscaleImage(Image *);
326
327static unsigned long
328 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
329
330static void
331 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
332 DestroyCubeInfo(CubeInfo *),
333 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
334 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
335 ReduceImageColors(const Image *,CubeInfo *);
336
337/*
338%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
339% %
340% %
341% %
342% A c q u i r e Q u a n t i z e I n f o %
343% %
344% %
345% %
346%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
347%
348% AcquireQuantizeInfo() allocates the QuantizeInfo structure.
349%
350% The format of the AcquireQuantizeInfo method is:
351%
352% QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
353%
354% A description of each parameter follows:
355%
356% o image_info: the image info.
357%
358*/
359MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
360{
361 QuantizeInfo
362 *quantize_info;
363
cristy90823212009-12-12 20:48:33 +0000364 quantize_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*quantize_info));
cristy3ed852e2009-09-05 21:47:34 +0000365 if (quantize_info == (QuantizeInfo *) NULL)
366 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
367 GetQuantizeInfo(quantize_info);
368 if (image_info != (ImageInfo *) NULL)
369 {
370 const char
371 *option;
372
373 quantize_info->dither=image_info->dither;
374 option=GetImageOption(image_info,"dither");
375 if (option != (const char *) NULL)
376 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
377 MagickDitherOptions,MagickFalse,option);
378 quantize_info->measure_error=image_info->verbose;
379 }
380 return(quantize_info);
381}
382
383/*
384%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
385% %
386% %
387% %
388+ A s s i g n I m a g e C o l o r s %
389% %
390% %
391% %
392%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
393%
394% AssignImageColors() generates the output image from the pruned tree. The
395% output image consists of two parts: (1) A color map, which is an array
396% of color descriptions (RGB triples) for each color present in the
397% output image; (2) A pixel array, which represents each pixel as an
398% index into the color map array.
399%
400% First, the assignment phase makes one pass over the pruned color
401% description tree to establish the image's color map. For each node
402% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
403% color of all pixels that classify no lower than this node. Each of
404% these colors becomes an entry in the color map.
405%
406% Finally, the assignment phase reclassifies each pixel in the pruned
407% tree to identify the deepest node containing the pixel's color. The
408% pixel's value in the pixel array becomes the index of this node's mean
409% color in the color map.
410%
411% The format of the AssignImageColors() method is:
412%
413% MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
414%
415% A description of each parameter follows.
416%
417% o image: the image.
418%
419% o cube_info: A pointer to the Cube structure.
420%
421*/
422
423static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
424 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
425{
426 MagickRealType
427 alpha;
428
429 if ((cube_info->associate_alpha == MagickFalse) ||
430 (pixel->opacity == OpaqueOpacity))
431 {
432 alpha_pixel->red=(MagickRealType) pixel->red;
433 alpha_pixel->green=(MagickRealType) pixel->green;
434 alpha_pixel->blue=(MagickRealType) pixel->blue;
435 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
436 return;
437 }
438 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
439 alpha_pixel->red=alpha*pixel->red;
440 alpha_pixel->green=alpha*pixel->green;
441 alpha_pixel->blue=alpha*pixel->blue;
442 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
443}
444
cristy75ffdb72010-01-07 17:40:12 +0000445static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
cristy3ed852e2009-09-05 21:47:34 +0000446{
447 if (value <= 0.0)
448 return((Quantum) 0);
449 if (value >= QuantumRange)
450 return((Quantum) QuantumRange);
451 return((Quantum) (value+0.5));
452}
453
454static inline unsigned long ColorToNodeId(const CubeInfo *cube_info,
455 const RealPixelPacket *pixel,unsigned long index)
456{
457 unsigned long
458 id;
459
460 id=(unsigned long) (
cristy75ffdb72010-01-07 17:40:12 +0000461 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
462 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
463 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
cristy3ed852e2009-09-05 21:47:34 +0000464 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +0000465 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
cristy3ed852e2009-09-05 21:47:34 +0000466 << 3;
467 return(id);
468}
469
470static inline MagickBooleanType IsSameColor(const Image *image,
471 const PixelPacket *p,const PixelPacket *q)
472{
473 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
474 return(MagickFalse);
475 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
476 return(MagickFalse);
477 return(MagickTrue);
478}
479
480static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
481{
482#define AssignImageTag "Assign/Image"
483
484 long
485 y;
486
487 MagickBooleanType
488 proceed;
489
490 RealPixelPacket
491 pixel;
492
493 register long
494 i,
495 x;
496
497 register const NodeInfo
498 *node_info;
499
500 ssize_t
501 count;
502
503 unsigned long
504 id,
505 index;
506
507 /*
508 Allocate image colormap.
509 */
510 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
511 (cube_info->quantize_info->colorspace != CMYKColorspace))
512 (void) TransformImageColorspace((Image *) image,
513 cube_info->quantize_info->colorspace);
514 else
515 if ((image->colorspace != GRAYColorspace) &&
516 (image->colorspace != RGBColorspace) &&
517 (image->colorspace != CMYColorspace))
518 (void) TransformImageColorspace((Image *) image,RGBColorspace);
519 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
520 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
521 image->filename);
522 image->colors=0;
523 cube_info->transparent_pixels=0;
524 cube_info->transparent_index=(-1);
525 (void) DefineImageColormap(image,cube_info,cube_info->root);
526 /*
527 Create a reduced color image.
528 */
529 if ((cube_info->quantize_info->dither != MagickFalse) &&
530 (cube_info->quantize_info->dither_method != NoDitherMethod))
531 (void) DitherImage(image,cube_info);
532 else
533 {
534 ExceptionInfo
535 *exception;
536
537 CacheView
538 *image_view;
539
540 exception=(&image->exception);
541 image_view=AcquireCacheView(image);
542 for (y=0; y < (long) image->rows; y++)
543 {
544 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +0000545 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +0000546
547 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000548 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000549
550 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
551 exception);
552 if (q == (PixelPacket *) NULL)
553 break;
554 indexes=GetCacheViewAuthenticIndexQueue(image_view);
555 for (x=0; x < (long) image->columns; x+=count)
556 {
557 /*
558 Identify the deepest node containing the pixel's color.
559 */
560 for (count=1; (x+count) < (long) image->columns; count++)
561 if (IsSameColor(image,q,q+count) == MagickFalse)
562 break;
563 AssociateAlphaPixel(cube_info,q,&pixel);
564 node_info=cube_info->root;
565 for (index=MaxTreeDepth-1; (long) index > 0; index--)
566 {
567 id=ColorToNodeId(cube_info,&pixel,index);
568 if (node_info->child[id] == (NodeInfo *) NULL)
569 break;
570 node_info=node_info->child[id];
571 }
572 /*
573 Find closest color among siblings and their children.
574 */
575 cube_info->target=pixel;
576 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
577 (QuantumRange+1.0)+1.0);
578 ClosestColor(image,cube_info,node_info->parent);
579 index=cube_info->color_number;
580 for (i=0; i < (long) count; i++)
581 {
582 if (image->storage_class == PseudoClass)
583 indexes[x+i]=(IndexPacket) index;
584 if (cube_info->quantize_info->measure_error == MagickFalse)
585 {
586 q->red=image->colormap[index].red;
587 q->green=image->colormap[index].green;
588 q->blue=image->colormap[index].blue;
589 if (cube_info->associate_alpha != MagickFalse)
590 q->opacity=image->colormap[index].opacity;
591 }
592 q++;
593 }
594 }
595 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
596 break;
597 proceed=SetImageProgress(image,AssignImageTag,y,image->rows);
598 if (proceed == MagickFalse)
599 break;
600 }
601 image_view=DestroyCacheView(image_view);
602 }
603 if (cube_info->quantize_info->measure_error != MagickFalse)
604 (void) GetImageQuantizeError(image);
605 if ((cube_info->quantize_info->number_colors == 2) &&
606 (cube_info->quantize_info->colorspace == GRAYColorspace))
607 {
608 Quantum
609 intensity;
610
611 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000612 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000613
614 /*
615 Monochrome image.
616 */
617 q=image->colormap;
618 for (i=0; i < (long) image->colors; i++)
619 {
620 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
621 QuantumRange/2.0) ? 0 : QuantumRange);
622 q->red=intensity;
623 q->green=intensity;
624 q->blue=intensity;
625 q++;
626 }
627 }
628 (void) SyncImage(image);
629 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
630 (cube_info->quantize_info->colorspace != CMYKColorspace))
631 (void) TransformImageColorspace((Image *) image,RGBColorspace);
632 return(MagickTrue);
633}
634
635/*
636%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
637% %
638% %
639% %
640+ C l a s s i f y I m a g e C o l o r s %
641% %
642% %
643% %
644%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
645%
646% ClassifyImageColors() begins by initializing a color description tree
647% of sufficient depth to represent each possible input color in a leaf.
648% However, it is impractical to generate a fully-formed color
649% description tree in the storage_class phase for realistic values of
650% Cmax. If colors components in the input image are quantized to k-bit
651% precision, so that Cmax= 2k-1, the tree would need k levels below the
652% root node to allow representing each possible input color in a leaf.
653% This becomes prohibitive because the tree's total number of nodes is
654% 1 + sum(i=1,k,8k).
655%
656% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
657% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
658% Initializes data structures for nodes only as they are needed; (2)
659% Chooses a maximum depth for the tree as a function of the desired
660% number of colors in the output image (currently log2(colormap size)).
661%
662% For each pixel in the input image, storage_class scans downward from
663% the root of the color description tree. At each level of the tree it
664% identifies the single node which represents a cube in RGB space
665% containing It updates the following data for each such node:
666%
667% n1 : Number of pixels whose color is contained in the RGB cube
668% which this node represents;
669%
670% n2 : Number of pixels whose color is not represented in a node at
671% lower depth in the tree; initially, n2 = 0 for all nodes except
672% leaves of the tree.
673%
674% Sr, Sg, Sb : Sums of the red, green, and blue component values for
675% all pixels not classified at a lower depth. The combination of
676% these sums and n2 will ultimately characterize the mean color of a
677% set of pixels represented by this node.
678%
679% E: the distance squared in RGB space between each pixel contained
680% within a node and the nodes' center. This represents the quantization
681% error for a node.
682%
683% The format of the ClassifyImageColors() method is:
684%
685% MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
686% const Image *image,ExceptionInfo *exception)
687%
688% A description of each parameter follows.
689%
690% o cube_info: A pointer to the Cube structure.
691%
692% o image: the image.
693%
694*/
695
696static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
697{
698 MagickBooleanType
699 associate_alpha;
700
701 associate_alpha=image->matte;
702 if (cube_info->quantize_info->colorspace == TransparentColorspace)
703 associate_alpha=MagickFalse;
704 if ((cube_info->quantize_info->number_colors == 2) &&
705 (cube_info->quantize_info->colorspace == GRAYColorspace))
706 associate_alpha=MagickFalse;
707 cube_info->associate_alpha=associate_alpha;
708}
709
710static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
711 const Image *image,ExceptionInfo *exception)
712{
713#define ClassifyImageTag "Classify/Image"
714
cristyc4c8d132010-01-07 01:58:38 +0000715 CacheView
716 *image_view;
717
cristy3ed852e2009-09-05 21:47:34 +0000718 long
719 y;
720
721 MagickBooleanType
722 proceed;
723
724 MagickRealType
725 bisect;
726
727 NodeInfo
728 *node_info;
729
730 RealPixelPacket
731 error,
732 mid,
733 midpoint,
734 pixel;
735
736 size_t
737 count;
738
739 unsigned long
740 id,
741 index,
742 level;
743
cristy3ed852e2009-09-05 21:47:34 +0000744 /*
745 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
746 */
747 SetAssociatedAlpha(image,cube_info);
748 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
749 (cube_info->quantize_info->colorspace != CMYKColorspace))
750 (void) TransformImageColorspace((Image *) image,
751 cube_info->quantize_info->colorspace);
752 else
753 if ((image->colorspace != GRAYColorspace) &&
754 (image->colorspace != CMYColorspace) &&
755 (image->colorspace != RGBColorspace))
756 (void) TransformImageColorspace((Image *) image,RGBColorspace);
757 midpoint.red=(MagickRealType) QuantumRange/2.0;
758 midpoint.green=(MagickRealType) QuantumRange/2.0;
759 midpoint.blue=(MagickRealType) QuantumRange/2.0;
760 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
761 error.opacity=0.0;
762 image_view=AcquireCacheView(image);
763 for (y=0; y < (long) image->rows; y++)
764 {
765 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000766 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000767
768 register long
769 x;
770
771 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
772 if (p == (const PixelPacket *) NULL)
773 break;
774 if (cube_info->nodes > MaxNodes)
775 {
776 /*
777 Prune one level if the color tree is too large.
778 */
779 PruneLevel(image,cube_info,cube_info->root);
780 cube_info->depth--;
781 }
782 for (x=0; x < (long) image->columns; x+=(long) count)
783 {
784 /*
785 Start at the root and descend the color cube tree.
786 */
787 for (count=1; (x+count) < image->columns; count++)
788 if (IsSameColor(image,p,p+count) == MagickFalse)
789 break;
790 AssociateAlphaPixel(cube_info,p,&pixel);
791 index=MaxTreeDepth-1;
792 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
793 mid=midpoint;
794 node_info=cube_info->root;
795 for (level=1; level <= MaxTreeDepth; level++)
796 {
797 bisect*=0.5;
798 id=ColorToNodeId(cube_info,&pixel,index);
799 mid.red+=(id & 1) != 0 ? bisect : -bisect;
800 mid.green+=(id & 2) != 0 ? bisect : -bisect;
801 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
802 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
803 if (node_info->child[id] == (NodeInfo *) NULL)
804 {
805 /*
806 Set colors of new node to contain pixel.
807 */
808 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
809 if (node_info->child[id] == (NodeInfo *) NULL)
810 (void) ThrowMagickException(exception,GetMagickModule(),
811 ResourceLimitError,"MemoryAllocationFailed","`%s'",
812 image->filename);
813 if (level == MaxTreeDepth)
814 cube_info->colors++;
815 }
816 /*
817 Approximate the quantization error represented by this node.
818 */
819 node_info=node_info->child[id];
820 error.red=QuantumScale*(pixel.red-mid.red);
821 error.green=QuantumScale*(pixel.green-mid.green);
822 error.blue=QuantumScale*(pixel.blue-mid.blue);
823 if (cube_info->associate_alpha != MagickFalse)
824 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
825 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
826 count*error.green*error.green+count*error.blue*error.blue+
827 count*error.opacity*error.opacity));
828 cube_info->root->quantize_error+=node_info->quantize_error;
829 index--;
830 }
831 /*
832 Sum RGB for this leaf for later derivation of the mean cube color.
833 */
834 node_info->number_unique+=count;
835 node_info->total_color.red+=count*QuantumScale*pixel.red;
836 node_info->total_color.green+=count*QuantumScale*pixel.green;
837 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
838 if (cube_info->associate_alpha != MagickFalse)
839 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
840 p+=count;
841 }
842 if (cube_info->colors > cube_info->maximum_colors)
843 {
844 PruneToCubeDepth(image,cube_info,cube_info->root);
845 break;
846 }
847 proceed=SetImageProgress(image,ClassifyImageTag,y,image->rows);
848 if (proceed == MagickFalse)
849 break;
850 }
851 for (y++; y < (long) image->rows; y++)
852 {
853 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000854 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000855
856 register long
857 x;
858
859 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
860 if (p == (const PixelPacket *) NULL)
861 break;
862 if (cube_info->nodes > MaxNodes)
863 {
864 /*
865 Prune one level if the color tree is too large.
866 */
867 PruneLevel(image,cube_info,cube_info->root);
868 cube_info->depth--;
869 }
870 for (x=0; x < (long) image->columns; x+=(long) count)
871 {
872 /*
873 Start at the root and descend the color cube tree.
874 */
875 for (count=1; (x+count) < image->columns; count++)
876 if (IsSameColor(image,p,p+count) == MagickFalse)
877 break;
878 AssociateAlphaPixel(cube_info,p,&pixel);
879 index=MaxTreeDepth-1;
880 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
881 mid=midpoint;
882 node_info=cube_info->root;
883 for (level=1; level <= cube_info->depth; level++)
884 {
885 bisect*=0.5;
886 id=ColorToNodeId(cube_info,&pixel,index);
887 mid.red+=(id & 1) != 0 ? bisect : -bisect;
888 mid.green+=(id & 2) != 0 ? bisect : -bisect;
889 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
890 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
891 if (node_info->child[id] == (NodeInfo *) NULL)
892 {
893 /*
894 Set colors of new node to contain pixel.
895 */
896 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
897 if (node_info->child[id] == (NodeInfo *) NULL)
898 (void) ThrowMagickException(exception,GetMagickModule(),
899 ResourceLimitError,"MemoryAllocationFailed","%s",
900 image->filename);
901 if (level == cube_info->depth)
902 cube_info->colors++;
903 }
904 /*
905 Approximate the quantization error represented by this node.
906 */
907 node_info=node_info->child[id];
908 error.red=QuantumScale*(pixel.red-mid.red);
909 error.green=QuantumScale*(pixel.green-mid.green);
910 error.blue=QuantumScale*(pixel.blue-mid.blue);
911 if (cube_info->associate_alpha != MagickFalse)
912 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
913 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
914 count*error.green*error.green+error.blue*error.blue+
915 count*error.opacity*error.opacity));
916 cube_info->root->quantize_error+=node_info->quantize_error;
917 index--;
918 }
919 /*
920 Sum RGB for this leaf for later derivation of the mean cube color.
921 */
922 node_info->number_unique+=count;
923 node_info->total_color.red+=count*QuantumScale*pixel.red;
924 node_info->total_color.green+=count*QuantumScale*pixel.green;
925 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
926 if (cube_info->associate_alpha != MagickFalse)
927 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
928 p+=count;
929 }
930 proceed=SetImageProgress(image,ClassifyImageTag,y,image->rows);
931 if (proceed == MagickFalse)
932 break;
933 }
934 image_view=DestroyCacheView(image_view);
935 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
936 (cube_info->quantize_info->colorspace != CMYKColorspace))
937 (void) TransformImageColorspace((Image *) image,RGBColorspace);
938 return(MagickTrue);
939}
940
941/*
942%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
943% %
944% %
945% %
946% C l o n e Q u a n t i z e I n f o %
947% %
948% %
949% %
950%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
951%
952% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
953% or if quantize info is NULL, a new one.
954%
955% The format of the CloneQuantizeInfo method is:
956%
957% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
958%
959% A description of each parameter follows:
960%
961% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
962% quantize info, or if image info is NULL a new one.
963%
964% o quantize_info: a structure of type info.
965%
966*/
967MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
968{
969 QuantizeInfo
970 *clone_info;
971
cristy90823212009-12-12 20:48:33 +0000972 clone_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*clone_info));
cristy3ed852e2009-09-05 21:47:34 +0000973 if (clone_info == (QuantizeInfo *) NULL)
974 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
975 GetQuantizeInfo(clone_info);
976 if (quantize_info == (QuantizeInfo *) NULL)
977 return(clone_info);
978 clone_info->number_colors=quantize_info->number_colors;
979 clone_info->tree_depth=quantize_info->tree_depth;
980 clone_info->dither=quantize_info->dither;
981 clone_info->dither_method=quantize_info->dither_method;
982 clone_info->colorspace=quantize_info->colorspace;
983 clone_info->measure_error=quantize_info->measure_error;
984 return(clone_info);
985}
986
987/*
988%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
989% %
990% %
991% %
992+ C l o s e s t C o l o r %
993% %
994% %
995% %
996%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
997%
998% ClosestColor() traverses the color cube tree at a particular node and
999% determines which colormap entry best represents the input color.
1000%
1001% The format of the ClosestColor method is:
1002%
1003% void ClosestColor(const Image *image,CubeInfo *cube_info,
1004% const NodeInfo *node_info)
1005%
1006% A description of each parameter follows.
1007%
1008% o image: the image.
1009%
1010% o cube_info: A pointer to the Cube structure.
1011%
1012% o node_info: the address of a structure of type NodeInfo which points to a
1013% node in the color cube tree that is to be pruned.
1014%
1015*/
1016static void ClosestColor(const Image *image,CubeInfo *cube_info,
1017 const NodeInfo *node_info)
1018{
1019 register long
1020 i;
1021
1022 unsigned long
1023 number_children;
1024
1025 /*
1026 Traverse any children.
1027 */
1028 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1029 for (i=0; i < (long) number_children; i++)
1030 if (node_info->child[i] != (NodeInfo *) NULL)
1031 ClosestColor(image,cube_info,node_info->child[i]);
1032 if (node_info->number_unique != 0)
1033 {
1034 MagickRealType
1035 pixel;
1036
1037 register MagickRealType
1038 alpha,
1039 beta,
1040 distance;
1041
1042 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001043 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00001044
1045 register RealPixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001046 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001047
1048 /*
1049 Determine if this color is "closest".
1050 */
1051 p=image->colormap+node_info->color_number;
1052 q=(&cube_info->target);
1053 alpha=1.0;
1054 beta=1.0;
1055 if (cube_info->associate_alpha == MagickFalse)
1056 {
cristyce70c172010-01-07 17:15:30 +00001057 alpha=(MagickRealType) (QuantumScale*(QuantumRange-GetOpacityPixelComponent(p)));
cristy3ed852e2009-09-05 21:47:34 +00001058 beta=(MagickRealType) (QuantumScale*(QuantumRange-q->opacity));
1059 }
1060 pixel=alpha*p->red-beta*q->red;
1061 distance=pixel*pixel;
1062 if (distance < cube_info->distance)
1063 {
1064 pixel=alpha*p->green-beta*q->green;
1065 distance+=pixel*pixel;
1066 if (distance < cube_info->distance)
1067 {
1068 pixel=alpha*p->blue-beta*q->blue;
1069 distance+=pixel*pixel;
1070 if (distance < cube_info->distance)
1071 {
1072 pixel=alpha-beta;
1073 distance+=pixel*pixel;
1074 if (distance < cube_info->distance)
1075 {
1076 cube_info->distance=distance;
1077 cube_info->color_number=node_info->color_number;
1078 }
1079 }
1080 }
1081 }
1082 }
1083}
1084
1085/*
1086%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1087% %
1088% %
1089% %
1090% C o m p r e s s I m a g e C o l o r m a p %
1091% %
1092% %
1093% %
1094%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1095%
1096% CompressImageColormap() compresses an image colormap by removing any
1097% duplicate or unused color entries.
1098%
1099% The format of the CompressImageColormap method is:
1100%
1101% MagickBooleanType CompressImageColormap(Image *image)
1102%
1103% A description of each parameter follows:
1104%
1105% o image: the image.
1106%
1107*/
1108MagickExport MagickBooleanType CompressImageColormap(Image *image)
1109{
1110 QuantizeInfo
1111 quantize_info;
1112
1113 assert(image != (Image *) NULL);
1114 assert(image->signature == MagickSignature);
1115 if (image->debug != MagickFalse)
1116 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1117 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1118 return(MagickFalse);
1119 GetQuantizeInfo(&quantize_info);
1120 quantize_info.number_colors=image->colors;
1121 quantize_info.tree_depth=MaxTreeDepth;
1122 return(QuantizeImage(&quantize_info,image));
1123}
1124
1125/*
1126%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1127% %
1128% %
1129% %
1130+ D e f i n e I m a g e C o l o r m a p %
1131% %
1132% %
1133% %
1134%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1135%
1136% DefineImageColormap() traverses the color cube tree and notes each colormap
1137% entry. A colormap entry is any node in the color cube tree where the
1138% of unique colors is not zero. DefineImageColormap() returns the number of
1139% colors in the image colormap.
1140%
1141% The format of the DefineImageColormap method is:
1142%
1143% unsigned long DefineImageColormap(Image *image,CubeInfo *cube_info,
1144% NodeInfo *node_info)
1145%
1146% A description of each parameter follows.
1147%
1148% o image: the image.
1149%
1150% o cube_info: A pointer to the Cube structure.
1151%
1152% o node_info: the address of a structure of type NodeInfo which points to a
1153% node in the color cube tree that is to be pruned.
1154%
1155*/
1156static unsigned long DefineImageColormap(Image *image,CubeInfo *cube_info,
1157 NodeInfo *node_info)
1158{
1159 register long
1160 i;
1161
1162 unsigned long
1163 number_children;
1164
1165 /*
1166 Traverse any children.
1167 */
1168 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1169 for (i=0; i < (long) number_children; i++)
1170 if (node_info->child[i] != (NodeInfo *) NULL)
1171 DefineImageColormap(image,cube_info,node_info->child[i]);
1172 if (node_info->number_unique != 0)
1173 {
1174 register MagickRealType
1175 alpha;
1176
1177 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001178 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001179
1180 /*
1181 Colormap entry is defined by the mean color in this cube.
1182 */
1183 q=image->colormap+image->colors;
1184 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1185 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1186 if (cube_info->associate_alpha == MagickFalse)
1187 {
cristyce70c172010-01-07 17:15:30 +00001188 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001189 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001190 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001191 node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001192 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001193 node_info->total_color.blue));
cristyce70c172010-01-07 17:15:30 +00001194 SetOpacityPixelComponent(q,OpaqueOpacity);
cristy3ed852e2009-09-05 21:47:34 +00001195 }
1196 else
1197 {
1198 MagickRealType
1199 opacity;
1200
1201 opacity=(MagickRealType) (alpha*QuantumRange*
1202 node_info->total_color.opacity);
cristyce70c172010-01-07 17:15:30 +00001203 q->opacity=ClampToQuantum(opacity);
cristy3ed852e2009-09-05 21:47:34 +00001204 if (q->opacity == OpaqueOpacity)
1205 {
cristyce70c172010-01-07 17:15:30 +00001206 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001207 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001208 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001209 node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001210 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001211 node_info->total_color.blue));
1212 }
1213 else
1214 {
1215 MagickRealType
1216 gamma;
1217
1218 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1219 (MagickRealType) q->opacity));
1220 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
cristyce70c172010-01-07 17:15:30 +00001221 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001222 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001223 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
cristy3ed852e2009-09-05 21:47:34 +00001224 QuantumRange*node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001225 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001226 node_info->total_color.blue));
1227 if (node_info->number_unique > cube_info->transparent_pixels)
1228 {
1229 cube_info->transparent_pixels=node_info->number_unique;
1230 cube_info->transparent_index=(long) image->colors;
1231 }
1232 }
1233 }
1234 node_info->color_number=image->colors++;
1235 }
1236 return(image->colors);
1237}
1238
1239/*
1240%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1241% %
1242% %
1243% %
1244+ D e s t r o y C u b e I n f o %
1245% %
1246% %
1247% %
1248%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1249%
1250% DestroyCubeInfo() deallocates memory associated with an image.
1251%
1252% The format of the DestroyCubeInfo method is:
1253%
1254% DestroyCubeInfo(CubeInfo *cube_info)
1255%
1256% A description of each parameter follows:
1257%
1258% o cube_info: the address of a structure of type CubeInfo.
1259%
1260*/
1261static void DestroyCubeInfo(CubeInfo *cube_info)
1262{
1263 register Nodes
1264 *nodes;
1265
1266 /*
1267 Release color cube tree storage.
1268 */
1269 do
1270 {
1271 nodes=cube_info->node_queue->next;
1272 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1273 cube_info->node_queue->nodes);
1274 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1275 cube_info->node_queue);
1276 cube_info->node_queue=nodes;
1277 } while (cube_info->node_queue != (Nodes *) NULL);
1278 if (cube_info->cache != (long *) NULL)
1279 cube_info->cache=(long *) RelinquishMagickMemory(cube_info->cache);
1280 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1281 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1282}
1283
1284/*
1285%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1286% %
1287% %
1288% %
1289% D e s t r o y Q u a n t i z e I n f o %
1290% %
1291% %
1292% %
1293%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1294%
1295% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1296% structure.
1297%
1298% The format of the DestroyQuantizeInfo method is:
1299%
1300% QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1301%
1302% A description of each parameter follows:
1303%
1304% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1305%
1306*/
1307MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1308{
1309 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1310 assert(quantize_info != (QuantizeInfo *) NULL);
1311 assert(quantize_info->signature == MagickSignature);
1312 quantize_info->signature=(~MagickSignature);
1313 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1314 return(quantize_info);
1315}
1316
1317/*
1318%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1319% %
1320% %
1321% %
1322+ D i t h e r I m a g e %
1323% %
1324% %
1325% %
1326%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1327%
1328% DitherImage() distributes the difference between an original image and
1329% the corresponding color reduced algorithm to neighboring pixels using
1330% serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1331% MagickTrue if the image is dithered otherwise MagickFalse.
1332%
1333% The format of the DitherImage method is:
1334%
1335% MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1336%
1337% A description of each parameter follows.
1338%
1339% o image: the image.
1340%
1341% o cube_info: A pointer to the Cube structure.
1342%
1343*/
1344
1345static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1346{
1347#define DitherImageTag "Dither/Image"
1348
cristyc4c8d132010-01-07 01:58:38 +00001349 CacheView
1350 *image_view;
1351
cristy3ed852e2009-09-05 21:47:34 +00001352 ExceptionInfo
1353 *exception;
1354
1355 long
1356 u,
1357 v,
1358 y;
1359
1360 MagickBooleanType
1361 proceed;
1362
1363 RealPixelPacket
1364 color,
1365 *current,
1366 pixel,
1367 *previous,
1368 *scanlines;
1369
1370 register CubeInfo
1371 *p;
1372
1373 unsigned long
1374 index;
1375
cristy3ed852e2009-09-05 21:47:34 +00001376 /*
1377 Distribute quantization error using Floyd-Steinberg.
1378 */
1379 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1380 2*sizeof(*scanlines));
1381 if (scanlines == (RealPixelPacket *) NULL)
1382 return(MagickFalse);
1383 p=cube_info;
1384 exception=(&image->exception);
1385 image_view=AcquireCacheView(image);
1386 for (y=0; y < (long) image->rows; y++)
1387 {
1388 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00001389 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00001390
1391 register long
1392 i,
1393 x;
1394
1395 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001396 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001397
1398 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1399 if (q == (PixelPacket *) NULL)
1400 return(MagickFalse);
1401 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1402 current=scanlines+(y & 0x01)*image->columns;
1403 previous=scanlines+((y+1) & 0x01)*image->columns;
1404 v=(y & 0x01) ? -1 : 1;
1405 for (x=0; x < (long) image->columns; x++)
1406 {
1407 u=(y & 0x01) ? (long) image->columns-1-x : x;
1408 AssociateAlphaPixel(cube_info,q+u,&pixel);
1409 if (x > 0)
1410 {
1411 pixel.red+=7*current[u-v].red/16;
1412 pixel.green+=7*current[u-v].green/16;
1413 pixel.blue+=7*current[u-v].blue/16;
1414 if (cube_info->associate_alpha != MagickFalse)
1415 pixel.opacity+=7*current[u-v].opacity/16;
1416 }
1417 if (y > 0)
1418 {
1419 if (x < (long) (image->columns-1))
1420 {
1421 pixel.red+=previous[u+v].red/16;
1422 pixel.green+=previous[u+v].green/16;
1423 pixel.blue+=previous[u+v].blue/16;
1424 if (cube_info->associate_alpha != MagickFalse)
1425 pixel.opacity+=previous[u+v].opacity/16;
1426 }
1427 pixel.red+=5*previous[u].red/16;
1428 pixel.green+=5*previous[u].green/16;
1429 pixel.blue+=5*previous[u].blue/16;
1430 if (cube_info->associate_alpha != MagickFalse)
1431 pixel.opacity+=5*previous[u].opacity/16;
1432 if (x > 0)
1433 {
1434 pixel.red+=3*previous[u-v].red/16;
1435 pixel.green+=3*previous[u-v].green/16;
1436 pixel.blue+=3*previous[u-v].blue/16;
1437 if (cube_info->associate_alpha != MagickFalse)
1438 pixel.opacity+=3*previous[u-v].opacity/16;
1439 }
1440 }
cristy75ffdb72010-01-07 17:40:12 +00001441 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1442 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1443 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristy3ed852e2009-09-05 21:47:34 +00001444 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001445 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1446 i=(long) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
1447 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1448 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
cristy3ed852e2009-09-05 21:47:34 +00001449 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001450 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
cristy3ed852e2009-09-05 21:47:34 +00001451 << 18);
1452 if (p->cache[i] < 0)
1453 {
1454 register NodeInfo
1455 *node_info;
1456
1457 register unsigned long
1458 id;
1459
1460 /*
1461 Identify the deepest node containing the pixel's color.
1462 */
1463 node_info=p->root;
1464 for (index=MaxTreeDepth-1; (long) index > 0; index--)
1465 {
1466 id=ColorToNodeId(cube_info,&pixel,index);
1467 if (node_info->child[id] == (NodeInfo *) NULL)
1468 break;
1469 node_info=node_info->child[id];
1470 }
1471 /*
1472 Find closest color among siblings and their children.
1473 */
1474 p->target=pixel;
1475 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1476 1.0)+1.0);
1477 ClosestColor(image,p,node_info->parent);
1478 p->cache[i]=(long) p->color_number;
1479 }
1480 /*
1481 Assign pixel to closest colormap entry.
1482 */
1483 index=(unsigned long) p->cache[i];
1484 if (image->storage_class == PseudoClass)
1485 indexes[u]=(IndexPacket) index;
1486 if (cube_info->quantize_info->measure_error == MagickFalse)
1487 {
1488 (q+u)->red=image->colormap[index].red;
1489 (q+u)->green=image->colormap[index].green;
1490 (q+u)->blue=image->colormap[index].blue;
1491 if (cube_info->associate_alpha != MagickFalse)
1492 (q+u)->opacity=image->colormap[index].opacity;
1493 }
1494 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1495 return(MagickFalse);
1496 /*
1497 Store the error.
1498 */
1499 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1500 current[u].red=pixel.red-color.red;
1501 current[u].green=pixel.green-color.green;
1502 current[u].blue=pixel.blue-color.blue;
1503 if (cube_info->associate_alpha != MagickFalse)
1504 current[u].opacity=pixel.opacity-color.opacity;
1505 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1506 if (proceed == MagickFalse)
1507 return(MagickFalse);
1508 p->offset++;
1509 }
1510 }
1511 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1512 image_view=DestroyCacheView(image_view);
1513 return(MagickTrue);
1514}
1515
1516static MagickBooleanType
1517 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1518
1519static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1520 const unsigned long level,const unsigned int direction)
1521{
1522 if (level == 1)
1523 switch (direction)
1524 {
1525 case WestGravity:
1526 {
1527 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1528 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1529 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1530 break;
1531 }
1532 case EastGravity:
1533 {
1534 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1535 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1536 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1537 break;
1538 }
1539 case NorthGravity:
1540 {
1541 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1542 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1543 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1544 break;
1545 }
1546 case SouthGravity:
1547 {
1548 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1549 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1550 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1551 break;
1552 }
1553 default:
1554 break;
1555 }
1556 else
1557 switch (direction)
1558 {
1559 case WestGravity:
1560 {
1561 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1562 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1563 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1564 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1565 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1566 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1567 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1568 break;
1569 }
1570 case EastGravity:
1571 {
1572 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1573 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1574 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1575 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1576 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1577 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1578 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1579 break;
1580 }
1581 case NorthGravity:
1582 {
1583 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1584 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1585 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1586 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1587 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1588 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1589 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1590 break;
1591 }
1592 case SouthGravity:
1593 {
1594 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1595 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1596 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1597 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1598 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1599 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1600 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1601 break;
1602 }
1603 default:
1604 break;
1605 }
1606}
1607
1608static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1609 CubeInfo *cube_info,const unsigned int direction)
1610{
1611#define DitherImageTag "Dither/Image"
1612
1613 MagickBooleanType
1614 proceed;
1615
1616 RealPixelPacket
1617 color,
1618 pixel;
1619
1620 register CubeInfo
1621 *p;
1622
1623 unsigned long
1624 index;
1625
1626 p=cube_info;
1627 if ((p->x >= 0) && (p->x < (long) image->columns) &&
1628 (p->y >= 0) && (p->y < (long) image->rows))
1629 {
1630 ExceptionInfo
1631 *exception;
1632
1633 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00001634 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00001635
1636 register long
1637 i;
1638
1639 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001640 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001641
1642 /*
1643 Distribute error.
1644 */
1645 exception=(&image->exception);
1646 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1647 if (q == (PixelPacket *) NULL)
1648 return(MagickFalse);
1649 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1650 AssociateAlphaPixel(cube_info,q,&pixel);
1651 for (i=0; i < ErrorQueueLength; i++)
1652 {
1653 pixel.red+=p->weights[i]*p->error[i].red;
1654 pixel.green+=p->weights[i]*p->error[i].green;
1655 pixel.blue+=p->weights[i]*p->error[i].blue;
1656 if (cube_info->associate_alpha != MagickFalse)
1657 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1658 }
cristy75ffdb72010-01-07 17:40:12 +00001659 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1660 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1661 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristy3ed852e2009-09-05 21:47:34 +00001662 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001663 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1664 i=(long) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
1665 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1666 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
cristy3ed852e2009-09-05 21:47:34 +00001667 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001668 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
cristy3ed852e2009-09-05 21:47:34 +00001669 << 18);
1670 if (p->cache[i] < 0)
1671 {
1672 register NodeInfo
1673 *node_info;
1674
1675 register unsigned long
1676 id;
1677
1678 /*
1679 Identify the deepest node containing the pixel's color.
1680 */
1681 node_info=p->root;
1682 for (index=MaxTreeDepth-1; (long) index > 0; index--)
1683 {
1684 id=ColorToNodeId(cube_info,&pixel,index);
1685 if (node_info->child[id] == (NodeInfo *) NULL)
1686 break;
1687 node_info=node_info->child[id];
1688 }
1689 /*
1690 Find closest color among siblings and their children.
1691 */
1692 p->target=pixel;
1693 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1694 QuantumRange+1.0)+1.0);
1695 ClosestColor(image,p,node_info->parent);
1696 p->cache[i]=(long) p->color_number;
1697 }
1698 /*
1699 Assign pixel to closest colormap entry.
1700 */
1701 index=(unsigned long) (1*p->cache[i]);
1702 if (image->storage_class == PseudoClass)
1703 *indexes=(IndexPacket) index;
1704 if (cube_info->quantize_info->measure_error == MagickFalse)
1705 {
1706 q->red=image->colormap[index].red;
1707 q->green=image->colormap[index].green;
1708 q->blue=image->colormap[index].blue;
1709 if (cube_info->associate_alpha != MagickFalse)
1710 q->opacity=image->colormap[index].opacity;
1711 }
1712 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1713 return(MagickFalse);
1714 /*
1715 Propagate the error as the last entry of the error queue.
1716 */
1717 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1718 sizeof(p->error[0]));
1719 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1720 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1721 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1722 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1723 if (cube_info->associate_alpha != MagickFalse)
1724 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1725 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1726 if (proceed == MagickFalse)
1727 return(MagickFalse);
1728 p->offset++;
1729 }
1730 switch (direction)
1731 {
1732 case WestGravity: p->x--; break;
1733 case EastGravity: p->x++; break;
1734 case NorthGravity: p->y--; break;
1735 case SouthGravity: p->y++; break;
1736 }
1737 return(MagickTrue);
1738}
1739
1740static inline long MagickMax(const long x,const long y)
1741{
1742 if (x > y)
1743 return(x);
1744 return(y);
1745}
1746
1747static inline long MagickMin(const long x,const long y)
1748{
1749 if (x < y)
1750 return(x);
1751 return(y);
1752}
1753
1754static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1755{
cristyc4c8d132010-01-07 01:58:38 +00001756 CacheView
1757 *image_view;
1758
cristy3ed852e2009-09-05 21:47:34 +00001759 MagickBooleanType
1760 status;
1761
1762 register long
1763 i;
1764
1765 unsigned long
1766 depth;
1767
cristy3ed852e2009-09-05 21:47:34 +00001768 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1769 return(FloydSteinbergDither(image,cube_info));
1770 /*
1771 Distribute quantization error along a Hilbert curve.
1772 */
1773 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1774 sizeof(*cube_info->error));
1775 cube_info->x=0;
1776 cube_info->y=0;
1777 i=MagickMax((long) image->columns,(long) image->rows);
1778 for (depth=1; i != 0; depth++)
1779 i>>=1;
1780 if ((long) (1L << depth) < MagickMax((long) image->columns,(long) image->rows))
1781 depth++;
1782 cube_info->offset=0;
1783 cube_info->span=(MagickSizeType) image->columns*image->rows;
1784 image_view=AcquireCacheView(image);
1785 if (depth > 1)
1786 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1787 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1788 image_view=DestroyCacheView(image_view);
1789 return(status);
1790}
1791
1792/*
1793%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1794% %
1795% %
1796% %
1797+ G e t C u b e I n f o %
1798% %
1799% %
1800% %
1801%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1802%
1803% GetCubeInfo() initialize the Cube data structure.
1804%
1805% The format of the GetCubeInfo method is:
1806%
1807% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1808% const unsigned long depth,const unsigned long maximum_colors)
1809%
1810% A description of each parameter follows.
1811%
1812% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1813%
1814% o depth: Normally, this integer value is zero or one. A zero or
1815% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1816% A tree of this depth generally allows the best representation of the
1817% reference image with the least amount of memory and the fastest
1818% computational speed. In some cases, such as an image with low color
1819% dispersion (a few number of colors), a value other than
1820% Log4(number_colors) is required. To expand the color tree completely,
1821% use a value of 8.
1822%
1823% o maximum_colors: maximum colors.
1824%
1825*/
1826static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1827 const unsigned long depth,const unsigned long maximum_colors)
1828{
1829 CubeInfo
1830 *cube_info;
1831
1832 MagickRealType
1833 sum,
1834 weight;
1835
1836 size_t
1837 length;
1838
1839 register long
1840 i;
1841
1842 /*
1843 Initialize tree to describe color cube_info.
1844 */
cristy90823212009-12-12 20:48:33 +00001845 cube_info=(CubeInfo *) AcquireAlignedMemory(1,sizeof(*cube_info));
cristy3ed852e2009-09-05 21:47:34 +00001846 if (cube_info == (CubeInfo *) NULL)
1847 return((CubeInfo *) NULL);
1848 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1849 cube_info->depth=depth;
1850 if (cube_info->depth > MaxTreeDepth)
1851 cube_info->depth=MaxTreeDepth;
1852 if (cube_info->depth < 2)
1853 cube_info->depth=2;
1854 cube_info->maximum_colors=maximum_colors;
1855 /*
1856 Initialize root node.
1857 */
1858 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1859 if (cube_info->root == (NodeInfo *) NULL)
1860 return((CubeInfo *) NULL);
1861 cube_info->root->parent=cube_info->root;
1862 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1863 if (cube_info->quantize_info->dither == MagickFalse)
1864 return(cube_info);
1865 /*
1866 Initialize dither resources.
1867 */
1868 length=(size_t) (1UL << (4*(8-CacheShift)));
1869 cube_info->cache=(long *) AcquireQuantumMemory(length,
1870 sizeof(*cube_info->cache));
1871 if (cube_info->cache == (long *) NULL)
1872 return((CubeInfo *) NULL);
1873 /*
1874 Initialize color cache.
1875 */
1876 for (i=0; i < (long) length; i++)
1877 cube_info->cache[i]=(-1);
1878 /*
1879 Distribute weights along a curve of exponential decay.
1880 */
1881 weight=1.0;
1882 for (i=0; i < ErrorQueueLength; i++)
1883 {
1884 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1885 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1886 }
1887 /*
1888 Normalize the weighting factors.
1889 */
1890 weight=0.0;
1891 for (i=0; i < ErrorQueueLength; i++)
1892 weight+=cube_info->weights[i];
1893 sum=0.0;
1894 for (i=0; i < ErrorQueueLength; i++)
1895 {
1896 cube_info->weights[i]/=weight;
1897 sum+=cube_info->weights[i];
1898 }
1899 cube_info->weights[0]+=1.0-sum;
1900 return(cube_info);
1901}
1902
1903/*
1904%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1905% %
1906% %
1907% %
1908+ G e t N o d e I n f o %
1909% %
1910% %
1911% %
1912%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1913%
1914% GetNodeInfo() allocates memory for a new node in the color cube tree and
1915% presets all fields to zero.
1916%
1917% The format of the GetNodeInfo method is:
1918%
1919% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const unsigned long id,
1920% const unsigned long level,NodeInfo *parent)
1921%
1922% A description of each parameter follows.
1923%
1924% o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1925%
1926% o id: Specifies the child number of the node.
1927%
1928% o level: Specifies the level in the storage_class the node resides.
1929%
1930*/
1931static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const unsigned long id,
1932 const unsigned long level,NodeInfo *parent)
1933{
1934 NodeInfo
1935 *node_info;
1936
1937 if (cube_info->free_nodes == 0)
1938 {
1939 Nodes
1940 *nodes;
1941
1942 /*
1943 Allocate a new queue of nodes.
1944 */
cristy90823212009-12-12 20:48:33 +00001945 nodes=(Nodes *) AcquireAlignedMemory(1,sizeof(*nodes));
cristy3ed852e2009-09-05 21:47:34 +00001946 if (nodes == (Nodes *) NULL)
1947 return((NodeInfo *) NULL);
1948 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1949 sizeof(*nodes->nodes));
1950 if (nodes->nodes == (NodeInfo *) NULL)
1951 return((NodeInfo *) NULL);
1952 nodes->next=cube_info->node_queue;
1953 cube_info->node_queue=nodes;
1954 cube_info->next_node=nodes->nodes;
1955 cube_info->free_nodes=NodesInAList;
1956 }
1957 cube_info->nodes++;
1958 cube_info->free_nodes--;
1959 node_info=cube_info->next_node++;
1960 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1961 node_info->parent=parent;
1962 node_info->id=id;
1963 node_info->level=level;
1964 return(node_info);
1965}
1966
1967/*
1968%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1969% %
1970% %
1971% %
1972% G e t I m a g e Q u a n t i z e E r r o r %
1973% %
1974% %
1975% %
1976%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1977%
1978% GetImageQuantizeError() measures the difference between the original
1979% and quantized images. This difference is the total quantization error.
1980% The error is computed by summing over all pixels in an image the distance
1981% squared in RGB space between each reference pixel value and its quantized
1982% value. These values are computed:
1983%
1984% o mean_error_per_pixel: This value is the mean error for any single
1985% pixel in the image.
1986%
1987% o normalized_mean_square_error: This value is the normalized mean
1988% quantization error for any single pixel in the image. This distance
1989% measure is normalized to a range between 0 and 1. It is independent
1990% of the range of red, green, and blue values in the image.
1991%
1992% o normalized_maximum_square_error: Thsi value is the normalized
1993% maximum quantization error for any single pixel in the image. This
1994% distance measure is normalized to a range between 0 and 1. It is
1995% independent of the range of red, green, and blue values in your image.
1996%
1997% The format of the GetImageQuantizeError method is:
1998%
1999% MagickBooleanType GetImageQuantizeError(Image *image)
2000%
2001% A description of each parameter follows.
2002%
2003% o image: the image.
2004%
2005*/
2006MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2007{
cristyc4c8d132010-01-07 01:58:38 +00002008 CacheView
2009 *image_view;
2010
cristy3ed852e2009-09-05 21:47:34 +00002011 ExceptionInfo
2012 *exception;
2013
2014 IndexPacket
2015 *indexes;
2016
2017 long
2018 y;
2019
2020 MagickRealType
2021 alpha,
2022 area,
2023 beta,
2024 distance,
2025 maximum_error,
2026 mean_error,
2027 mean_error_per_pixel;
2028
2029 unsigned long
2030 index;
2031
cristy3ed852e2009-09-05 21:47:34 +00002032 assert(image != (Image *) NULL);
2033 assert(image->signature == MagickSignature);
2034 if (image->debug != MagickFalse)
2035 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2036 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2037 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2038 if (image->storage_class == DirectClass)
2039 return(MagickTrue);
2040 alpha=1.0;
2041 beta=1.0;
2042 area=3.0*image->columns*image->rows;
2043 maximum_error=0.0;
2044 mean_error_per_pixel=0.0;
2045 mean_error=0.0;
2046 exception=(&image->exception);
2047 image_view=AcquireCacheView(image);
2048 for (y=0; y < (long) image->rows; y++)
2049 {
2050 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00002051 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00002052
2053 register long
2054 x;
2055
2056 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2057 if (p == (const PixelPacket *) NULL)
2058 break;
2059 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2060 for (x=0; x < (long) image->columns; x++)
2061 {
2062 index=1UL*indexes[x];
2063 if (image->matte != MagickFalse)
2064 {
cristyce70c172010-01-07 17:15:30 +00002065 alpha=(MagickRealType) (QuantumScale*(QuantumRange-GetOpacityPixelComponent(p)));
cristy3ed852e2009-09-05 21:47:34 +00002066 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2067 image->colormap[index].opacity));
2068 }
2069 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2070 mean_error_per_pixel+=distance;
2071 mean_error+=distance*distance;
2072 if (distance > maximum_error)
2073 maximum_error=distance;
2074 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2075 mean_error_per_pixel+=distance;
2076 mean_error+=distance*distance;
2077 if (distance > maximum_error)
2078 maximum_error=distance;
2079 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2080 mean_error_per_pixel+=distance;
2081 mean_error+=distance*distance;
2082 if (distance > maximum_error)
2083 maximum_error=distance;
2084 p++;
2085 }
2086 }
2087 image_view=DestroyCacheView(image_view);
2088 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2089 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2090 mean_error/area;
2091 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2092 return(MagickTrue);
2093}
2094
2095/*
2096%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2097% %
2098% %
2099% %
2100% G e t Q u a n t i z e I n f o %
2101% %
2102% %
2103% %
2104%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2105%
2106% GetQuantizeInfo() initializes the QuantizeInfo structure.
2107%
2108% The format of the GetQuantizeInfo method is:
2109%
2110% GetQuantizeInfo(QuantizeInfo *quantize_info)
2111%
2112% A description of each parameter follows:
2113%
2114% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2115%
2116*/
2117MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2118{
2119 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2120 assert(quantize_info != (QuantizeInfo *) NULL);
2121 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2122 quantize_info->number_colors=256;
2123 quantize_info->dither=MagickTrue;
2124 quantize_info->dither_method=RiemersmaDitherMethod;
2125 quantize_info->colorspace=UndefinedColorspace;
2126 quantize_info->measure_error=MagickFalse;
2127 quantize_info->signature=MagickSignature;
2128}
2129
2130/*
2131%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2132% %
2133% %
2134% %
2135% P o s t e r i z e I m a g e %
2136% %
2137% %
2138% %
2139%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2140%
2141% PosterizeImage() reduces the image to a limited number of colors for a
2142% "poster" effect.
2143%
2144% The format of the PosterizeImage method is:
2145%
2146% MagickBooleanType PosterizeImage(Image *image,const unsigned long levels,
2147% const MagickBooleanType dither)
2148%
2149% A description of each parameter follows:
2150%
2151% o image: Specifies a pointer to an Image structure.
2152%
2153% o levels: Number of color levels allowed in each channel. Very low values
2154% (2, 3, or 4) have the most visible effect.
2155%
2156% o dither: Set this integer value to something other than zero to
2157% dither the mapped image.
2158%
2159*/
2160MagickExport MagickBooleanType PosterizeImage(Image *image,
2161 const unsigned long levels,const MagickBooleanType dither)
2162{
cristyc4c8d132010-01-07 01:58:38 +00002163 CacheView
2164 *posterize_view;
2165
cristy3ed852e2009-09-05 21:47:34 +00002166 ExceptionInfo
2167 *exception;
2168
2169 Image
2170 *posterize_image;
2171
2172 IndexPacket
2173 *indexes;
2174
2175 long
2176 j,
2177 k,
2178 l,
2179 n;
2180
2181 MagickBooleanType
2182 status;
2183
2184 QuantizeInfo
2185 *quantize_info;
2186
2187 register long
2188 i;
2189
2190 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00002191 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00002192
cristy3ed852e2009-09-05 21:47:34 +00002193 /*
2194 Posterize image.
2195 */
2196 assert(image != (Image *) NULL);
2197 assert(image->signature == MagickSignature);
2198 if (image->debug != MagickFalse)
2199 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2200 posterize_image=AcquireImage((ImageInfo *) NULL);
2201 if (posterize_image == (Image *) NULL)
2202 return(MagickFalse);
2203 l=1;
2204 while ((l*l*l) < (long) MagickMin((long) levels*levels*levels,MaxColormapSize+1))
2205 l++;
2206 status=SetImageExtent(posterize_image,(unsigned long) (l*l*l),1);
2207 if (status == MagickFalse)
2208 {
2209 posterize_image=DestroyImage(posterize_image);
2210 return(MagickFalse);
2211 }
2212 status=AcquireImageColormap(posterize_image,levels*levels*levels);
2213 if (status == MagickFalse)
2214 {
2215 posterize_image=DestroyImage(posterize_image);
2216 return(MagickFalse);
2217 }
2218 posterize_view=AcquireCacheView(posterize_image);
2219 exception=(&image->exception);
2220 q=QueueCacheViewAuthenticPixels(posterize_view,0,0,posterize_image->columns,1,
2221 exception);
2222 if (q == (PixelPacket *) NULL)
2223 {
2224 posterize_view=DestroyCacheView(posterize_view);
2225 posterize_image=DestroyImage(posterize_image);
2226 return(MagickFalse);
2227 }
2228 indexes=GetCacheViewAuthenticIndexQueue(posterize_view);
2229 n=0;
2230 for (i=0; i < l; i++)
2231 for (j=0; j < l; j++)
2232 for (k=0; k < l; k++)
2233 {
2234 posterize_image->colormap[n].red=(Quantum) (QuantumRange*i/
2235 MagickMax(l-1L,1L));
2236 posterize_image->colormap[n].green=(Quantum)
2237 (QuantumRange*j/MagickMax(l-1L,1L));
2238 posterize_image->colormap[n].blue=(Quantum) (QuantumRange*k/
2239 MagickMax(l-1L,1L));
2240 posterize_image->colormap[n].opacity=OpaqueOpacity;
2241 *q++=posterize_image->colormap[n];
2242 indexes[n]=(IndexPacket) n;
2243 n++;
2244 }
2245 if (SyncCacheViewAuthenticPixels(posterize_view,exception) == MagickFalse)
2246 {
2247 posterize_view=DestroyCacheView(posterize_view);
2248 posterize_image=DestroyImage(posterize_image);
2249 return(MagickFalse);
2250 }
2251 posterize_view=DestroyCacheView(posterize_view);
2252 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2253 quantize_info->dither=dither;
2254 status=RemapImage(quantize_info,image,posterize_image);
2255 quantize_info=DestroyQuantizeInfo(quantize_info);
2256 posterize_image=DestroyImage(posterize_image);
2257 return(status);
2258}
2259
2260/*
2261%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2262% %
2263% %
2264% %
2265+ P r u n e C h i l d %
2266% %
2267% %
2268% %
2269%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2270%
2271% PruneChild() deletes the given node and merges its statistics into its
2272% parent.
2273%
2274% The format of the PruneSubtree method is:
2275%
2276% PruneChild(const Image *image,CubeInfo *cube_info,
2277% const NodeInfo *node_info)
2278%
2279% A description of each parameter follows.
2280%
2281% o image: the image.
2282%
2283% o cube_info: A pointer to the Cube structure.
2284%
2285% o node_info: pointer to node in color cube tree that is to be pruned.
2286%
2287*/
2288static void PruneChild(const Image *image,CubeInfo *cube_info,
2289 const NodeInfo *node_info)
2290{
2291 NodeInfo
2292 *parent;
2293
2294 register long
2295 i;
2296
2297 unsigned long
2298 number_children;
2299
2300 /*
2301 Traverse any children.
2302 */
2303 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2304 for (i=0; i < (long) number_children; i++)
2305 if (node_info->child[i] != (NodeInfo *) NULL)
2306 PruneChild(image,cube_info,node_info->child[i]);
2307 /*
2308 Merge color statistics into parent.
2309 */
2310 parent=node_info->parent;
2311 parent->number_unique+=node_info->number_unique;
2312 parent->total_color.red+=node_info->total_color.red;
2313 parent->total_color.green+=node_info->total_color.green;
2314 parent->total_color.blue+=node_info->total_color.blue;
2315 parent->total_color.opacity+=node_info->total_color.opacity;
2316 parent->child[node_info->id]=(NodeInfo *) NULL;
2317 cube_info->nodes--;
2318}
2319
2320/*
2321%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2322% %
2323% %
2324% %
2325+ P r u n e L e v e l %
2326% %
2327% %
2328% %
2329%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2330%
2331% PruneLevel() deletes all nodes at the bottom level of the color tree merging
2332% their color statistics into their parent node.
2333%
2334% The format of the PruneLevel method is:
2335%
2336% PruneLevel(const Image *image,CubeInfo *cube_info,
2337% const NodeInfo *node_info)
2338%
2339% A description of each parameter follows.
2340%
2341% o image: the image.
2342%
2343% o cube_info: A pointer to the Cube structure.
2344%
2345% o node_info: pointer to node in color cube tree that is to be pruned.
2346%
2347*/
2348static void PruneLevel(const Image *image,CubeInfo *cube_info,
2349 const NodeInfo *node_info)
2350{
2351 register long
2352 i;
2353
2354 unsigned long
2355 number_children;
2356
2357 /*
2358 Traverse any children.
2359 */
2360 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2361 for (i=0; i < (long) number_children; i++)
2362 if (node_info->child[i] != (NodeInfo *) NULL)
2363 PruneLevel(image,cube_info,node_info->child[i]);
2364 if (node_info->level == cube_info->depth)
2365 PruneChild(image,cube_info,node_info);
2366}
2367
2368/*
2369%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2370% %
2371% %
2372% %
2373+ P r u n e T o C u b e D e p t h %
2374% %
2375% %
2376% %
2377%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2378%
2379% PruneToCubeDepth() deletes any nodes at a depth greater than
2380% cube_info->depth while merging their color statistics into their parent
2381% node.
2382%
2383% The format of the PruneToCubeDepth method is:
2384%
2385% PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2386% const NodeInfo *node_info)
2387%
2388% A description of each parameter follows.
2389%
2390% o cube_info: A pointer to the Cube structure.
2391%
2392% o node_info: pointer to node in color cube tree that is to be pruned.
2393%
2394*/
2395static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2396 const NodeInfo *node_info)
2397{
2398 register long
2399 i;
2400
2401 unsigned long
2402 number_children;
2403
2404 /*
2405 Traverse any children.
2406 */
2407 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2408 for (i=0; i < (long) number_children; i++)
2409 if (node_info->child[i] != (NodeInfo *) NULL)
2410 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2411 if (node_info->level > cube_info->depth)
2412 PruneChild(image,cube_info,node_info);
2413}
2414
2415/*
2416%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2417% %
2418% %
2419% %
2420% Q u a n t i z e I m a g e %
2421% %
2422% %
2423% %
2424%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2425%
2426% QuantizeImage() analyzes the colors within a reference image and chooses a
2427% fixed number of colors to represent the image. The goal of the algorithm
2428% is to minimize the color difference between the input and output image while
2429% minimizing the processing time.
2430%
2431% The format of the QuantizeImage method is:
2432%
2433% MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2434% Image *image)
2435%
2436% A description of each parameter follows:
2437%
2438% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2439%
2440% o image: the image.
2441%
2442*/
2443MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2444 Image *image)
2445{
2446 CubeInfo
2447 *cube_info;
2448
2449 MagickBooleanType
2450 status;
2451
2452 unsigned long
2453 depth,
2454 maximum_colors;
2455
2456 assert(quantize_info != (const QuantizeInfo *) NULL);
2457 assert(quantize_info->signature == MagickSignature);
2458 assert(image != (Image *) NULL);
2459 assert(image->signature == MagickSignature);
2460 if (image->debug != MagickFalse)
2461 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2462 maximum_colors=quantize_info->number_colors;
2463 if (maximum_colors == 0)
2464 maximum_colors=MaxColormapSize;
2465 if (maximum_colors > MaxColormapSize)
2466 maximum_colors=MaxColormapSize;
2467 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2468 (image->matte == MagickFalse))
2469 (void) SetGrayscaleImage(image);
2470 if ((image->storage_class == PseudoClass) &&
2471 (image->colors <= maximum_colors))
2472 return(MagickTrue);
2473 depth=quantize_info->tree_depth;
2474 if (depth == 0)
2475 {
2476 unsigned long
2477 colors;
2478
2479 /*
2480 Depth of color tree is: Log4(colormap size)+2.
2481 */
2482 colors=maximum_colors;
2483 for (depth=1; colors != 0; depth++)
2484 colors>>=2;
2485 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2486 depth--;
2487 if ((image->matte != MagickFalse) && (depth > 5))
2488 depth--;
2489 }
2490 /*
2491 Initialize color cube.
2492 */
2493 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2494 if (cube_info == (CubeInfo *) NULL)
2495 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2496 image->filename);
2497 status=ClassifyImageColors(cube_info,image,&image->exception);
2498 if (status != MagickFalse)
2499 {
2500 /*
2501 Reduce the number of colors in the image.
2502 */
2503 ReduceImageColors(image,cube_info);
2504 status=AssignImageColors(image,cube_info);
2505 }
2506 DestroyCubeInfo(cube_info);
2507 return(status);
2508}
2509
2510/*
2511%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2512% %
2513% %
2514% %
2515% Q u a n t i z e I m a g e s %
2516% %
2517% %
2518% %
2519%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2520%
2521% QuantizeImages() analyzes the colors within a set of reference images and
2522% chooses a fixed number of colors to represent the set. The goal of the
2523% algorithm is to minimize the color difference between the input and output
2524% images while minimizing the processing time.
2525%
2526% The format of the QuantizeImages method is:
2527%
2528% MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2529% Image *images)
2530%
2531% A description of each parameter follows:
2532%
2533% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2534%
2535% o images: Specifies a pointer to a list of Image structures.
2536%
2537*/
2538MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2539 Image *images)
2540{
2541 CubeInfo
2542 *cube_info;
2543
2544 Image
2545 *image;
2546
2547 MagickBooleanType
2548 proceed,
2549 status;
2550
2551 MagickProgressMonitor
2552 progress_monitor;
2553
2554 register long
2555 i;
2556
2557 unsigned long
2558 depth,
2559 maximum_colors,
2560 number_images;
2561
2562 assert(quantize_info != (const QuantizeInfo *) NULL);
2563 assert(quantize_info->signature == MagickSignature);
2564 assert(images != (Image *) NULL);
2565 assert(images->signature == MagickSignature);
2566 if (images->debug != MagickFalse)
2567 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2568 if (GetNextImageInList(images) == (Image *) NULL)
2569 {
2570 /*
2571 Handle a single image with QuantizeImage.
2572 */
2573 status=QuantizeImage(quantize_info,images);
2574 return(status);
2575 }
2576 status=MagickFalse;
2577 maximum_colors=quantize_info->number_colors;
2578 if (maximum_colors == 0)
2579 maximum_colors=MaxColormapSize;
2580 if (maximum_colors > MaxColormapSize)
2581 maximum_colors=MaxColormapSize;
2582 depth=quantize_info->tree_depth;
2583 if (depth == 0)
2584 {
2585 unsigned long
2586 colors;
2587
2588 /*
2589 Depth of color tree is: Log4(colormap size)+2.
2590 */
2591 colors=maximum_colors;
2592 for (depth=1; colors != 0; depth++)
2593 colors>>=2;
2594 if (quantize_info->dither != MagickFalse)
2595 depth--;
2596 }
2597 /*
2598 Initialize color cube.
2599 */
2600 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2601 if (cube_info == (CubeInfo *) NULL)
2602 {
2603 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2604 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2605 return(MagickFalse);
2606 }
2607 number_images=GetImageListLength(images);
2608 image=images;
2609 for (i=0; image != (Image *) NULL; i++)
2610 {
2611 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2612 image->client_data);
2613 status=ClassifyImageColors(cube_info,image,&image->exception);
2614 if (status == MagickFalse)
2615 break;
2616 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2617 proceed=SetImageProgress(image,AssignImageTag,i,number_images);
2618 if (proceed == MagickFalse)
2619 break;
2620 image=GetNextImageInList(image);
2621 }
2622 if (status != MagickFalse)
2623 {
2624 /*
2625 Reduce the number of colors in an image sequence.
2626 */
2627 ReduceImageColors(images,cube_info);
2628 image=images;
2629 for (i=0; image != (Image *) NULL; i++)
2630 {
2631 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2632 NULL,image->client_data);
2633 status=AssignImageColors(image,cube_info);
2634 if (status == MagickFalse)
2635 break;
2636 (void) SetImageProgressMonitor(image,progress_monitor,
2637 image->client_data);
2638 proceed=SetImageProgress(image,AssignImageTag,i,number_images);
2639 if (proceed == MagickFalse)
2640 break;
2641 image=GetNextImageInList(image);
2642 }
2643 }
2644 DestroyCubeInfo(cube_info);
2645 return(status);
2646}
2647
2648/*
2649%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2650% %
2651% %
2652% %
2653+ R e d u c e %
2654% %
2655% %
2656% %
2657%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2658%
2659% Reduce() traverses the color cube tree and prunes any node whose
2660% quantization error falls below a particular threshold.
2661%
2662% The format of the Reduce method is:
2663%
2664% Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2665%
2666% A description of each parameter follows.
2667%
2668% o image: the image.
2669%
2670% o cube_info: A pointer to the Cube structure.
2671%
2672% o node_info: pointer to node in color cube tree that is to be pruned.
2673%
2674*/
2675static void Reduce(const Image *image,CubeInfo *cube_info,
2676 const NodeInfo *node_info)
2677{
2678 register long
2679 i;
2680
2681 unsigned long
2682 number_children;
2683
2684 /*
2685 Traverse any children.
2686 */
2687 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2688 for (i=0; i < (long) number_children; i++)
2689 if (node_info->child[i] != (NodeInfo *) NULL)
2690 Reduce(image,cube_info,node_info->child[i]);
2691 if (node_info->quantize_error <= cube_info->pruning_threshold)
2692 PruneChild(image,cube_info,node_info);
2693 else
2694 {
2695 /*
2696 Find minimum pruning threshold.
2697 */
2698 if (node_info->number_unique > 0)
2699 cube_info->colors++;
2700 if (node_info->quantize_error < cube_info->next_threshold)
2701 cube_info->next_threshold=node_info->quantize_error;
2702 }
2703}
2704
2705/*
2706%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2707% %
2708% %
2709% %
2710+ R e d u c e I m a g e C o l o r s %
2711% %
2712% %
2713% %
2714%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2715%
2716% ReduceImageColors() repeatedly prunes the tree until the number of nodes
2717% with n2 > 0 is less than or equal to the maximum number of colors allowed
2718% in the output image. On any given iteration over the tree, it selects
2719% those nodes whose E value is minimal for pruning and merges their
2720% color statistics upward. It uses a pruning threshold, Ep, to govern
2721% node selection as follows:
2722%
2723% Ep = 0
2724% while number of nodes with (n2 > 0) > required maximum number of colors
2725% prune all nodes such that E <= Ep
2726% Set Ep to minimum E in remaining nodes
2727%
2728% This has the effect of minimizing any quantization error when merging
2729% two nodes together.
2730%
2731% When a node to be pruned has offspring, the pruning procedure invokes
2732% itself recursively in order to prune the tree from the leaves upward.
2733% n2, Sr, Sg, and Sb in a node being pruned are always added to the
2734% corresponding data in that node's parent. This retains the pruned
2735% node's color characteristics for later averaging.
2736%
2737% For each node, n2 pixels exist for which that node represents the
2738% smallest volume in RGB space containing those pixel's colors. When n2
2739% > 0 the node will uniquely define a color in the output image. At the
2740% beginning of reduction, n2 = 0 for all nodes except a the leaves of
2741% the tree which represent colors present in the input image.
2742%
2743% The other pixel count, n1, indicates the total number of colors
2744% within the cubic volume which the node represents. This includes n1 -
2745% n2 pixels whose colors should be defined by nodes at a lower level in
2746% the tree.
2747%
2748% The format of the ReduceImageColors method is:
2749%
2750% ReduceImageColors(const Image *image,CubeInfo *cube_info)
2751%
2752% A description of each parameter follows.
2753%
2754% o image: the image.
2755%
2756% o cube_info: A pointer to the Cube structure.
2757%
2758*/
2759static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2760{
2761#define ReduceImageTag "Reduce/Image"
2762
2763 MagickBooleanType
2764 proceed;
2765
2766 MagickOffsetType
2767 offset;
2768
2769 unsigned long
2770 span;
2771
2772 cube_info->next_threshold=0.0;
2773 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2774 {
2775 cube_info->pruning_threshold=cube_info->next_threshold;
2776 cube_info->next_threshold=cube_info->root->quantize_error-1;
2777 cube_info->colors=0;
2778 Reduce(image,cube_info,cube_info->root);
2779 offset=(MagickOffsetType) span-cube_info->colors;
2780 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2781 cube_info->maximum_colors+1);
2782 if (proceed == MagickFalse)
2783 break;
2784 }
2785}
2786
2787/*
2788%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2789% %
2790% %
2791% %
2792% R e m a p I m a g e %
2793% %
2794% %
2795% %
2796%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2797%
2798% RemapImage() replaces the colors of an image with the closest color from
2799% a reference image.
2800%
2801% The format of the RemapImage method is:
2802%
2803% MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2804% Image *image,const Image *remap_image)
2805%
2806% A description of each parameter follows:
2807%
2808% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2809%
2810% o image: the image.
2811%
2812% o remap_image: the reference image.
2813%
2814*/
2815MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2816 Image *image,const Image *remap_image)
2817{
2818 CubeInfo
2819 *cube_info;
2820
2821 MagickBooleanType
2822 status;
2823
2824 /*
2825 Initialize color cube.
2826 */
2827 assert(image != (Image *) NULL);
2828 assert(image->signature == MagickSignature);
2829 if (image->debug != MagickFalse)
2830 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2831 assert(remap_image != (Image *) NULL);
2832 assert(remap_image->signature == MagickSignature);
2833 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2834 quantize_info->number_colors);
2835 if (cube_info == (CubeInfo *) NULL)
2836 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2837 image->filename);
2838 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2839 if (status != MagickFalse)
2840 {
2841 /*
2842 Classify image colors from the reference image.
2843 */
2844 cube_info->quantize_info->number_colors=cube_info->colors;
2845 status=AssignImageColors(image,cube_info);
2846 }
2847 DestroyCubeInfo(cube_info);
2848 return(status);
2849}
2850
2851/*
2852%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2853% %
2854% %
2855% %
2856% R e m a p I m a g e s %
2857% %
2858% %
2859% %
2860%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2861%
2862% RemapImages() replaces the colors of a sequence of images with the
2863% closest color from a reference image.
2864%
2865% The format of the RemapImage method is:
2866%
2867% MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2868% Image *images,Image *remap_image)
2869%
2870% A description of each parameter follows:
2871%
2872% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2873%
2874% o images: the image sequence.
2875%
2876% o remap_image: the reference image.
2877%
2878*/
2879MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2880 Image *images,const Image *remap_image)
2881{
2882 CubeInfo
2883 *cube_info;
2884
2885 Image
2886 *image;
2887
2888 MagickBooleanType
2889 status;
2890
2891 assert(images != (Image *) NULL);
2892 assert(images->signature == MagickSignature);
2893 if (images->debug != MagickFalse)
2894 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2895 image=images;
2896 if (remap_image == (Image *) NULL)
2897 {
2898 /*
2899 Create a global colormap for an image sequence.
2900 */
2901 status=QuantizeImages(quantize_info,images);
2902 return(status);
2903 }
2904 /*
2905 Classify image colors from the reference image.
2906 */
2907 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2908 quantize_info->number_colors);
2909 if (cube_info == (CubeInfo *) NULL)
2910 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2911 image->filename);
2912 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2913 if (status != MagickFalse)
2914 {
2915 /*
2916 Classify image colors from the reference image.
2917 */
2918 cube_info->quantize_info->number_colors=cube_info->colors;
2919 image=images;
2920 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
2921 {
2922 status=AssignImageColors(image,cube_info);
2923 if (status == MagickFalse)
2924 break;
2925 }
2926 }
2927 DestroyCubeInfo(cube_info);
2928 return(status);
2929}
2930
2931/*
2932%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2933% %
2934% %
2935% %
2936% S e t G r a y s c a l e I m a g e %
2937% %
2938% %
2939% %
2940%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2941%
2942% SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
2943%
2944% The format of the SetGrayscaleImage method is:
2945%
2946% MagickBooleanType SetGrayscaleImage(Image *image)
2947%
2948% A description of each parameter follows:
2949%
2950% o image: The image.
2951%
2952*/
2953
2954#if defined(__cplusplus) || defined(c_plusplus)
2955extern "C" {
2956#endif
2957
2958static int IntensityCompare(const void *x,const void *y)
2959{
2960 long
2961 intensity;
2962
2963 PixelPacket
2964 *color_1,
2965 *color_2;
2966
2967 color_1=(PixelPacket *) x;
2968 color_2=(PixelPacket *) y;
2969 intensity=PixelIntensityToQuantum(color_1)-(long)
2970 PixelIntensityToQuantum(color_2);
2971 return(intensity);
2972}
2973
2974#if defined(__cplusplus) || defined(c_plusplus)
2975}
2976#endif
2977
2978static MagickBooleanType SetGrayscaleImage(Image *image)
2979{
cristyc4c8d132010-01-07 01:58:38 +00002980 CacheView
2981 *image_view;
2982
cristy3ed852e2009-09-05 21:47:34 +00002983 ExceptionInfo
2984 *exception;
2985
2986 long
2987 j,
2988 y;
2989
2990 PixelPacket
2991 *colormap;
2992
2993 long
2994 *colormap_index;
2995
2996 register long
2997 i;
2998
2999 MagickBooleanType
3000 status;
3001
cristy3ed852e2009-09-05 21:47:34 +00003002 assert(image != (Image *) NULL);
3003 assert(image->signature == MagickSignature);
3004 if (image->type != GrayscaleType)
3005 (void) TransformImageColorspace(image,GRAYColorspace);
3006 colormap_index=(long *) AcquireQuantumMemory(MaxMap+1,
3007 sizeof(*colormap_index));
3008 if (colormap_index == (long *) NULL)
3009 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3010 image->filename);
3011 if (image->storage_class != PseudoClass)
3012 {
3013 ExceptionInfo
3014 *exception;
3015
3016 for (i=0; i <= (long) MaxMap; i++)
3017 colormap_index[i]=(-1);
3018 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3019 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3020 image->filename);
3021 image->colors=0;
3022 status=MagickTrue;
3023 exception=(&image->exception);
3024 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003025#if defined(MAGICKCORE_OPENMP_SUPPORT)
3026 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003027#endif
3028 for (y=0; y < (long) image->rows; y++)
3029 {
3030 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00003031 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00003032
3033 register long
3034 x;
3035
3036 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00003037 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003038
3039 if (status == MagickFalse)
3040 continue;
3041 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3042 exception);
3043 if (q == (PixelPacket *) NULL)
3044 {
3045 status=MagickFalse;
3046 continue;
3047 }
3048 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3049 for (x=0; x < (long) image->columns; x++)
3050 {
3051 register unsigned long
3052 intensity;
3053
3054 intensity=ScaleQuantumToMap(q->red);
3055 if (colormap_index[intensity] < 0)
3056 {
cristyb5d5f722009-11-04 03:03:49 +00003057#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy3ed852e2009-09-05 21:47:34 +00003058 #pragma omp critical (MagickCore_SetGrayscaleImage)
3059#endif
3060 if (colormap_index[intensity] < 0)
3061 {
3062 colormap_index[intensity]=(long) image->colors;
3063 image->colormap[image->colors]=(*q);
3064 image->colors++;
3065 }
3066 }
3067 indexes[x]=(IndexPacket) colormap_index[intensity];
3068 q++;
3069 }
3070 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3071 status=MagickFalse;
3072 }
3073 image_view=DestroyCacheView(image_view);
3074 }
3075 for (i=0; i < (long) image->colors; i++)
3076 image->colormap[i].opacity=(unsigned short) i;
3077 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3078 IntensityCompare);
3079 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3080 sizeof(*colormap));
3081 if (colormap == (PixelPacket *) NULL)
3082 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3083 image->filename);
3084 j=0;
3085 colormap[j]=image->colormap[0];
3086 for (i=0; i < (long) image->colors; i++)
3087 {
3088 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3089 {
3090 j++;
3091 colormap[j]=image->colormap[i];
3092 }
3093 colormap_index[(long) image->colormap[i].opacity]=j;
3094 }
3095 image->colors=(unsigned long) (j+1);
3096 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3097 image->colormap=colormap;
3098 status=MagickTrue;
3099 exception=(&image->exception);
3100 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003101#if defined(MAGICKCORE_OPENMP_SUPPORT)
3102 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003103#endif
3104 for (y=0; y < (long) image->rows; y++)
3105 {
3106 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00003107 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00003108
3109 register long
3110 x;
3111
3112 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00003113 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003114
3115 if (status == MagickFalse)
3116 continue;
3117 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3118 if (q == (PixelPacket *) NULL)
3119 {
3120 status=MagickFalse;
3121 continue;
3122 }
3123 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3124 for (x=0; x < (long) image->columns; x++)
3125 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3126 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3127 status=MagickFalse;
3128 }
3129 image_view=DestroyCacheView(image_view);
3130 colormap_index=(long *) RelinquishMagickMemory(colormap_index);
3131 image->type=GrayscaleType;
3132 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3133 image->type=BilevelType;
3134 return(status);
3135}