2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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 %
13 % MagickCore Methods to Reduce the Number of Unique Colors in an Image %
20 % Copyright 1999-2010 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
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. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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.
44 % A reduction of colors in an image is also desirable for image
45 % transmission and real-time animation.
47 % QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 % them down to some fixed number of colors.
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).
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 =
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
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.
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).
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 +
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)).
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
105 % n1: Number of pixels whose color is contained in the RGB cube which
106 % this node represents;
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.
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.
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.
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:
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
133 % This has the effect of minimizing any quantization error when merging
134 % two nodes together.
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.
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.
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
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.
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.
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.
170 % This method is based on a similar algorithm written by Paul Raveling.
175 Include declarations.
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/colormap.h"
182 #include "magick/colorspace.h"
183 #include "magick/enhance.h"
184 #include "magick/exception.h"
185 #include "magick/exception-private.h"
186 #include "magick/histogram.h"
187 #include "magick/image.h"
188 #include "magick/image-private.h"
189 #include "magick/list.h"
190 #include "magick/memory_.h"
191 #include "magick/monitor.h"
192 #include "magick/monitor-private.h"
193 #include "magick/option.h"
194 #include "magick/pixel-private.h"
195 #include "magick/quantize.h"
196 #include "magick/quantum.h"
197 #include "magick/string_.h"
202 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
207 #define ErrorQueueLength 16
208 #define MaxNodes 266817
209 #define MaxTreeDepth 8
210 #define NodesInAList 1920
215 typedef struct _RealPixelPacket
224 typedef struct _NodeInfo
245 typedef struct _Nodes
254 typedef struct _CubeInfo
292 error[ErrorQueueLength];
295 weights[ErrorQueueLength];
321 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
324 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
326 static MagickBooleanType
327 AssignImageColors(Image *,CubeInfo *),
328 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
329 DitherImage(Image *,CubeInfo *),
330 SetGrayscaleImage(Image *);
333 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
336 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
337 DestroyCubeInfo(CubeInfo *),
338 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
339 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
340 ReduceImageColors(const Image *,CubeInfo *);
343 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
347 % A c q u i r e Q u a n t i z e I n f o %
351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
353 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
355 % The format of the AcquireQuantizeInfo method is:
357 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
359 % A description of each parameter follows:
361 % o image_info: the image info.
364 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
369 quantize_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*quantize_info));
370 if (quantize_info == (QuantizeInfo *) NULL)
371 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
372 GetQuantizeInfo(quantize_info);
373 if (image_info != (ImageInfo *) NULL)
378 quantize_info->dither=image_info->dither;
379 option=GetImageOption(image_info,"dither");
380 if (option != (const char *) NULL)
381 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
382 MagickDitherOptions,MagickFalse,option);
383 quantize_info->measure_error=image_info->verbose;
385 return(quantize_info);
389 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
393 + A s s i g n I m a g e C o l o r s %
397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399 % AssignImageColors() generates the output image from the pruned tree. The
400 % output image consists of two parts: (1) A color map, which is an array
401 % of color descriptions (RGB triples) for each color present in the
402 % output image; (2) A pixel array, which represents each pixel as an
403 % index into the color map array.
405 % First, the assignment phase makes one pass over the pruned color
406 % description tree to establish the image's color map. For each node
407 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
408 % color of all pixels that classify no lower than this node. Each of
409 % these colors becomes an entry in the color map.
411 % Finally, the assignment phase reclassifies each pixel in the pruned
412 % tree to identify the deepest node containing the pixel's color. The
413 % pixel's value in the pixel array becomes the index of this node's mean
414 % color in the color map.
416 % The format of the AssignImageColors() method is:
418 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
420 % A description of each parameter follows.
422 % o image: the image.
424 % o cube_info: A pointer to the Cube structure.
428 static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
429 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
434 if ((cube_info->associate_alpha == MagickFalse) ||
435 (pixel->opacity == OpaqueOpacity))
437 alpha_pixel->red=(MagickRealType) pixel->red;
438 alpha_pixel->green=(MagickRealType) pixel->green;
439 alpha_pixel->blue=(MagickRealType) pixel->blue;
440 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
443 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
444 alpha_pixel->red=alpha*pixel->red;
445 alpha_pixel->green=alpha*pixel->green;
446 alpha_pixel->blue=alpha*pixel->blue;
447 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
450 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
454 if (value >= QuantumRange)
455 return((Quantum) QuantumRange);
456 return((Quantum) (value+0.5));
459 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
460 const RealPixelPacket *pixel,size_t index)
466 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
467 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
468 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
469 if (cube_info->associate_alpha != MagickFalse)
470 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
475 static inline MagickBooleanType IsSameColor(const Image *image,
476 const PixelPacket *p,const PixelPacket *q)
478 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
480 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
485 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
487 #define AssignImageTag "Assign/Image"
502 register const NodeInfo
513 Allocate image colormap.
515 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
516 (cube_info->quantize_info->colorspace != CMYKColorspace))
517 (void) TransformImageColorspace((Image *) image,
518 cube_info->quantize_info->colorspace);
520 if ((image->colorspace != GRAYColorspace) &&
521 (image->colorspace != RGBColorspace) &&
522 (image->colorspace != CMYColorspace))
523 (void) TransformImageColorspace((Image *) image,RGBColorspace);
524 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
525 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
528 cube_info->transparent_pixels=0;
529 cube_info->transparent_index=(-1);
530 (void) DefineImageColormap(image,cube_info,cube_info->root);
532 Create a reduced color image.
534 if ((cube_info->quantize_info->dither != MagickFalse) &&
535 (cube_info->quantize_info->dither_method != NoDitherMethod))
536 (void) DitherImage(image,cube_info);
545 exception=(&image->exception);
546 image_view=AcquireCacheView(image);
547 for (y=0; y < (ssize_t) image->rows; y++)
555 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
557 if (q == (PixelPacket *) NULL)
559 indexes=GetCacheViewAuthenticIndexQueue(image_view);
560 for (x=0; x < (ssize_t) image->columns; x+=count)
563 Identify the deepest node containing the pixel's color.
565 for (count=1; (x+count) < (ssize_t) image->columns; count++)
566 if (IsSameColor(image,q,q+count) == MagickFalse)
568 AssociateAlphaPixel(cube_info,q,&pixel);
569 node_info=cube_info->root;
570 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
572 id=ColorToNodeId(cube_info,&pixel,index);
573 if (node_info->child[id] == (NodeInfo *) NULL)
575 node_info=node_info->child[id];
578 Find closest color among siblings and their children.
580 cube_info->target=pixel;
581 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
582 (QuantumRange+1.0)+1.0);
583 ClosestColor(image,cube_info,node_info->parent);
584 index=cube_info->color_number;
585 for (i=0; i < (ssize_t) count; i++)
587 if (image->storage_class == PseudoClass)
588 indexes[x+i]=(IndexPacket) index;
589 if (cube_info->quantize_info->measure_error == MagickFalse)
591 q->red=image->colormap[index].red;
592 q->green=image->colormap[index].green;
593 q->blue=image->colormap[index].blue;
594 if (cube_info->associate_alpha != MagickFalse)
595 q->opacity=image->colormap[index].opacity;
600 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
602 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
604 if (proceed == MagickFalse)
607 image_view=DestroyCacheView(image_view);
609 if (cube_info->quantize_info->measure_error != MagickFalse)
610 (void) GetImageQuantizeError(image);
611 if ((cube_info->quantize_info->number_colors == 2) &&
612 (cube_info->quantize_info->colorspace == GRAYColorspace))
624 for (i=0; i < (ssize_t) image->colors; i++)
626 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
627 QuantumRange/2.0) ? 0 : QuantumRange);
634 (void) SyncImage(image);
635 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
636 (cube_info->quantize_info->colorspace != CMYKColorspace))
637 (void) TransformImageColorspace((Image *) image,RGBColorspace);
642 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
646 + C l a s s i f y I m a g e C o l o r s %
650 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
652 % ClassifyImageColors() begins by initializing a color description tree
653 % of sufficient depth to represent each possible input color in a leaf.
654 % However, it is impractical to generate a fully-formed color
655 % description tree in the storage_class phase for realistic values of
656 % Cmax. If colors components in the input image are quantized to k-bit
657 % precision, so that Cmax= 2k-1, the tree would need k levels below the
658 % root node to allow representing each possible input color in a leaf.
659 % This becomes prohibitive because the tree's total number of nodes is
662 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
663 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
664 % Initializes data structures for nodes only as they are needed; (2)
665 % Chooses a maximum depth for the tree as a function of the desired
666 % number of colors in the output image (currently log2(colormap size)).
668 % For each pixel in the input image, storage_class scans downward from
669 % the root of the color description tree. At each level of the tree it
670 % identifies the single node which represents a cube in RGB space
671 % containing It updates the following data for each such node:
673 % n1 : Number of pixels whose color is contained in the RGB cube
674 % which this node represents;
676 % n2 : Number of pixels whose color is not represented in a node at
677 % lower depth in the tree; initially, n2 = 0 for all nodes except
678 % leaves of the tree.
680 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
681 % all pixels not classified at a lower depth. The combination of
682 % these sums and n2 will ultimately characterize the mean color of a
683 % set of pixels represented by this node.
685 % E: the distance squared in RGB space between each pixel contained
686 % within a node and the nodes' center. This represents the quantization
689 % The format of the ClassifyImageColors() method is:
691 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
692 % const Image *image,ExceptionInfo *exception)
694 % A description of each parameter follows.
696 % o cube_info: A pointer to the Cube structure.
698 % o image: the image.
702 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
707 associate_alpha=image->matte;
708 if (cube_info->quantize_info->colorspace == TransparentColorspace)
709 associate_alpha=MagickFalse;
710 if ((cube_info->quantize_info->number_colors == 2) &&
711 (cube_info->quantize_info->colorspace == GRAYColorspace))
712 associate_alpha=MagickFalse;
713 cube_info->associate_alpha=associate_alpha;
716 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
717 const Image *image,ExceptionInfo *exception)
719 #define ClassifyImageTag "Classify/Image"
751 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
753 SetAssociatedAlpha(image,cube_info);
754 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
755 (cube_info->quantize_info->colorspace != CMYKColorspace))
756 (void) TransformImageColorspace((Image *) image,
757 cube_info->quantize_info->colorspace);
759 if ((image->colorspace != GRAYColorspace) &&
760 (image->colorspace != CMYColorspace) &&
761 (image->colorspace != RGBColorspace))
762 (void) TransformImageColorspace((Image *) image,RGBColorspace);
763 midpoint.red=(MagickRealType) QuantumRange/2.0;
764 midpoint.green=(MagickRealType) QuantumRange/2.0;
765 midpoint.blue=(MagickRealType) QuantumRange/2.0;
766 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
768 image_view=AcquireCacheView(image);
769 for (y=0; y < (ssize_t) image->rows; y++)
771 register const PixelPacket
777 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
778 if (p == (const PixelPacket *) NULL)
780 if (cube_info->nodes > MaxNodes)
783 Prune one level if the color tree is too large.
785 PruneLevel(image,cube_info,cube_info->root);
788 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
791 Start at the root and descend the color cube tree.
793 for (count=1; (x+count) < (ssize_t) image->columns; count++)
794 if (IsSameColor(image,p,p+count) == MagickFalse)
796 AssociateAlphaPixel(cube_info,p,&pixel);
797 index=MaxTreeDepth-1;
798 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
800 node_info=cube_info->root;
801 for (level=1; level <= MaxTreeDepth; level++)
804 id=ColorToNodeId(cube_info,&pixel,index);
805 mid.red+=(id & 1) != 0 ? bisect : -bisect;
806 mid.green+=(id & 2) != 0 ? bisect : -bisect;
807 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
808 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
809 if (node_info->child[id] == (NodeInfo *) NULL)
812 Set colors of new node to contain pixel.
814 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
815 if (node_info->child[id] == (NodeInfo *) NULL)
816 (void) ThrowMagickException(exception,GetMagickModule(),
817 ResourceLimitError,"MemoryAllocationFailed","`%s'",
819 if (level == MaxTreeDepth)
823 Approximate the quantization error represented by this node.
825 node_info=node_info->child[id];
826 error.red=QuantumScale*(pixel.red-mid.red);
827 error.green=QuantumScale*(pixel.green-mid.green);
828 error.blue=QuantumScale*(pixel.blue-mid.blue);
829 if (cube_info->associate_alpha != MagickFalse)
830 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
831 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
832 count*error.green*error.green+count*error.blue*error.blue+
833 count*error.opacity*error.opacity));
834 cube_info->root->quantize_error+=node_info->quantize_error;
838 Sum RGB for this leaf for later derivation of the mean cube color.
840 node_info->number_unique+=count;
841 node_info->total_color.red+=count*QuantumScale*pixel.red;
842 node_info->total_color.green+=count*QuantumScale*pixel.green;
843 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
844 if (cube_info->associate_alpha != MagickFalse)
845 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
848 if (cube_info->colors > cube_info->maximum_colors)
850 PruneToCubeDepth(image,cube_info,cube_info->root);
853 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
855 if (proceed == MagickFalse)
858 for (y++; y < (ssize_t) image->rows; y++)
860 register const PixelPacket
866 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
867 if (p == (const PixelPacket *) NULL)
869 if (cube_info->nodes > MaxNodes)
872 Prune one level if the color tree is too large.
874 PruneLevel(image,cube_info,cube_info->root);
877 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
880 Start at the root and descend the color cube tree.
882 for (count=1; (x+count) < (ssize_t) image->columns; count++)
883 if (IsSameColor(image,p,p+count) == MagickFalse)
885 AssociateAlphaPixel(cube_info,p,&pixel);
886 index=MaxTreeDepth-1;
887 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
889 node_info=cube_info->root;
890 for (level=1; level <= cube_info->depth; level++)
893 id=ColorToNodeId(cube_info,&pixel,index);
894 mid.red+=(id & 1) != 0 ? bisect : -bisect;
895 mid.green+=(id & 2) != 0 ? bisect : -bisect;
896 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
897 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
898 if (node_info->child[id] == (NodeInfo *) NULL)
901 Set colors of new node to contain pixel.
903 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
904 if (node_info->child[id] == (NodeInfo *) NULL)
905 (void) ThrowMagickException(exception,GetMagickModule(),
906 ResourceLimitError,"MemoryAllocationFailed","%s",
908 if (level == cube_info->depth)
912 Approximate the quantization error represented by this node.
914 node_info=node_info->child[id];
915 error.red=QuantumScale*(pixel.red-mid.red);
916 error.green=QuantumScale*(pixel.green-mid.green);
917 error.blue=QuantumScale*(pixel.blue-mid.blue);
918 if (cube_info->associate_alpha != MagickFalse)
919 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
920 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
921 count*error.green*error.green+error.blue*error.blue+
922 count*error.opacity*error.opacity));
923 cube_info->root->quantize_error+=node_info->quantize_error;
927 Sum RGB for this leaf for later derivation of the mean cube color.
929 node_info->number_unique+=count;
930 node_info->total_color.red+=count*QuantumScale*pixel.red;
931 node_info->total_color.green+=count*QuantumScale*pixel.green;
932 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
933 if (cube_info->associate_alpha != MagickFalse)
934 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
937 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
939 if (proceed == MagickFalse)
942 image_view=DestroyCacheView(image_view);
943 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
944 (cube_info->quantize_info->colorspace != CMYKColorspace))
945 (void) TransformImageColorspace((Image *) image,RGBColorspace);
950 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
954 % C l o n e Q u a n t i z e I n f o %
958 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
960 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
961 % or if quantize info is NULL, a new one.
963 % The format of the CloneQuantizeInfo method is:
965 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
967 % A description of each parameter follows:
969 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
970 % quantize info, or if image info is NULL a new one.
972 % o quantize_info: a structure of type info.
975 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
980 clone_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*clone_info));
981 if (clone_info == (QuantizeInfo *) NULL)
982 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
983 GetQuantizeInfo(clone_info);
984 if (quantize_info == (QuantizeInfo *) NULL)
986 clone_info->number_colors=quantize_info->number_colors;
987 clone_info->tree_depth=quantize_info->tree_depth;
988 clone_info->dither=quantize_info->dither;
989 clone_info->dither_method=quantize_info->dither_method;
990 clone_info->colorspace=quantize_info->colorspace;
991 clone_info->measure_error=quantize_info->measure_error;
996 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1000 + C l o s e s t C o l o r %
1004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1006 % ClosestColor() traverses the color cube tree at a particular node and
1007 % determines which colormap entry best represents the input color.
1009 % The format of the ClosestColor method is:
1011 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1012 % const NodeInfo *node_info)
1014 % A description of each parameter follows.
1016 % o image: the image.
1018 % o cube_info: A pointer to the Cube structure.
1020 % o node_info: the address of a structure of type NodeInfo which points to a
1021 % node in the color cube tree that is to be pruned.
1024 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1025 const NodeInfo *node_info)
1034 Traverse any children.
1036 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1037 for (i=0; i < (ssize_t) number_children; i++)
1038 if (node_info->child[i] != (NodeInfo *) NULL)
1039 ClosestColor(image,cube_info,node_info->child[i]);
1040 if (node_info->number_unique != 0)
1045 register MagickRealType
1050 register PixelPacket
1053 register RealPixelPacket
1057 Determine if this color is "closest".
1059 p=image->colormap+node_info->color_number;
1060 q=(&cube_info->target);
1063 if (cube_info->associate_alpha == MagickFalse)
1065 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1066 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1068 pixel=alpha*p->red-beta*q->red;
1069 distance=pixel*pixel;
1070 if (distance < cube_info->distance)
1072 pixel=alpha*p->green-beta*q->green;
1073 distance+=pixel*pixel;
1074 if (distance < cube_info->distance)
1076 pixel=alpha*p->blue-beta*q->blue;
1077 distance+=pixel*pixel;
1078 if (distance < cube_info->distance)
1081 distance+=pixel*pixel;
1082 if (distance < cube_info->distance)
1084 cube_info->distance=distance;
1085 cube_info->color_number=node_info->color_number;
1094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1098 % C o m p r e s s I m a g e C o l o r m a p %
1102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1104 % CompressImageColormap() compresses an image colormap by removing any
1105 % duplicate or unused color entries.
1107 % The format of the CompressImageColormap method is:
1109 % MagickBooleanType CompressImageColormap(Image *image)
1111 % A description of each parameter follows:
1113 % o image: the image.
1116 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1121 assert(image != (Image *) NULL);
1122 assert(image->signature == MagickSignature);
1123 if (image->debug != MagickFalse)
1124 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1125 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1126 return(MagickFalse);
1127 GetQuantizeInfo(&quantize_info);
1128 quantize_info.number_colors=image->colors;
1129 quantize_info.tree_depth=MaxTreeDepth;
1130 return(QuantizeImage(&quantize_info,image));
1134 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1138 + D e f i n e I m a g e C o l o r m a p %
1142 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1144 % DefineImageColormap() traverses the color cube tree and notes each colormap
1145 % entry. A colormap entry is any node in the color cube tree where the
1146 % of unique colors is not zero. DefineImageColormap() returns the number of
1147 % colors in the image colormap.
1149 % The format of the DefineImageColormap method is:
1151 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1152 % NodeInfo *node_info)
1154 % A description of each parameter follows.
1156 % o image: the image.
1158 % o cube_info: A pointer to the Cube structure.
1160 % o node_info: the address of a structure of type NodeInfo which points to a
1161 % node in the color cube tree that is to be pruned.
1164 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1165 NodeInfo *node_info)
1174 Traverse any children.
1176 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1177 for (i=0; i < (ssize_t) number_children; i++)
1178 if (node_info->child[i] != (NodeInfo *) NULL)
1179 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1180 if (node_info->number_unique != 0)
1182 register MagickRealType
1185 register PixelPacket
1189 Colormap entry is defined by the mean color in this cube.
1191 q=image->colormap+image->colors;
1192 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1193 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1194 if (cube_info->associate_alpha == MagickFalse)
1196 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1197 node_info->total_color.red));
1198 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1199 node_info->total_color.green));
1200 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1201 node_info->total_color.blue));
1202 SetOpacityPixelComponent(q,OpaqueOpacity);
1209 opacity=(MagickRealType) (alpha*QuantumRange*
1210 node_info->total_color.opacity);
1211 q->opacity=ClampToQuantum(opacity);
1212 if (q->opacity == OpaqueOpacity)
1214 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1215 node_info->total_color.red));
1216 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1217 node_info->total_color.green));
1218 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1219 node_info->total_color.blue));
1226 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1227 (MagickRealType) q->opacity));
1228 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1229 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1230 node_info->total_color.red));
1231 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1232 QuantumRange*node_info->total_color.green));
1233 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1234 node_info->total_color.blue));
1235 if (node_info->number_unique > cube_info->transparent_pixels)
1237 cube_info->transparent_pixels=node_info->number_unique;
1238 cube_info->transparent_index=(ssize_t) image->colors;
1242 node_info->color_number=image->colors++;
1244 return(image->colors);
1248 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1252 + D e s t r o y C u b e I n f o %
1256 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1258 % DestroyCubeInfo() deallocates memory associated with an image.
1260 % The format of the DestroyCubeInfo method is:
1262 % DestroyCubeInfo(CubeInfo *cube_info)
1264 % A description of each parameter follows:
1266 % o cube_info: the address of a structure of type CubeInfo.
1269 static void DestroyCubeInfo(CubeInfo *cube_info)
1275 Release color cube tree storage.
1279 nodes=cube_info->node_queue->next;
1280 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1281 cube_info->node_queue->nodes);
1282 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1283 cube_info->node_queue);
1284 cube_info->node_queue=nodes;
1285 } while (cube_info->node_queue != (Nodes *) NULL);
1286 if (cube_info->cache != (ssize_t *) NULL)
1287 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1288 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1289 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1293 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1297 % D e s t r o y Q u a n t i z e I n f o %
1301 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1303 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1306 % The format of the DestroyQuantizeInfo method is:
1308 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1310 % A description of each parameter follows:
1312 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1315 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1317 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1318 assert(quantize_info != (QuantizeInfo *) NULL);
1319 assert(quantize_info->signature == MagickSignature);
1320 quantize_info->signature=(~MagickSignature);
1321 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1322 return(quantize_info);
1326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1330 + D i t h e r I m a g e %
1334 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1336 % DitherImage() distributes the difference between an original image and
1337 % the corresponding color reduced algorithm to neighboring pixels using
1338 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1339 % MagickTrue if the image is dithered otherwise MagickFalse.
1341 % The format of the DitherImage method is:
1343 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1345 % A description of each parameter follows.
1347 % o image: the image.
1349 % o cube_info: A pointer to the Cube structure.
1353 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1354 const RealPixelPacket *pixel)
1356 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1357 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1358 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1359 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1365 RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1366 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1367 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)));
1368 if (cube_info->associate_alpha != MagickFalse)
1370 AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)));
1374 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1376 #define DitherImageTag "Dither/Image"
1406 Distribute quantization error using Floyd-Steinberg.
1408 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1409 2*sizeof(*scanlines));
1410 if (scanlines == (RealPixelPacket *) NULL)
1411 return(MagickFalse);
1413 exception=(&image->exception);
1414 image_view=AcquireCacheView(image);
1415 for (y=0; y < (ssize_t) image->rows; y++)
1417 register IndexPacket
1424 register PixelPacket
1427 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1428 if (q == (PixelPacket *) NULL)
1429 return(MagickFalse);
1430 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1431 current=scanlines+(y & 0x01)*image->columns;
1432 previous=scanlines+((y+1) & 0x01)*image->columns;
1433 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1434 for (x=0; x < (ssize_t) image->columns; x++)
1436 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1437 AssociateAlphaPixel(cube_info,q+u,&pixel);
1440 pixel.red+=7*current[u-v].red/16;
1441 pixel.green+=7*current[u-v].green/16;
1442 pixel.blue+=7*current[u-v].blue/16;
1443 if (cube_info->associate_alpha != MagickFalse)
1444 pixel.opacity+=7*current[u-v].opacity/16;
1448 if (x < (ssize_t) (image->columns-1))
1450 pixel.red+=previous[u+v].red/16;
1451 pixel.green+=previous[u+v].green/16;
1452 pixel.blue+=previous[u+v].blue/16;
1453 if (cube_info->associate_alpha != MagickFalse)
1454 pixel.opacity+=previous[u+v].opacity/16;
1456 pixel.red+=5*previous[u].red/16;
1457 pixel.green+=5*previous[u].green/16;
1458 pixel.blue+=5*previous[u].blue/16;
1459 if (cube_info->associate_alpha != MagickFalse)
1460 pixel.opacity+=5*previous[u].opacity/16;
1463 pixel.red+=3*previous[u-v].red/16;
1464 pixel.green+=3*previous[u-v].green/16;
1465 pixel.blue+=3*previous[u-v].blue/16;
1466 if (cube_info->associate_alpha != MagickFalse)
1467 pixel.opacity+=3*previous[u-v].opacity/16;
1470 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1471 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1472 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1473 if (cube_info->associate_alpha != MagickFalse)
1474 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1475 i=CacheOffset(cube_info,&pixel);
1476 if (p->cache[i] < 0)
1485 Identify the deepest node containing the pixel's color.
1488 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1490 id=ColorToNodeId(cube_info,&pixel,index);
1491 if (node_info->child[id] == (NodeInfo *) NULL)
1493 node_info=node_info->child[id];
1496 Find closest color among siblings and their children.
1499 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1501 ClosestColor(image,p,node_info->parent);
1502 p->cache[i]=(ssize_t) p->color_number;
1505 Assign pixel to closest colormap entry.
1507 index=(size_t) p->cache[i];
1508 if (image->storage_class == PseudoClass)
1509 indexes[u]=(IndexPacket) index;
1510 if (cube_info->quantize_info->measure_error == MagickFalse)
1512 (q+u)->red=image->colormap[index].red;
1513 (q+u)->green=image->colormap[index].green;
1514 (q+u)->blue=image->colormap[index].blue;
1515 if (cube_info->associate_alpha != MagickFalse)
1516 (q+u)->opacity=image->colormap[index].opacity;
1518 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1519 return(MagickFalse);
1523 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1524 current[u].red=pixel.red-color.red;
1525 current[u].green=pixel.green-color.green;
1526 current[u].blue=pixel.blue-color.blue;
1527 if (cube_info->associate_alpha != MagickFalse)
1528 current[u].opacity=pixel.opacity-color.opacity;
1529 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1530 if (proceed == MagickFalse)
1531 return(MagickFalse);
1535 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1536 image_view=DestroyCacheView(image_view);
1540 static MagickBooleanType
1541 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1543 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1544 const size_t level,const unsigned int direction)
1551 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1552 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1553 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1558 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1559 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1560 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1565 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1566 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1567 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1572 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1573 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1574 (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,WestGravity);
1588 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1589 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1590 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1591 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
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,EastGravity);
1599 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1600 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1601 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1602 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1607 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1608 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1609 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1610 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1611 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1612 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1613 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1618 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1619 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1620 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1621 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1622 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1623 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1624 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1632 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1633 CubeInfo *cube_info,const unsigned int direction)
1635 #define DitherImageTag "Dither/Image"
1651 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1652 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1657 register IndexPacket
1663 register PixelPacket
1669 exception=(&image->exception);
1670 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1671 if (q == (PixelPacket *) NULL)
1672 return(MagickFalse);
1673 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1674 AssociateAlphaPixel(cube_info,q,&pixel);
1675 for (i=0; i < ErrorQueueLength; i++)
1677 pixel.red+=p->weights[i]*p->error[i].red;
1678 pixel.green+=p->weights[i]*p->error[i].green;
1679 pixel.blue+=p->weights[i]*p->error[i].blue;
1680 if (cube_info->associate_alpha != MagickFalse)
1681 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1683 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1684 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1685 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1686 if (cube_info->associate_alpha != MagickFalse)
1687 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1688 i=CacheOffset(cube_info,&pixel);
1689 if (p->cache[i] < 0)
1698 Identify the deepest node containing the pixel's color.
1701 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1703 id=ColorToNodeId(cube_info,&pixel,index);
1704 if (node_info->child[id] == (NodeInfo *) NULL)
1706 node_info=node_info->child[id];
1709 Find closest color among siblings and their children.
1712 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1713 QuantumRange+1.0)+1.0);
1714 ClosestColor(image,p,node_info->parent);
1715 p->cache[i]=(ssize_t) p->color_number;
1718 Assign pixel to closest colormap entry.
1720 index=(size_t) (1*p->cache[i]);
1721 if (image->storage_class == PseudoClass)
1722 *indexes=(IndexPacket) index;
1723 if (cube_info->quantize_info->measure_error == MagickFalse)
1725 q->red=image->colormap[index].red;
1726 q->green=image->colormap[index].green;
1727 q->blue=image->colormap[index].blue;
1728 if (cube_info->associate_alpha != MagickFalse)
1729 q->opacity=image->colormap[index].opacity;
1731 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1732 return(MagickFalse);
1734 Propagate the error as the last entry of the error queue.
1736 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1737 sizeof(p->error[0]));
1738 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1739 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1740 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1741 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1742 if (cube_info->associate_alpha != MagickFalse)
1743 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1744 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1745 if (proceed == MagickFalse)
1746 return(MagickFalse);
1751 case WestGravity: p->x--; break;
1752 case EastGravity: p->x++; break;
1753 case NorthGravity: p->y--; break;
1754 case SouthGravity: p->y++; break;
1759 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1766 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1773 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1787 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1788 return(FloydSteinbergDither(image,cube_info));
1790 Distribute quantization error along a Hilbert curve.
1792 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1793 sizeof(*cube_info->error));
1796 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1797 for (depth=1; i != 0; depth++)
1799 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1801 cube_info->offset=0;
1802 cube_info->span=(MagickSizeType) image->columns*image->rows;
1803 image_view=AcquireCacheView(image);
1805 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1806 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1807 image_view=DestroyCacheView(image_view);
1812 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1816 + G e t C u b e I n f o %
1820 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1822 % GetCubeInfo() initialize the Cube data structure.
1824 % The format of the GetCubeInfo method is:
1826 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1827 % const size_t depth,const size_t maximum_colors)
1829 % A description of each parameter follows.
1831 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1833 % o depth: Normally, this integer value is zero or one. A zero or
1834 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1835 % A tree of this depth generally allows the best representation of the
1836 % reference image with the least amount of memory and the fastest
1837 % computational speed. In some cases, such as an image with low color
1838 % dispersion (a few number of colors), a value other than
1839 % Log4(number_colors) is required. To expand the color tree completely,
1842 % o maximum_colors: maximum colors.
1845 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1846 const size_t depth,const size_t maximum_colors)
1862 Initialize tree to describe color cube_info.
1864 cube_info=(CubeInfo *) AcquireAlignedMemory(1,sizeof(*cube_info));
1865 if (cube_info == (CubeInfo *) NULL)
1866 return((CubeInfo *) NULL);
1867 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1868 cube_info->depth=depth;
1869 if (cube_info->depth > MaxTreeDepth)
1870 cube_info->depth=MaxTreeDepth;
1871 if (cube_info->depth < 2)
1873 cube_info->maximum_colors=maximum_colors;
1875 Initialize root node.
1877 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1878 if (cube_info->root == (NodeInfo *) NULL)
1879 return((CubeInfo *) NULL);
1880 cube_info->root->parent=cube_info->root;
1881 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1882 if (cube_info->quantize_info->dither == MagickFalse)
1885 Initialize dither resources.
1887 length=(size_t) (1UL << (4*(8-CacheShift)));
1888 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1889 sizeof(*cube_info->cache));
1890 if (cube_info->cache == (ssize_t *) NULL)
1891 return((CubeInfo *) NULL);
1893 Initialize color cache.
1895 for (i=0; i < (ssize_t) length; i++)
1896 cube_info->cache[i]=(-1);
1898 Distribute weights along a curve of exponential decay.
1901 for (i=0; i < ErrorQueueLength; i++)
1903 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1904 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1907 Normalize the weighting factors.
1910 for (i=0; i < ErrorQueueLength; i++)
1911 weight+=cube_info->weights[i];
1913 for (i=0; i < ErrorQueueLength; i++)
1915 cube_info->weights[i]/=weight;
1916 sum+=cube_info->weights[i];
1918 cube_info->weights[0]+=1.0-sum;
1923 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1927 + G e t N o d e I n f o %
1931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1933 % GetNodeInfo() allocates memory for a new node in the color cube tree and
1934 % presets all fields to zero.
1936 % The format of the GetNodeInfo method is:
1938 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1939 % const size_t level,NodeInfo *parent)
1941 % A description of each parameter follows.
1943 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1945 % o id: Specifies the child number of the node.
1947 % o level: Specifies the level in the storage_class the node resides.
1950 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1951 const size_t level,NodeInfo *parent)
1956 if (cube_info->free_nodes == 0)
1962 Allocate a new queue of nodes.
1964 nodes=(Nodes *) AcquireAlignedMemory(1,sizeof(*nodes));
1965 if (nodes == (Nodes *) NULL)
1966 return((NodeInfo *) NULL);
1967 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1968 sizeof(*nodes->nodes));
1969 if (nodes->nodes == (NodeInfo *) NULL)
1970 return((NodeInfo *) NULL);
1971 nodes->next=cube_info->node_queue;
1972 cube_info->node_queue=nodes;
1973 cube_info->next_node=nodes->nodes;
1974 cube_info->free_nodes=NodesInAList;
1977 cube_info->free_nodes--;
1978 node_info=cube_info->next_node++;
1979 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1980 node_info->parent=parent;
1982 node_info->level=level;
1987 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1991 % G e t I m a g e Q u a n t i z e E r r o r %
1995 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1997 % GetImageQuantizeError() measures the difference between the original
1998 % and quantized images. This difference is the total quantization error.
1999 % The error is computed by summing over all pixels in an image the distance
2000 % squared in RGB space between each reference pixel value and its quantized
2001 % value. These values are computed:
2003 % o mean_error_per_pixel: This value is the mean error for any single
2004 % pixel in the image.
2006 % o normalized_mean_square_error: This value is the normalized mean
2007 % quantization error for any single pixel in the image. This distance
2008 % measure is normalized to a range between 0 and 1. It is independent
2009 % of the range of red, green, and blue values in the image.
2011 % o normalized_maximum_square_error: Thsi value is the normalized
2012 % maximum quantization error for any single pixel in the image. This
2013 % distance measure is normalized to a range between 0 and 1. It is
2014 % independent of the range of red, green, and blue values in your image.
2016 % The format of the GetImageQuantizeError method is:
2018 % MagickBooleanType GetImageQuantizeError(Image *image)
2020 % A description of each parameter follows.
2022 % o image: the image.
2025 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2046 mean_error_per_pixel;
2051 assert(image != (Image *) NULL);
2052 assert(image->signature == MagickSignature);
2053 if (image->debug != MagickFalse)
2054 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2055 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2056 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2057 if (image->storage_class == DirectClass)
2061 area=3.0*image->columns*image->rows;
2063 mean_error_per_pixel=0.0;
2065 exception=(&image->exception);
2066 image_view=AcquireCacheView(image);
2067 for (y=0; y < (ssize_t) image->rows; y++)
2069 register const PixelPacket
2075 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2076 if (p == (const PixelPacket *) NULL)
2078 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2079 for (x=0; x < (ssize_t) image->columns; x++)
2081 index=1UL*indexes[x];
2082 if (image->matte != MagickFalse)
2084 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2085 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2086 image->colormap[index].opacity));
2088 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2089 mean_error_per_pixel+=distance;
2090 mean_error+=distance*distance;
2091 if (distance > maximum_error)
2092 maximum_error=distance;
2093 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2094 mean_error_per_pixel+=distance;
2095 mean_error+=distance*distance;
2096 if (distance > maximum_error)
2097 maximum_error=distance;
2098 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2099 mean_error_per_pixel+=distance;
2100 mean_error+=distance*distance;
2101 if (distance > maximum_error)
2102 maximum_error=distance;
2106 image_view=DestroyCacheView(image_view);
2107 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2108 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2110 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2115 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2119 % G e t Q u a n t i z e I n f o %
2123 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2125 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2127 % The format of the GetQuantizeInfo method is:
2129 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2131 % A description of each parameter follows:
2133 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2136 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2138 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2139 assert(quantize_info != (QuantizeInfo *) NULL);
2140 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2141 quantize_info->number_colors=256;
2142 quantize_info->dither=MagickTrue;
2143 quantize_info->dither_method=RiemersmaDitherMethod;
2144 quantize_info->colorspace=UndefinedColorspace;
2145 quantize_info->measure_error=MagickFalse;
2146 quantize_info->signature=MagickSignature;
2150 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2154 % P o s t e r i z e I m a g e %
2158 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2160 % PosterizeImage() reduces the image to a limited number of colors for a
2163 % The format of the PosterizeImage method is:
2165 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2166 % const MagickBooleanType dither)
2168 % A description of each parameter follows:
2170 % o image: Specifies a pointer to an Image structure.
2172 % o levels: Number of color levels allowed in each channel. Very low values
2173 % (2, 3, or 4) have the most visible effect.
2175 % o dither: Set this integer value to something other than zero to
2176 % dither the mapped image.
2179 MagickExport MagickBooleanType PosterizeImage(Image *image,
2180 const size_t levels,const MagickBooleanType dither)
2209 register PixelPacket
2218 assert(image != (Image *) NULL);
2219 assert(image->signature == MagickSignature);
2220 if (image->debug != MagickFalse)
2221 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2222 posterize_image=AcquireImage((ImageInfo *) NULL);
2223 if (posterize_image == (Image *) NULL)
2224 return(MagickFalse);
2226 length=(size_t) (levels*levels*levels);
2227 while ((l*l*l) < (ssize_t) MagickMin((ssize_t) length,MaxColormapSize+1))
2229 status=SetImageExtent(posterize_image,(size_t) (l*l*l),1);
2230 if (status == MagickFalse)
2232 posterize_image=DestroyImage(posterize_image);
2233 return(MagickFalse);
2235 status=AcquireImageColormap(posterize_image,levels*levels*levels);
2236 if (status == MagickFalse)
2238 posterize_image=DestroyImage(posterize_image);
2239 return(MagickFalse);
2241 posterize_view=AcquireCacheView(posterize_image);
2242 exception=(&image->exception);
2243 q=QueueCacheViewAuthenticPixels(posterize_view,0,0,posterize_image->columns,1,
2245 if (q == (PixelPacket *) NULL)
2247 posterize_view=DestroyCacheView(posterize_view);
2248 posterize_image=DestroyImage(posterize_image);
2249 return(MagickFalse);
2251 indexes=GetCacheViewAuthenticIndexQueue(posterize_view);
2253 for (i=0; i < l; i++)
2254 for (j=0; j < l; j++)
2255 for (k=0; k < l; k++)
2257 posterize_image->colormap[n].red=(Quantum) (QuantumRange*i/
2258 MagickMax(l-1L,1L));
2259 posterize_image->colormap[n].green=(Quantum)
2260 (QuantumRange*j/MagickMax(l-1L,1L));
2261 posterize_image->colormap[n].blue=(Quantum) (QuantumRange*k/
2262 MagickMax(l-1L,1L));
2263 posterize_image->colormap[n].opacity=OpaqueOpacity;
2264 *q++=posterize_image->colormap[n];
2265 indexes[n]=(IndexPacket) n;
2268 if (SyncCacheViewAuthenticPixels(posterize_view,exception) == MagickFalse)
2270 posterize_view=DestroyCacheView(posterize_view);
2271 posterize_image=DestroyImage(posterize_image);
2272 return(MagickFalse);
2274 posterize_view=DestroyCacheView(posterize_view);
2275 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2276 quantize_info->dither=dither;
2277 status=RemapImage(quantize_info,image,posterize_image);
2278 quantize_info=DestroyQuantizeInfo(quantize_info);
2279 posterize_image=DestroyImage(posterize_image);
2284 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2288 + P r u n e C h i l d %
2292 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2294 % PruneChild() deletes the given node and merges its statistics into its
2297 % The format of the PruneSubtree method is:
2299 % PruneChild(const Image *image,CubeInfo *cube_info,
2300 % const NodeInfo *node_info)
2302 % A description of each parameter follows.
2304 % o image: the image.
2306 % o cube_info: A pointer to the Cube structure.
2308 % o node_info: pointer to node in color cube tree that is to be pruned.
2311 static void PruneChild(const Image *image,CubeInfo *cube_info,
2312 const NodeInfo *node_info)
2324 Traverse any children.
2326 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2327 for (i=0; i < (ssize_t) number_children; i++)
2328 if (node_info->child[i] != (NodeInfo *) NULL)
2329 PruneChild(image,cube_info,node_info->child[i]);
2331 Merge color statistics into parent.
2333 parent=node_info->parent;
2334 parent->number_unique+=node_info->number_unique;
2335 parent->total_color.red+=node_info->total_color.red;
2336 parent->total_color.green+=node_info->total_color.green;
2337 parent->total_color.blue+=node_info->total_color.blue;
2338 parent->total_color.opacity+=node_info->total_color.opacity;
2339 parent->child[node_info->id]=(NodeInfo *) NULL;
2344 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2348 + P r u n e L e v e l %
2352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2354 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2355 % their color statistics into their parent node.
2357 % The format of the PruneLevel method is:
2359 % PruneLevel(const Image *image,CubeInfo *cube_info,
2360 % const NodeInfo *node_info)
2362 % A description of each parameter follows.
2364 % o image: the image.
2366 % o cube_info: A pointer to the Cube structure.
2368 % o node_info: pointer to node in color cube tree that is to be pruned.
2371 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2372 const NodeInfo *node_info)
2381 Traverse any children.
2383 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2384 for (i=0; i < (ssize_t) number_children; i++)
2385 if (node_info->child[i] != (NodeInfo *) NULL)
2386 PruneLevel(image,cube_info,node_info->child[i]);
2387 if (node_info->level == cube_info->depth)
2388 PruneChild(image,cube_info,node_info);
2392 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2396 + P r u n e T o C u b e D e p t h %
2400 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2402 % PruneToCubeDepth() deletes any nodes at a depth greater than
2403 % cube_info->depth while merging their color statistics into their parent
2406 % The format of the PruneToCubeDepth method is:
2408 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2409 % const NodeInfo *node_info)
2411 % A description of each parameter follows.
2413 % o cube_info: A pointer to the Cube structure.
2415 % o node_info: pointer to node in color cube tree that is to be pruned.
2418 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2419 const NodeInfo *node_info)
2428 Traverse any children.
2430 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2431 for (i=0; i < (ssize_t) number_children; i++)
2432 if (node_info->child[i] != (NodeInfo *) NULL)
2433 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2434 if (node_info->level > cube_info->depth)
2435 PruneChild(image,cube_info,node_info);
2439 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2443 % Q u a n t i z e I m a g e %
2447 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2449 % QuantizeImage() analyzes the colors within a reference image and chooses a
2450 % fixed number of colors to represent the image. The goal of the algorithm
2451 % is to minimize the color difference between the input and output image while
2452 % minimizing the processing time.
2454 % The format of the QuantizeImage method is:
2456 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2459 % A description of each parameter follows:
2461 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2463 % o image: the image.
2466 static MagickBooleanType DirectToColormapImage(Image *image,
2467 ExceptionInfo *exception)
2485 number_colors=(size_t) (image->columns*image->rows);
2486 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2487 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2490 image_view=AcquireCacheView(image);
2491 for (y=0; y < (ssize_t) image->rows; y++)
2496 register IndexPacket
2499 register PixelPacket
2505 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2506 if (q == (const PixelPacket *) NULL)
2508 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2509 for (x=0; x < (ssize_t) image->columns; x++)
2511 indexes[x]=(IndexPacket) i;
2512 image->colormap[i++]=(*q++);
2514 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2516 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2518 if (proceed == MagickFalse)
2521 image_view=DestroyCacheView(image_view);
2525 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2538 assert(quantize_info != (const QuantizeInfo *) NULL);
2539 assert(quantize_info->signature == MagickSignature);
2540 assert(image != (Image *) NULL);
2541 assert(image->signature == MagickSignature);
2542 if (image->debug != MagickFalse)
2543 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2544 maximum_colors=quantize_info->number_colors;
2545 if (maximum_colors == 0)
2546 maximum_colors=MaxColormapSize;
2547 if (maximum_colors > MaxColormapSize)
2548 maximum_colors=MaxColormapSize;
2549 if ((image->columns*image->rows) <= maximum_colors)
2550 return(DirectToColormapImage(image,&image->exception));
2551 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2552 (image->matte == MagickFalse))
2553 (void) SetGrayscaleImage(image);
2554 if ((image->storage_class == PseudoClass) &&
2555 (image->colors <= maximum_colors))
2557 depth=quantize_info->tree_depth;
2564 Depth of color tree is: Log4(colormap size)+2.
2566 colors=maximum_colors;
2567 for (depth=1; colors != 0; depth++)
2569 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2571 if ((image->matte != MagickFalse) && (depth > 5))
2575 Initialize color cube.
2577 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2578 if (cube_info == (CubeInfo *) NULL)
2579 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2581 status=ClassifyImageColors(cube_info,image,&image->exception);
2582 if (status != MagickFalse)
2585 Reduce the number of colors in the image.
2587 ReduceImageColors(image,cube_info);
2588 status=AssignImageColors(image,cube_info);
2590 DestroyCubeInfo(cube_info);
2595 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2599 % Q u a n t i z e I m a g e s %
2603 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2605 % QuantizeImages() analyzes the colors within a set of reference images and
2606 % chooses a fixed number of colors to represent the set. The goal of the
2607 % algorithm is to minimize the color difference between the input and output
2608 % images while minimizing the processing time.
2610 % The format of the QuantizeImages method is:
2612 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2615 % A description of each parameter follows:
2617 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2619 % o images: Specifies a pointer to a list of Image structures.
2622 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2635 MagickProgressMonitor
2646 assert(quantize_info != (const QuantizeInfo *) NULL);
2647 assert(quantize_info->signature == MagickSignature);
2648 assert(images != (Image *) NULL);
2649 assert(images->signature == MagickSignature);
2650 if (images->debug != MagickFalse)
2651 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2652 if (GetNextImageInList(images) == (Image *) NULL)
2655 Handle a single image with QuantizeImage.
2657 status=QuantizeImage(quantize_info,images);
2661 maximum_colors=quantize_info->number_colors;
2662 if (maximum_colors == 0)
2663 maximum_colors=MaxColormapSize;
2664 if (maximum_colors > MaxColormapSize)
2665 maximum_colors=MaxColormapSize;
2666 depth=quantize_info->tree_depth;
2673 Depth of color tree is: Log4(colormap size)+2.
2675 colors=maximum_colors;
2676 for (depth=1; colors != 0; depth++)
2678 if (quantize_info->dither != MagickFalse)
2682 Initialize color cube.
2684 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2685 if (cube_info == (CubeInfo *) NULL)
2687 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2688 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2689 return(MagickFalse);
2691 number_images=GetImageListLength(images);
2693 for (i=0; image != (Image *) NULL; i++)
2695 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2696 image->client_data);
2697 status=ClassifyImageColors(cube_info,image,&image->exception);
2698 if (status == MagickFalse)
2700 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2701 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2703 if (proceed == MagickFalse)
2705 image=GetNextImageInList(image);
2707 if (status != MagickFalse)
2710 Reduce the number of colors in an image sequence.
2712 ReduceImageColors(images,cube_info);
2714 for (i=0; image != (Image *) NULL; i++)
2716 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2717 NULL,image->client_data);
2718 status=AssignImageColors(image,cube_info);
2719 if (status == MagickFalse)
2721 (void) SetImageProgressMonitor(image,progress_monitor,
2722 image->client_data);
2723 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2725 if (proceed == MagickFalse)
2727 image=GetNextImageInList(image);
2730 DestroyCubeInfo(cube_info);
2735 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2743 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2745 % Reduce() traverses the color cube tree and prunes any node whose
2746 % quantization error falls below a particular threshold.
2748 % The format of the Reduce method is:
2750 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2752 % A description of each parameter follows.
2754 % o image: the image.
2756 % o cube_info: A pointer to the Cube structure.
2758 % o node_info: pointer to node in color cube tree that is to be pruned.
2761 static void Reduce(const Image *image,CubeInfo *cube_info,
2762 const NodeInfo *node_info)
2771 Traverse any children.
2773 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2774 for (i=0; i < (ssize_t) number_children; i++)
2775 if (node_info->child[i] != (NodeInfo *) NULL)
2776 Reduce(image,cube_info,node_info->child[i]);
2777 if (node_info->quantize_error <= cube_info->pruning_threshold)
2778 PruneChild(image,cube_info,node_info);
2782 Find minimum pruning threshold.
2784 if (node_info->number_unique > 0)
2785 cube_info->colors++;
2786 if (node_info->quantize_error < cube_info->next_threshold)
2787 cube_info->next_threshold=node_info->quantize_error;
2792 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2796 + R e d u c e I m a g e C o l o r s %
2800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2802 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2803 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2804 % in the output image. On any given iteration over the tree, it selects
2805 % those nodes whose E value is minimal for pruning and merges their
2806 % color statistics upward. It uses a pruning threshold, Ep, to govern
2807 % node selection as follows:
2810 % while number of nodes with (n2 > 0) > required maximum number of colors
2811 % prune all nodes such that E <= Ep
2812 % Set Ep to minimum E in remaining nodes
2814 % This has the effect of minimizing any quantization error when merging
2815 % two nodes together.
2817 % When a node to be pruned has offspring, the pruning procedure invokes
2818 % itself recursively in order to prune the tree from the leaves upward.
2819 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2820 % corresponding data in that node's parent. This retains the pruned
2821 % node's color characteristics for later averaging.
2823 % For each node, n2 pixels exist for which that node represents the
2824 % smallest volume in RGB space containing those pixel's colors. When n2
2825 % > 0 the node will uniquely define a color in the output image. At the
2826 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2827 % the tree which represent colors present in the input image.
2829 % The other pixel count, n1, indicates the total number of colors
2830 % within the cubic volume which the node represents. This includes n1 -
2831 % n2 pixels whose colors should be defined by nodes at a lower level in
2834 % The format of the ReduceImageColors method is:
2836 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2838 % A description of each parameter follows.
2840 % o image: the image.
2842 % o cube_info: A pointer to the Cube structure.
2845 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2847 #define ReduceImageTag "Reduce/Image"
2858 cube_info->next_threshold=0.0;
2859 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2861 cube_info->pruning_threshold=cube_info->next_threshold;
2862 cube_info->next_threshold=cube_info->root->quantize_error-1;
2863 cube_info->colors=0;
2864 Reduce(image,cube_info,cube_info->root);
2865 offset=(MagickOffsetType) span-cube_info->colors;
2866 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2867 cube_info->maximum_colors+1);
2868 if (proceed == MagickFalse)
2874 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2878 % R e m a p I m a g e %
2882 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2884 % RemapImage() replaces the colors of an image with the closest color from
2885 % a reference image.
2887 % The format of the RemapImage method is:
2889 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2890 % Image *image,const Image *remap_image)
2892 % A description of each parameter follows:
2894 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2896 % o image: the image.
2898 % o remap_image: the reference image.
2901 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2902 Image *image,const Image *remap_image)
2911 Initialize color cube.
2913 assert(image != (Image *) NULL);
2914 assert(image->signature == MagickSignature);
2915 if (image->debug != MagickFalse)
2916 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2917 assert(remap_image != (Image *) NULL);
2918 assert(remap_image->signature == MagickSignature);
2919 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2920 quantize_info->number_colors);
2921 if (cube_info == (CubeInfo *) NULL)
2922 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2924 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2925 if (status != MagickFalse)
2928 Classify image colors from the reference image.
2930 cube_info->quantize_info->number_colors=cube_info->colors;
2931 status=AssignImageColors(image,cube_info);
2933 DestroyCubeInfo(cube_info);
2938 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2942 % R e m a p I m a g e s %
2946 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2948 % RemapImages() replaces the colors of a sequence of images with the
2949 % closest color from a reference image.
2951 % The format of the RemapImage method is:
2953 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2954 % Image *images,Image *remap_image)
2956 % A description of each parameter follows:
2958 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2960 % o images: the image sequence.
2962 % o remap_image: the reference image.
2965 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2966 Image *images,const Image *remap_image)
2977 assert(images != (Image *) NULL);
2978 assert(images->signature == MagickSignature);
2979 if (images->debug != MagickFalse)
2980 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2982 if (remap_image == (Image *) NULL)
2985 Create a global colormap for an image sequence.
2987 status=QuantizeImages(quantize_info,images);
2991 Classify image colors from the reference image.
2993 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2994 quantize_info->number_colors);
2995 if (cube_info == (CubeInfo *) NULL)
2996 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2998 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2999 if (status != MagickFalse)
3002 Classify image colors from the reference image.
3004 cube_info->quantize_info->number_colors=cube_info->colors;
3006 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3008 status=AssignImageColors(image,cube_info);
3009 if (status == MagickFalse)
3013 DestroyCubeInfo(cube_info);
3018 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3022 % S e t G r a y s c a l e I m a g e %
3026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3028 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3030 % The format of the SetGrayscaleImage method is:
3032 % MagickBooleanType SetGrayscaleImage(Image *image)
3034 % A description of each parameter follows:
3036 % o image: The image.
3040 #if defined(__cplusplus) || defined(c_plusplus)
3044 static int IntensityCompare(const void *x,const void *y)
3053 color_1=(PixelPacket *) x;
3054 color_2=(PixelPacket *) y;
3055 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3056 PixelIntensityToQuantum(color_2);
3057 return((int) intensity);
3060 #if defined(__cplusplus) || defined(c_plusplus)
3064 static MagickBooleanType SetGrayscaleImage(Image *image)
3088 assert(image != (Image *) NULL);
3089 assert(image->signature == MagickSignature);
3090 if (image->type != GrayscaleType)
3091 (void) TransformImageColorspace(image,GRAYColorspace);
3092 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3093 sizeof(*colormap_index));
3094 if (colormap_index == (ssize_t *) NULL)
3095 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3097 if (image->storage_class != PseudoClass)
3102 for (i=0; i <= (ssize_t) MaxMap; i++)
3103 colormap_index[i]=(-1);
3104 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3105 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3109 exception=(&image->exception);
3110 image_view=AcquireCacheView(image);
3111 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3112 #pragma omp parallel for schedule(dynamic,4) shared(status)
3114 for (y=0; y < (ssize_t) image->rows; y++)
3116 register IndexPacket
3122 register const PixelPacket
3125 if (status == MagickFalse)
3127 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3129 if (q == (PixelPacket *) NULL)
3134 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3135 for (x=0; x < (ssize_t) image->columns; x++)
3140 intensity=ScaleQuantumToMap(q->red);
3141 if (colormap_index[intensity] < 0)
3143 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3144 #pragma omp critical (MagickCore_SetGrayscaleImage)
3146 if (colormap_index[intensity] < 0)
3148 colormap_index[intensity]=(ssize_t) image->colors;
3149 image->colormap[image->colors]=(*q);
3153 indexes[x]=(IndexPacket) colormap_index[intensity];
3156 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3159 image_view=DestroyCacheView(image_view);
3161 for (i=0; i < (ssize_t) image->colors; i++)
3162 image->colormap[i].opacity=(unsigned short) i;
3163 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3165 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3167 if (colormap == (PixelPacket *) NULL)
3168 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3171 colormap[j]=image->colormap[0];
3172 for (i=0; i < (ssize_t) image->colors; i++)
3174 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3177 colormap[j]=image->colormap[i];
3179 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3181 image->colors=(size_t) (j+1);
3182 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3183 image->colormap=colormap;
3185 exception=(&image->exception);
3186 image_view=AcquireCacheView(image);
3187 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3188 #pragma omp parallel for schedule(dynamic,4) shared(status)
3190 for (y=0; y < (ssize_t) image->rows; y++)
3192 register IndexPacket
3198 register const PixelPacket
3201 if (status == MagickFalse)
3203 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3204 if (q == (PixelPacket *) NULL)
3209 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3210 for (x=0; x < (ssize_t) image->columns; x++)
3211 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3212 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3215 image_view=DestroyCacheView(image_view);
3216 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3217 image->type=GrayscaleType;
3218 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3219 image->type=BilevelType;