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"
203 #define ErrorQueueLength 16
204 #define MaxNodes 266817
205 #define MaxTreeDepth 8
206 #define NodesInAList 1920
211 typedef struct _RealPixelPacket
220 typedef struct _NodeInfo
241 typedef struct _Nodes
250 typedef struct _CubeInfo
288 error[ErrorQueueLength];
291 weights[ErrorQueueLength];
317 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
320 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
322 static MagickBooleanType
323 AssignImageColors(Image *,CubeInfo *),
324 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
325 DitherImage(Image *,CubeInfo *),
326 SetGrayscaleImage(Image *);
329 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
332 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
333 DestroyCubeInfo(CubeInfo *),
334 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
335 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
336 ReduceImageColors(const Image *,CubeInfo *);
339 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
343 % A c q u i r e Q u a n t i z e I n f o %
347 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
349 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
351 % The format of the AcquireQuantizeInfo method is:
353 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
355 % A description of each parameter follows:
357 % o image_info: the image info.
360 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
365 quantize_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*quantize_info));
366 if (quantize_info == (QuantizeInfo *) NULL)
367 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
368 GetQuantizeInfo(quantize_info);
369 if (image_info != (ImageInfo *) NULL)
374 quantize_info->dither=image_info->dither;
375 option=GetImageOption(image_info,"dither");
376 if (option != (const char *) NULL)
377 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
378 MagickDitherOptions,MagickFalse,option);
379 quantize_info->measure_error=image_info->verbose;
381 return(quantize_info);
385 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
389 + A s s i g n I m a g e C o l o r s %
393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
395 % AssignImageColors() generates the output image from the pruned tree. The
396 % output image consists of two parts: (1) A color map, which is an array
397 % of color descriptions (RGB triples) for each color present in the
398 % output image; (2) A pixel array, which represents each pixel as an
399 % index into the color map array.
401 % First, the assignment phase makes one pass over the pruned color
402 % description tree to establish the image's color map. For each node
403 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
404 % color of all pixels that classify no lower than this node. Each of
405 % these colors becomes an entry in the color map.
407 % Finally, the assignment phase reclassifies each pixel in the pruned
408 % tree to identify the deepest node containing the pixel's color. The
409 % pixel's value in the pixel array becomes the index of this node's mean
410 % color in the color map.
412 % The format of the AssignImageColors() method is:
414 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
416 % A description of each parameter follows.
418 % o image: the image.
420 % o cube_info: A pointer to the Cube structure.
424 static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
425 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
430 if ((cube_info->associate_alpha == MagickFalse) ||
431 (pixel->opacity == OpaqueOpacity))
433 alpha_pixel->red=(MagickRealType) pixel->red;
434 alpha_pixel->green=(MagickRealType) pixel->green;
435 alpha_pixel->blue=(MagickRealType) pixel->blue;
436 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
439 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
440 alpha_pixel->red=alpha*pixel->red;
441 alpha_pixel->green=alpha*pixel->green;
442 alpha_pixel->blue=alpha*pixel->blue;
443 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
446 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
450 if (value >= QuantumRange)
451 return((Quantum) QuantumRange);
452 return((Quantum) (value+0.5));
455 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
456 const RealPixelPacket *pixel,size_t index)
462 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
463 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
464 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
465 if (cube_info->associate_alpha != MagickFalse)
466 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
471 static inline MagickBooleanType IsSameColor(const Image *image,
472 const PixelPacket *p,const PixelPacket *q)
474 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
476 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
481 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
483 #define AssignImageTag "Assign/Image"
498 register const NodeInfo
509 Allocate image colormap.
511 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
512 (cube_info->quantize_info->colorspace != CMYKColorspace))
513 (void) TransformImageColorspace((Image *) image,
514 cube_info->quantize_info->colorspace);
516 if ((image->colorspace != GRAYColorspace) &&
517 (image->colorspace != RGBColorspace) &&
518 (image->colorspace != CMYColorspace))
519 (void) TransformImageColorspace((Image *) image,RGBColorspace);
520 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
521 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
524 cube_info->transparent_pixels=0;
525 cube_info->transparent_index=(-1);
526 (void) DefineImageColormap(image,cube_info,cube_info->root);
528 Create a reduced color image.
530 if ((cube_info->quantize_info->dither != MagickFalse) &&
531 (cube_info->quantize_info->dither_method != NoDitherMethod))
532 (void) DitherImage(image,cube_info);
541 exception=(&image->exception);
542 image_view=AcquireCacheView(image);
543 for (y=0; y < (ssize_t) image->rows; y++)
551 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
553 if (q == (PixelPacket *) NULL)
555 indexes=GetCacheViewAuthenticIndexQueue(image_view);
556 for (x=0; x < (ssize_t) image->columns; x+=count)
559 Identify the deepest node containing the pixel's color.
561 for (count=1; (x+count) < (ssize_t) image->columns; count++)
562 if (IsSameColor(image,q,q+count) == MagickFalse)
564 AssociateAlphaPixel(cube_info,q,&pixel);
565 node_info=cube_info->root;
566 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
568 id=ColorToNodeId(cube_info,&pixel,index);
569 if (node_info->child[id] == (NodeInfo *) NULL)
571 node_info=node_info->child[id];
574 Find closest color among siblings and their children.
576 cube_info->target=pixel;
577 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
578 (QuantumRange+1.0)+1.0);
579 ClosestColor(image,cube_info,node_info->parent);
580 index=cube_info->color_number;
581 for (i=0; i < (ssize_t) count; i++)
583 if (image->storage_class == PseudoClass)
584 indexes[x+i]=(IndexPacket) index;
585 if (cube_info->quantize_info->measure_error == MagickFalse)
587 q->red=image->colormap[index].red;
588 q->green=image->colormap[index].green;
589 q->blue=image->colormap[index].blue;
590 if (cube_info->associate_alpha != MagickFalse)
591 q->opacity=image->colormap[index].opacity;
596 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
598 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
600 if (proceed == MagickFalse)
603 image_view=DestroyCacheView(image_view);
605 if (cube_info->quantize_info->measure_error != MagickFalse)
606 (void) GetImageQuantizeError(image);
607 if ((cube_info->quantize_info->number_colors == 2) &&
608 (cube_info->quantize_info->colorspace == GRAYColorspace))
620 for (i=0; i < (ssize_t) image->colors; i++)
622 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
623 QuantumRange/2.0) ? 0 : QuantumRange);
630 (void) SyncImage(image);
631 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
632 (cube_info->quantize_info->colorspace != CMYKColorspace))
633 (void) TransformImageColorspace((Image *) image,RGBColorspace);
638 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
642 + C l a s s i f y I m a g e C o l o r s %
646 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
648 % ClassifyImageColors() begins by initializing a color description tree
649 % of sufficient depth to represent each possible input color in a leaf.
650 % However, it is impractical to generate a fully-formed color
651 % description tree in the storage_class phase for realistic values of
652 % Cmax. If colors components in the input image are quantized to k-bit
653 % precision, so that Cmax= 2k-1, the tree would need k levels below the
654 % root node to allow representing each possible input color in a leaf.
655 % This becomes prohibitive because the tree's total number of nodes is
658 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
659 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
660 % Initializes data structures for nodes only as they are needed; (2)
661 % Chooses a maximum depth for the tree as a function of the desired
662 % number of colors in the output image (currently log2(colormap size)).
664 % For each pixel in the input image, storage_class scans downward from
665 % the root of the color description tree. At each level of the tree it
666 % identifies the single node which represents a cube in RGB space
667 % containing It updates the following data for each such node:
669 % n1 : Number of pixels whose color is contained in the RGB cube
670 % which this node represents;
672 % n2 : Number of pixels whose color is not represented in a node at
673 % lower depth in the tree; initially, n2 = 0 for all nodes except
674 % leaves of the tree.
676 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
677 % all pixels not classified at a lower depth. The combination of
678 % these sums and n2 will ultimately characterize the mean color of a
679 % set of pixels represented by this node.
681 % E: the distance squared in RGB space between each pixel contained
682 % within a node and the nodes' center. This represents the quantization
685 % The format of the ClassifyImageColors() method is:
687 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
688 % const Image *image,ExceptionInfo *exception)
690 % A description of each parameter follows.
692 % o cube_info: A pointer to the Cube structure.
694 % o image: the image.
698 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
703 associate_alpha=image->matte;
704 if (cube_info->quantize_info->colorspace == TransparentColorspace)
705 associate_alpha=MagickFalse;
706 if ((cube_info->quantize_info->number_colors == 2) &&
707 (cube_info->quantize_info->colorspace == GRAYColorspace))
708 associate_alpha=MagickFalse;
709 cube_info->associate_alpha=associate_alpha;
712 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
713 const Image *image,ExceptionInfo *exception)
715 #define ClassifyImageTag "Classify/Image"
747 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
749 SetAssociatedAlpha(image,cube_info);
750 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
751 (cube_info->quantize_info->colorspace != CMYKColorspace))
752 (void) TransformImageColorspace((Image *) image,
753 cube_info->quantize_info->colorspace);
755 if ((image->colorspace != GRAYColorspace) &&
756 (image->colorspace != CMYColorspace) &&
757 (image->colorspace != RGBColorspace))
758 (void) TransformImageColorspace((Image *) image,RGBColorspace);
759 midpoint.red=(MagickRealType) QuantumRange/2.0;
760 midpoint.green=(MagickRealType) QuantumRange/2.0;
761 midpoint.blue=(MagickRealType) QuantumRange/2.0;
762 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
764 image_view=AcquireCacheView(image);
765 for (y=0; y < (ssize_t) image->rows; y++)
767 register const PixelPacket
773 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
774 if (p == (const PixelPacket *) NULL)
776 if (cube_info->nodes > MaxNodes)
779 Prune one level if the color tree is too large.
781 PruneLevel(image,cube_info,cube_info->root);
784 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
787 Start at the root and descend the color cube tree.
789 for (count=1; (x+count) < image->columns; count++)
790 if (IsSameColor(image,p,p+count) == MagickFalse)
792 AssociateAlphaPixel(cube_info,p,&pixel);
793 index=MaxTreeDepth-1;
794 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
796 node_info=cube_info->root;
797 for (level=1; level <= MaxTreeDepth; level++)
800 id=ColorToNodeId(cube_info,&pixel,index);
801 mid.red+=(id & 1) != 0 ? bisect : -bisect;
802 mid.green+=(id & 2) != 0 ? bisect : -bisect;
803 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
804 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
805 if (node_info->child[id] == (NodeInfo *) NULL)
808 Set colors of new node to contain pixel.
810 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
811 if (node_info->child[id] == (NodeInfo *) NULL)
812 (void) ThrowMagickException(exception,GetMagickModule(),
813 ResourceLimitError,"MemoryAllocationFailed","`%s'",
815 if (level == MaxTreeDepth)
819 Approximate the quantization error represented by this node.
821 node_info=node_info->child[id];
822 error.red=QuantumScale*(pixel.red-mid.red);
823 error.green=QuantumScale*(pixel.green-mid.green);
824 error.blue=QuantumScale*(pixel.blue-mid.blue);
825 if (cube_info->associate_alpha != MagickFalse)
826 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
827 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
828 count*error.green*error.green+count*error.blue*error.blue+
829 count*error.opacity*error.opacity));
830 cube_info->root->quantize_error+=node_info->quantize_error;
834 Sum RGB for this leaf for later derivation of the mean cube color.
836 node_info->number_unique+=count;
837 node_info->total_color.red+=count*QuantumScale*pixel.red;
838 node_info->total_color.green+=count*QuantumScale*pixel.green;
839 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
840 if (cube_info->associate_alpha != MagickFalse)
841 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
844 if (cube_info->colors > cube_info->maximum_colors)
846 PruneToCubeDepth(image,cube_info,cube_info->root);
849 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
851 if (proceed == MagickFalse)
854 for (y++; y < (ssize_t) image->rows; y++)
856 register const PixelPacket
862 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
863 if (p == (const PixelPacket *) NULL)
865 if (cube_info->nodes > MaxNodes)
868 Prune one level if the color tree is too large.
870 PruneLevel(image,cube_info,cube_info->root);
873 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
876 Start at the root and descend the color cube tree.
878 for (count=1; (x+count) < image->columns; count++)
879 if (IsSameColor(image,p,p+count) == MagickFalse)
881 AssociateAlphaPixel(cube_info,p,&pixel);
882 index=MaxTreeDepth-1;
883 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
885 node_info=cube_info->root;
886 for (level=1; level <= cube_info->depth; level++)
889 id=ColorToNodeId(cube_info,&pixel,index);
890 mid.red+=(id & 1) != 0 ? bisect : -bisect;
891 mid.green+=(id & 2) != 0 ? bisect : -bisect;
892 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
893 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
894 if (node_info->child[id] == (NodeInfo *) NULL)
897 Set colors of new node to contain pixel.
899 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
900 if (node_info->child[id] == (NodeInfo *) NULL)
901 (void) ThrowMagickException(exception,GetMagickModule(),
902 ResourceLimitError,"MemoryAllocationFailed","%s",
904 if (level == cube_info->depth)
908 Approximate the quantization error represented by this node.
910 node_info=node_info->child[id];
911 error.red=QuantumScale*(pixel.red-mid.red);
912 error.green=QuantumScale*(pixel.green-mid.green);
913 error.blue=QuantumScale*(pixel.blue-mid.blue);
914 if (cube_info->associate_alpha != MagickFalse)
915 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
916 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
917 count*error.green*error.green+error.blue*error.blue+
918 count*error.opacity*error.opacity));
919 cube_info->root->quantize_error+=node_info->quantize_error;
923 Sum RGB for this leaf for later derivation of the mean cube color.
925 node_info->number_unique+=count;
926 node_info->total_color.red+=count*QuantumScale*pixel.red;
927 node_info->total_color.green+=count*QuantumScale*pixel.green;
928 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
929 if (cube_info->associate_alpha != MagickFalse)
930 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
933 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
935 if (proceed == MagickFalse)
938 image_view=DestroyCacheView(image_view);
939 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
940 (cube_info->quantize_info->colorspace != CMYKColorspace))
941 (void) TransformImageColorspace((Image *) image,RGBColorspace);
946 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
950 % C l o n e Q u a n t i z e I n f o %
954 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
956 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
957 % or if quantize info is NULL, a new one.
959 % The format of the CloneQuantizeInfo method is:
961 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
963 % A description of each parameter follows:
965 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
966 % quantize info, or if image info is NULL a new one.
968 % o quantize_info: a structure of type info.
971 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
976 clone_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*clone_info));
977 if (clone_info == (QuantizeInfo *) NULL)
978 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
979 GetQuantizeInfo(clone_info);
980 if (quantize_info == (QuantizeInfo *) NULL)
982 clone_info->number_colors=quantize_info->number_colors;
983 clone_info->tree_depth=quantize_info->tree_depth;
984 clone_info->dither=quantize_info->dither;
985 clone_info->dither_method=quantize_info->dither_method;
986 clone_info->colorspace=quantize_info->colorspace;
987 clone_info->measure_error=quantize_info->measure_error;
992 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
996 + C l o s e s t C o l o r %
1000 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1002 % ClosestColor() traverses the color cube tree at a particular node and
1003 % determines which colormap entry best represents the input color.
1005 % The format of the ClosestColor method is:
1007 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1008 % const NodeInfo *node_info)
1010 % A description of each parameter follows.
1012 % o image: the image.
1014 % o cube_info: A pointer to the Cube structure.
1016 % o node_info: the address of a structure of type NodeInfo which points to a
1017 % node in the color cube tree that is to be pruned.
1020 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1021 const NodeInfo *node_info)
1030 Traverse any children.
1032 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1033 for (i=0; i < (ssize_t) number_children; i++)
1034 if (node_info->child[i] != (NodeInfo *) NULL)
1035 ClosestColor(image,cube_info,node_info->child[i]);
1036 if (node_info->number_unique != 0)
1041 register MagickRealType
1046 register PixelPacket
1049 register RealPixelPacket
1053 Determine if this color is "closest".
1055 p=image->colormap+node_info->color_number;
1056 q=(&cube_info->target);
1059 if (cube_info->associate_alpha == MagickFalse)
1061 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1062 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1064 pixel=alpha*p->red-beta*q->red;
1065 distance=pixel*pixel;
1066 if (distance < cube_info->distance)
1068 pixel=alpha*p->green-beta*q->green;
1069 distance+=pixel*pixel;
1070 if (distance < cube_info->distance)
1072 pixel=alpha*p->blue-beta*q->blue;
1073 distance+=pixel*pixel;
1074 if (distance < cube_info->distance)
1077 distance+=pixel*pixel;
1078 if (distance < cube_info->distance)
1080 cube_info->distance=distance;
1081 cube_info->color_number=node_info->color_number;
1090 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1094 % C o m p r e s s I m a g e C o l o r m a p %
1098 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1100 % CompressImageColormap() compresses an image colormap by removing any
1101 % duplicate or unused color entries.
1103 % The format of the CompressImageColormap method is:
1105 % MagickBooleanType CompressImageColormap(Image *image)
1107 % A description of each parameter follows:
1109 % o image: the image.
1112 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1117 assert(image != (Image *) NULL);
1118 assert(image->signature == MagickSignature);
1119 if (image->debug != MagickFalse)
1120 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1121 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1122 return(MagickFalse);
1123 GetQuantizeInfo(&quantize_info);
1124 quantize_info.number_colors=image->colors;
1125 quantize_info.tree_depth=MaxTreeDepth;
1126 return(QuantizeImage(&quantize_info,image));
1130 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1134 + D e f i n e I m a g e C o l o r m a p %
1138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1140 % DefineImageColormap() traverses the color cube tree and notes each colormap
1141 % entry. A colormap entry is any node in the color cube tree where the
1142 % of unique colors is not zero. DefineImageColormap() returns the number of
1143 % colors in the image colormap.
1145 % The format of the DefineImageColormap method is:
1147 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1148 % NodeInfo *node_info)
1150 % A description of each parameter follows.
1152 % o image: the image.
1154 % o cube_info: A pointer to the Cube structure.
1156 % o node_info: the address of a structure of type NodeInfo which points to a
1157 % node in the color cube tree that is to be pruned.
1160 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1161 NodeInfo *node_info)
1170 Traverse any children.
1172 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1173 for (i=0; i < (ssize_t) number_children; i++)
1174 if (node_info->child[i] != (NodeInfo *) NULL)
1175 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1176 if (node_info->number_unique != 0)
1178 register MagickRealType
1181 register PixelPacket
1185 Colormap entry is defined by the mean color in this cube.
1187 q=image->colormap+image->colors;
1188 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1189 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1190 if (cube_info->associate_alpha == MagickFalse)
1192 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1193 node_info->total_color.red));
1194 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1195 node_info->total_color.green));
1196 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1197 node_info->total_color.blue));
1198 SetOpacityPixelComponent(q,OpaqueOpacity);
1205 opacity=(MagickRealType) (alpha*QuantumRange*
1206 node_info->total_color.opacity);
1207 q->opacity=ClampToQuantum(opacity);
1208 if (q->opacity == OpaqueOpacity)
1210 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1211 node_info->total_color.red));
1212 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1213 node_info->total_color.green));
1214 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1215 node_info->total_color.blue));
1222 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1223 (MagickRealType) q->opacity));
1224 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1225 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1226 node_info->total_color.red));
1227 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1228 QuantumRange*node_info->total_color.green));
1229 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1230 node_info->total_color.blue));
1231 if (node_info->number_unique > cube_info->transparent_pixels)
1233 cube_info->transparent_pixels=node_info->number_unique;
1234 cube_info->transparent_index=(ssize_t) image->colors;
1238 node_info->color_number=image->colors++;
1240 return(image->colors);
1244 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1248 + D e s t r o y C u b e I n f o %
1252 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1254 % DestroyCubeInfo() deallocates memory associated with an image.
1256 % The format of the DestroyCubeInfo method is:
1258 % DestroyCubeInfo(CubeInfo *cube_info)
1260 % A description of each parameter follows:
1262 % o cube_info: the address of a structure of type CubeInfo.
1265 static void DestroyCubeInfo(CubeInfo *cube_info)
1271 Release color cube tree storage.
1275 nodes=cube_info->node_queue->next;
1276 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1277 cube_info->node_queue->nodes);
1278 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1279 cube_info->node_queue);
1280 cube_info->node_queue=nodes;
1281 } while (cube_info->node_queue != (Nodes *) NULL);
1282 if (cube_info->cache != (ssize_t *) NULL)
1283 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1284 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1285 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1289 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1293 % D e s t r o y Q u a n t i z e I n f o %
1297 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1299 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1302 % The format of the DestroyQuantizeInfo method is:
1304 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1306 % A description of each parameter follows:
1308 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1311 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1313 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1314 assert(quantize_info != (QuantizeInfo *) NULL);
1315 assert(quantize_info->signature == MagickSignature);
1316 quantize_info->signature=(~MagickSignature);
1317 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1318 return(quantize_info);
1322 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1326 + D i t h e r I m a g e %
1330 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1332 % DitherImage() distributes the difference between an original image and
1333 % the corresponding color reduced algorithm to neighboring pixels using
1334 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1335 % MagickTrue if the image is dithered otherwise MagickFalse.
1337 % The format of the DitherImage method is:
1339 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1341 % A description of each parameter follows.
1343 % o image: the image.
1345 % o cube_info: A pointer to the Cube structure.
1349 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1351 #define DitherImageTag "Dither/Image"
1381 Distribute quantization error using Floyd-Steinberg.
1383 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1384 2*sizeof(*scanlines));
1385 if (scanlines == (RealPixelPacket *) NULL)
1386 return(MagickFalse);
1388 exception=(&image->exception);
1389 image_view=AcquireCacheView(image);
1390 for (y=0; y < (ssize_t) image->rows; y++)
1392 register IndexPacket
1399 register PixelPacket
1402 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1403 if (q == (PixelPacket *) NULL)
1404 return(MagickFalse);
1405 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1406 current=scanlines+(y & 0x01)*image->columns;
1407 previous=scanlines+((y+1) & 0x01)*image->columns;
1408 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1409 for (x=0; x < (ssize_t) image->columns; x++)
1411 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1412 AssociateAlphaPixel(cube_info,q+u,&pixel);
1415 pixel.red+=7*current[u-v].red/16;
1416 pixel.green+=7*current[u-v].green/16;
1417 pixel.blue+=7*current[u-v].blue/16;
1418 if (cube_info->associate_alpha != MagickFalse)
1419 pixel.opacity+=7*current[u-v].opacity/16;
1423 if (x < (ssize_t) (image->columns-1))
1425 pixel.red+=previous[u+v].red/16;
1426 pixel.green+=previous[u+v].green/16;
1427 pixel.blue+=previous[u+v].blue/16;
1428 if (cube_info->associate_alpha != MagickFalse)
1429 pixel.opacity+=previous[u+v].opacity/16;
1431 pixel.red+=5*previous[u].red/16;
1432 pixel.green+=5*previous[u].green/16;
1433 pixel.blue+=5*previous[u].blue/16;
1434 if (cube_info->associate_alpha != MagickFalse)
1435 pixel.opacity+=5*previous[u].opacity/16;
1438 pixel.red+=3*previous[u-v].red/16;
1439 pixel.green+=3*previous[u-v].green/16;
1440 pixel.blue+=3*previous[u-v].blue/16;
1441 if (cube_info->associate_alpha != MagickFalse)
1442 pixel.opacity+=3*previous[u-v].opacity/16;
1445 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1446 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1447 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1448 if (cube_info->associate_alpha != MagickFalse)
1449 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1450 i=(ssize_t) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
1451 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1452 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
1453 if (cube_info->associate_alpha != MagickFalse)
1454 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
1456 if (p->cache[i] < 0)
1465 Identify the deepest node containing the pixel's color.
1468 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1470 id=ColorToNodeId(cube_info,&pixel,index);
1471 if (node_info->child[id] == (NodeInfo *) NULL)
1473 node_info=node_info->child[id];
1476 Find closest color among siblings and their children.
1479 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1481 ClosestColor(image,p,node_info->parent);
1482 p->cache[i]=(ssize_t) p->color_number;
1485 Assign pixel to closest colormap entry.
1487 index=(size_t) p->cache[i];
1488 if (image->storage_class == PseudoClass)
1489 indexes[u]=(IndexPacket) index;
1490 if (cube_info->quantize_info->measure_error == MagickFalse)
1492 (q+u)->red=image->colormap[index].red;
1493 (q+u)->green=image->colormap[index].green;
1494 (q+u)->blue=image->colormap[index].blue;
1495 if (cube_info->associate_alpha != MagickFalse)
1496 (q+u)->opacity=image->colormap[index].opacity;
1498 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1499 return(MagickFalse);
1503 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1504 current[u].red=pixel.red-color.red;
1505 current[u].green=pixel.green-color.green;
1506 current[u].blue=pixel.blue-color.blue;
1507 if (cube_info->associate_alpha != MagickFalse)
1508 current[u].opacity=pixel.opacity-color.opacity;
1509 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1510 if (proceed == MagickFalse)
1511 return(MagickFalse);
1515 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1516 image_view=DestroyCacheView(image_view);
1520 static MagickBooleanType
1521 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1523 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1524 const size_t level,const unsigned int direction)
1531 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1532 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1533 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1538 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1539 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1540 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1545 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1546 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1547 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1552 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1553 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1554 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1565 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1566 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1567 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1568 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1569 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1570 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1571 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1576 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1577 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1578 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1579 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1580 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1581 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1582 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
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,NorthGravity);
1590 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1591 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1592 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1593 Riemersma(image,image_view,cube_info,level-1,EastGravity);
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,SouthGravity);
1601 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1602 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1603 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1604 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1612 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1613 CubeInfo *cube_info,const unsigned int direction)
1615 #define DitherImageTag "Dither/Image"
1631 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1632 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1637 register IndexPacket
1643 register PixelPacket
1649 exception=(&image->exception);
1650 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1651 if (q == (PixelPacket *) NULL)
1652 return(MagickFalse);
1653 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1654 AssociateAlphaPixel(cube_info,q,&pixel);
1655 for (i=0; i < ErrorQueueLength; i++)
1657 pixel.red+=p->weights[i]*p->error[i].red;
1658 pixel.green+=p->weights[i]*p->error[i].green;
1659 pixel.blue+=p->weights[i]*p->error[i].blue;
1660 if (cube_info->associate_alpha != MagickFalse)
1661 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1663 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1664 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1665 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1666 if (cube_info->associate_alpha != MagickFalse)
1667 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1668 i=(ssize_t) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
1669 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1670 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
1671 if (cube_info->associate_alpha != MagickFalse)
1672 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
1674 if (p->cache[i] < 0)
1683 Identify the deepest node containing the pixel's color.
1686 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1688 id=ColorToNodeId(cube_info,&pixel,index);
1689 if (node_info->child[id] == (NodeInfo *) NULL)
1691 node_info=node_info->child[id];
1694 Find closest color among siblings and their children.
1697 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1698 QuantumRange+1.0)+1.0);
1699 ClosestColor(image,p,node_info->parent);
1700 p->cache[i]=(ssize_t) p->color_number;
1703 Assign pixel to closest colormap entry.
1705 index=(size_t) (1*p->cache[i]);
1706 if (image->storage_class == PseudoClass)
1707 *indexes=(IndexPacket) index;
1708 if (cube_info->quantize_info->measure_error == MagickFalse)
1710 q->red=image->colormap[index].red;
1711 q->green=image->colormap[index].green;
1712 q->blue=image->colormap[index].blue;
1713 if (cube_info->associate_alpha != MagickFalse)
1714 q->opacity=image->colormap[index].opacity;
1716 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1717 return(MagickFalse);
1719 Propagate the error as the last entry of the error queue.
1721 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1722 sizeof(p->error[0]));
1723 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1724 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1725 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1726 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1727 if (cube_info->associate_alpha != MagickFalse)
1728 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1729 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1730 if (proceed == MagickFalse)
1731 return(MagickFalse);
1736 case WestGravity: p->x--; break;
1737 case EastGravity: p->x++; break;
1738 case NorthGravity: p->y--; break;
1739 case SouthGravity: p->y++; break;
1744 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1751 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1758 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1772 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1773 return(FloydSteinbergDither(image,cube_info));
1775 Distribute quantization error along a Hilbert curve.
1777 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1778 sizeof(*cube_info->error));
1781 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1782 for (depth=1; i != 0; depth++)
1784 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1786 cube_info->offset=0;
1787 cube_info->span=(MagickSizeType) image->columns*image->rows;
1788 image_view=AcquireCacheView(image);
1790 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1791 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1792 image_view=DestroyCacheView(image_view);
1797 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1801 + G e t C u b e I n f o %
1805 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1807 % GetCubeInfo() initialize the Cube data structure.
1809 % The format of the GetCubeInfo method is:
1811 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1812 % const size_t depth,const size_t maximum_colors)
1814 % A description of each parameter follows.
1816 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1818 % o depth: Normally, this integer value is zero or one. A zero or
1819 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1820 % A tree of this depth generally allows the best representation of the
1821 % reference image with the least amount of memory and the fastest
1822 % computational speed. In some cases, such as an image with low color
1823 % dispersion (a few number of colors), a value other than
1824 % Log4(number_colors) is required. To expand the color tree completely,
1827 % o maximum_colors: maximum colors.
1830 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1831 const size_t depth,const size_t maximum_colors)
1847 Initialize tree to describe color cube_info.
1849 cube_info=(CubeInfo *) AcquireAlignedMemory(1,sizeof(*cube_info));
1850 if (cube_info == (CubeInfo *) NULL)
1851 return((CubeInfo *) NULL);
1852 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1853 cube_info->depth=depth;
1854 if (cube_info->depth > MaxTreeDepth)
1855 cube_info->depth=MaxTreeDepth;
1856 if (cube_info->depth < 2)
1858 cube_info->maximum_colors=maximum_colors;
1860 Initialize root node.
1862 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1863 if (cube_info->root == (NodeInfo *) NULL)
1864 return((CubeInfo *) NULL);
1865 cube_info->root->parent=cube_info->root;
1866 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1867 if (cube_info->quantize_info->dither == MagickFalse)
1870 Initialize dither resources.
1872 length=(size_t) (1UL << (4*(8-CacheShift)));
1873 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1874 sizeof(*cube_info->cache));
1875 if (cube_info->cache == (ssize_t *) NULL)
1876 return((CubeInfo *) NULL);
1878 Initialize color cache.
1880 for (i=0; i < (ssize_t) length; i++)
1881 cube_info->cache[i]=(-1);
1883 Distribute weights along a curve of exponential decay.
1886 for (i=0; i < ErrorQueueLength; i++)
1888 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1889 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1892 Normalize the weighting factors.
1895 for (i=0; i < ErrorQueueLength; i++)
1896 weight+=cube_info->weights[i];
1898 for (i=0; i < ErrorQueueLength; i++)
1900 cube_info->weights[i]/=weight;
1901 sum+=cube_info->weights[i];
1903 cube_info->weights[0]+=1.0-sum;
1908 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1912 + G e t N o d e I n f o %
1916 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1918 % GetNodeInfo() allocates memory for a new node in the color cube tree and
1919 % presets all fields to zero.
1921 % The format of the GetNodeInfo method is:
1923 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1924 % const size_t level,NodeInfo *parent)
1926 % A description of each parameter follows.
1928 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1930 % o id: Specifies the child number of the node.
1932 % o level: Specifies the level in the storage_class the node resides.
1935 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1936 const size_t level,NodeInfo *parent)
1941 if (cube_info->free_nodes == 0)
1947 Allocate a new queue of nodes.
1949 nodes=(Nodes *) AcquireAlignedMemory(1,sizeof(*nodes));
1950 if (nodes == (Nodes *) NULL)
1951 return((NodeInfo *) NULL);
1952 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1953 sizeof(*nodes->nodes));
1954 if (nodes->nodes == (NodeInfo *) NULL)
1955 return((NodeInfo *) NULL);
1956 nodes->next=cube_info->node_queue;
1957 cube_info->node_queue=nodes;
1958 cube_info->next_node=nodes->nodes;
1959 cube_info->free_nodes=NodesInAList;
1962 cube_info->free_nodes--;
1963 node_info=cube_info->next_node++;
1964 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1965 node_info->parent=parent;
1967 node_info->level=level;
1972 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1976 % G e t I m a g e Q u a n t i z e E r r o r %
1980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1982 % GetImageQuantizeError() measures the difference between the original
1983 % and quantized images. This difference is the total quantization error.
1984 % The error is computed by summing over all pixels in an image the distance
1985 % squared in RGB space between each reference pixel value and its quantized
1986 % value. These values are computed:
1988 % o mean_error_per_pixel: This value is the mean error for any single
1989 % pixel in the image.
1991 % o normalized_mean_square_error: This value is the normalized mean
1992 % quantization error for any single pixel in the image. This distance
1993 % measure is normalized to a range between 0 and 1. It is independent
1994 % of the range of red, green, and blue values in the image.
1996 % o normalized_maximum_square_error: Thsi value is the normalized
1997 % maximum quantization error for any single pixel in the image. This
1998 % distance measure is normalized to a range between 0 and 1. It is
1999 % independent of the range of red, green, and blue values in your image.
2001 % The format of the GetImageQuantizeError method is:
2003 % MagickBooleanType GetImageQuantizeError(Image *image)
2005 % A description of each parameter follows.
2007 % o image: the image.
2010 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2031 mean_error_per_pixel;
2036 assert(image != (Image *) NULL);
2037 assert(image->signature == MagickSignature);
2038 if (image->debug != MagickFalse)
2039 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2040 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2041 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2042 if (image->storage_class == DirectClass)
2046 area=3.0*image->columns*image->rows;
2048 mean_error_per_pixel=0.0;
2050 exception=(&image->exception);
2051 image_view=AcquireCacheView(image);
2052 for (y=0; y < (ssize_t) image->rows; y++)
2054 register const PixelPacket
2060 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2061 if (p == (const PixelPacket *) NULL)
2063 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2064 for (x=0; x < (ssize_t) image->columns; x++)
2066 index=1UL*indexes[x];
2067 if (image->matte != MagickFalse)
2069 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2070 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2071 image->colormap[index].opacity));
2073 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2074 mean_error_per_pixel+=distance;
2075 mean_error+=distance*distance;
2076 if (distance > maximum_error)
2077 maximum_error=distance;
2078 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2079 mean_error_per_pixel+=distance;
2080 mean_error+=distance*distance;
2081 if (distance > maximum_error)
2082 maximum_error=distance;
2083 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2084 mean_error_per_pixel+=distance;
2085 mean_error+=distance*distance;
2086 if (distance > maximum_error)
2087 maximum_error=distance;
2091 image_view=DestroyCacheView(image_view);
2092 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2093 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2095 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2100 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2104 % G e t Q u a n t i z e I n f o %
2108 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2110 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2112 % The format of the GetQuantizeInfo method is:
2114 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2116 % A description of each parameter follows:
2118 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2121 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2123 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2124 assert(quantize_info != (QuantizeInfo *) NULL);
2125 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2126 quantize_info->number_colors=256;
2127 quantize_info->dither=MagickTrue;
2128 quantize_info->dither_method=RiemersmaDitherMethod;
2129 quantize_info->colorspace=UndefinedColorspace;
2130 quantize_info->measure_error=MagickFalse;
2131 quantize_info->signature=MagickSignature;
2135 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2139 % P o s t e r i z e I m a g e %
2143 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2145 % PosterizeImage() reduces the image to a limited number of colors for a
2148 % The format of the PosterizeImage method is:
2150 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2151 % const MagickBooleanType dither)
2153 % A description of each parameter follows:
2155 % o image: Specifies a pointer to an Image structure.
2157 % o levels: Number of color levels allowed in each channel. Very low values
2158 % (2, 3, or 4) have the most visible effect.
2160 % o dither: Set this integer value to something other than zero to
2161 % dither the mapped image.
2164 MagickExport MagickBooleanType PosterizeImage(Image *image,
2165 const size_t levels,const MagickBooleanType dither)
2194 register PixelPacket
2203 assert(image != (Image *) NULL);
2204 assert(image->signature == MagickSignature);
2205 if (image->debug != MagickFalse)
2206 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2207 posterize_image=AcquireImage((ImageInfo *) NULL);
2208 if (posterize_image == (Image *) NULL)
2209 return(MagickFalse);
2211 length=(size_t) (levels*levels*levels);
2212 while ((l*l*l) < (ssize_t) MagickMin((ssize_t) length,MaxColormapSize+1))
2214 status=SetImageExtent(posterize_image,(size_t) (l*l*l),1);
2215 if (status == MagickFalse)
2217 posterize_image=DestroyImage(posterize_image);
2218 return(MagickFalse);
2220 status=AcquireImageColormap(posterize_image,levels*levels*levels);
2221 if (status == MagickFalse)
2223 posterize_image=DestroyImage(posterize_image);
2224 return(MagickFalse);
2226 posterize_view=AcquireCacheView(posterize_image);
2227 exception=(&image->exception);
2228 q=QueueCacheViewAuthenticPixels(posterize_view,0,0,posterize_image->columns,1,
2230 if (q == (PixelPacket *) NULL)
2232 posterize_view=DestroyCacheView(posterize_view);
2233 posterize_image=DestroyImage(posterize_image);
2234 return(MagickFalse);
2236 indexes=GetCacheViewAuthenticIndexQueue(posterize_view);
2238 for (i=0; i < l; i++)
2239 for (j=0; j < l; j++)
2240 for (k=0; k < l; k++)
2242 posterize_image->colormap[n].red=(Quantum) (QuantumRange*i/
2243 MagickMax(l-1L,1L));
2244 posterize_image->colormap[n].green=(Quantum)
2245 (QuantumRange*j/MagickMax(l-1L,1L));
2246 posterize_image->colormap[n].blue=(Quantum) (QuantumRange*k/
2247 MagickMax(l-1L,1L));
2248 posterize_image->colormap[n].opacity=OpaqueOpacity;
2249 *q++=posterize_image->colormap[n];
2250 indexes[n]=(IndexPacket) n;
2253 if (SyncCacheViewAuthenticPixels(posterize_view,exception) == MagickFalse)
2255 posterize_view=DestroyCacheView(posterize_view);
2256 posterize_image=DestroyImage(posterize_image);
2257 return(MagickFalse);
2259 posterize_view=DestroyCacheView(posterize_view);
2260 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2261 quantize_info->dither=dither;
2262 status=RemapImage(quantize_info,image,posterize_image);
2263 quantize_info=DestroyQuantizeInfo(quantize_info);
2264 posterize_image=DestroyImage(posterize_image);
2269 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2273 + P r u n e C h i l d %
2277 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2279 % PruneChild() deletes the given node and merges its statistics into its
2282 % The format of the PruneSubtree method is:
2284 % PruneChild(const Image *image,CubeInfo *cube_info,
2285 % const NodeInfo *node_info)
2287 % A description of each parameter follows.
2289 % o image: the image.
2291 % o cube_info: A pointer to the Cube structure.
2293 % o node_info: pointer to node in color cube tree that is to be pruned.
2296 static void PruneChild(const Image *image,CubeInfo *cube_info,
2297 const NodeInfo *node_info)
2309 Traverse any children.
2311 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2312 for (i=0; i < (ssize_t) number_children; i++)
2313 if (node_info->child[i] != (NodeInfo *) NULL)
2314 PruneChild(image,cube_info,node_info->child[i]);
2316 Merge color statistics into parent.
2318 parent=node_info->parent;
2319 parent->number_unique+=node_info->number_unique;
2320 parent->total_color.red+=node_info->total_color.red;
2321 parent->total_color.green+=node_info->total_color.green;
2322 parent->total_color.blue+=node_info->total_color.blue;
2323 parent->total_color.opacity+=node_info->total_color.opacity;
2324 parent->child[node_info->id]=(NodeInfo *) NULL;
2329 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2333 + P r u n e L e v e l %
2337 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2339 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2340 % their color statistics into their parent node.
2342 % The format of the PruneLevel method is:
2344 % PruneLevel(const Image *image,CubeInfo *cube_info,
2345 % const NodeInfo *node_info)
2347 % A description of each parameter follows.
2349 % o image: the image.
2351 % o cube_info: A pointer to the Cube structure.
2353 % o node_info: pointer to node in color cube tree that is to be pruned.
2356 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2357 const NodeInfo *node_info)
2366 Traverse any children.
2368 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2369 for (i=0; i < (ssize_t) number_children; i++)
2370 if (node_info->child[i] != (NodeInfo *) NULL)
2371 PruneLevel(image,cube_info,node_info->child[i]);
2372 if (node_info->level == cube_info->depth)
2373 PruneChild(image,cube_info,node_info);
2377 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2381 + P r u n e T o C u b e D e p t h %
2385 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2387 % PruneToCubeDepth() deletes any nodes at a depth greater than
2388 % cube_info->depth while merging their color statistics into their parent
2391 % The format of the PruneToCubeDepth method is:
2393 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2394 % const NodeInfo *node_info)
2396 % A description of each parameter follows.
2398 % o cube_info: A pointer to the Cube structure.
2400 % o node_info: pointer to node in color cube tree that is to be pruned.
2403 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2404 const NodeInfo *node_info)
2413 Traverse any children.
2415 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2416 for (i=0; i < (ssize_t) number_children; i++)
2417 if (node_info->child[i] != (NodeInfo *) NULL)
2418 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2419 if (node_info->level > cube_info->depth)
2420 PruneChild(image,cube_info,node_info);
2424 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2428 % Q u a n t i z e I m a g e %
2432 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2434 % QuantizeImage() analyzes the colors within a reference image and chooses a
2435 % fixed number of colors to represent the image. The goal of the algorithm
2436 % is to minimize the color difference between the input and output image while
2437 % minimizing the processing time.
2439 % The format of the QuantizeImage method is:
2441 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2444 % A description of each parameter follows:
2446 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2448 % o image: the image.
2451 static MagickBooleanType DirectToColormapImage(Image *image,
2452 ExceptionInfo *exception)
2470 number_colors=(size_t) (image->columns*image->rows);
2471 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2472 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2475 image_view=AcquireCacheView(image);
2476 for (y=0; y < (ssize_t) image->rows; y++)
2481 register IndexPacket
2484 register PixelPacket
2490 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2491 if (q == (const PixelPacket *) NULL)
2493 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2494 for (x=0; x < (ssize_t) image->columns; x++)
2496 indexes[x]=(IndexPacket) i;
2497 image->colormap[i++]=(*q++);
2499 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2501 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2503 if (proceed == MagickFalse)
2506 image_view=DestroyCacheView(image_view);
2510 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2523 assert(quantize_info != (const QuantizeInfo *) NULL);
2524 assert(quantize_info->signature == MagickSignature);
2525 assert(image != (Image *) NULL);
2526 assert(image->signature == MagickSignature);
2527 if (image->debug != MagickFalse)
2528 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2529 maximum_colors=quantize_info->number_colors;
2530 if (maximum_colors == 0)
2531 maximum_colors=MaxColormapSize;
2532 if (maximum_colors > MaxColormapSize)
2533 maximum_colors=MaxColormapSize;
2534 if ((image->columns*image->rows) <= maximum_colors)
2535 return(DirectToColormapImage(image,&image->exception));
2536 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2537 (image->matte == MagickFalse))
2538 (void) SetGrayscaleImage(image);
2539 if ((image->storage_class == PseudoClass) &&
2540 (image->colors <= maximum_colors))
2542 depth=quantize_info->tree_depth;
2549 Depth of color tree is: Log4(colormap size)+2.
2551 colors=maximum_colors;
2552 for (depth=1; colors != 0; depth++)
2554 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2556 if ((image->matte != MagickFalse) && (depth > 5))
2560 Initialize color cube.
2562 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2563 if (cube_info == (CubeInfo *) NULL)
2564 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2566 status=ClassifyImageColors(cube_info,image,&image->exception);
2567 if (status != MagickFalse)
2570 Reduce the number of colors in the image.
2572 ReduceImageColors(image,cube_info);
2573 status=AssignImageColors(image,cube_info);
2575 DestroyCubeInfo(cube_info);
2580 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2584 % Q u a n t i z e I m a g e s %
2588 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2590 % QuantizeImages() analyzes the colors within a set of reference images and
2591 % chooses a fixed number of colors to represent the set. The goal of the
2592 % algorithm is to minimize the color difference between the input and output
2593 % images while minimizing the processing time.
2595 % The format of the QuantizeImages method is:
2597 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2600 % A description of each parameter follows:
2602 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2604 % o images: Specifies a pointer to a list of Image structures.
2607 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2620 MagickProgressMonitor
2631 assert(quantize_info != (const QuantizeInfo *) NULL);
2632 assert(quantize_info->signature == MagickSignature);
2633 assert(images != (Image *) NULL);
2634 assert(images->signature == MagickSignature);
2635 if (images->debug != MagickFalse)
2636 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2637 if (GetNextImageInList(images) == (Image *) NULL)
2640 Handle a single image with QuantizeImage.
2642 status=QuantizeImage(quantize_info,images);
2646 maximum_colors=quantize_info->number_colors;
2647 if (maximum_colors == 0)
2648 maximum_colors=MaxColormapSize;
2649 if (maximum_colors > MaxColormapSize)
2650 maximum_colors=MaxColormapSize;
2651 depth=quantize_info->tree_depth;
2658 Depth of color tree is: Log4(colormap size)+2.
2660 colors=maximum_colors;
2661 for (depth=1; colors != 0; depth++)
2663 if (quantize_info->dither != MagickFalse)
2667 Initialize color cube.
2669 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2670 if (cube_info == (CubeInfo *) NULL)
2672 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2673 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2674 return(MagickFalse);
2676 number_images=GetImageListLength(images);
2678 for (i=0; image != (Image *) NULL; i++)
2680 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2681 image->client_data);
2682 status=ClassifyImageColors(cube_info,image,&image->exception);
2683 if (status == MagickFalse)
2685 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2686 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2688 if (proceed == MagickFalse)
2690 image=GetNextImageInList(image);
2692 if (status != MagickFalse)
2695 Reduce the number of colors in an image sequence.
2697 ReduceImageColors(images,cube_info);
2699 for (i=0; image != (Image *) NULL; i++)
2701 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2702 NULL,image->client_data);
2703 status=AssignImageColors(image,cube_info);
2704 if (status == MagickFalse)
2706 (void) SetImageProgressMonitor(image,progress_monitor,
2707 image->client_data);
2708 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2710 if (proceed == MagickFalse)
2712 image=GetNextImageInList(image);
2715 DestroyCubeInfo(cube_info);
2720 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2728 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2730 % Reduce() traverses the color cube tree and prunes any node whose
2731 % quantization error falls below a particular threshold.
2733 % The format of the Reduce method is:
2735 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2737 % A description of each parameter follows.
2739 % o image: the image.
2741 % o cube_info: A pointer to the Cube structure.
2743 % o node_info: pointer to node in color cube tree that is to be pruned.
2746 static void Reduce(const Image *image,CubeInfo *cube_info,
2747 const NodeInfo *node_info)
2756 Traverse any children.
2758 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2759 for (i=0; i < (ssize_t) number_children; i++)
2760 if (node_info->child[i] != (NodeInfo *) NULL)
2761 Reduce(image,cube_info,node_info->child[i]);
2762 if (node_info->quantize_error <= cube_info->pruning_threshold)
2763 PruneChild(image,cube_info,node_info);
2767 Find minimum pruning threshold.
2769 if (node_info->number_unique > 0)
2770 cube_info->colors++;
2771 if (node_info->quantize_error < cube_info->next_threshold)
2772 cube_info->next_threshold=node_info->quantize_error;
2777 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2781 + R e d u c e I m a g e C o l o r s %
2785 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2787 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2788 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2789 % in the output image. On any given iteration over the tree, it selects
2790 % those nodes whose E value is minimal for pruning and merges their
2791 % color statistics upward. It uses a pruning threshold, Ep, to govern
2792 % node selection as follows:
2795 % while number of nodes with (n2 > 0) > required maximum number of colors
2796 % prune all nodes such that E <= Ep
2797 % Set Ep to minimum E in remaining nodes
2799 % This has the effect of minimizing any quantization error when merging
2800 % two nodes together.
2802 % When a node to be pruned has offspring, the pruning procedure invokes
2803 % itself recursively in order to prune the tree from the leaves upward.
2804 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2805 % corresponding data in that node's parent. This retains the pruned
2806 % node's color characteristics for later averaging.
2808 % For each node, n2 pixels exist for which that node represents the
2809 % smallest volume in RGB space containing those pixel's colors. When n2
2810 % > 0 the node will uniquely define a color in the output image. At the
2811 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2812 % the tree which represent colors present in the input image.
2814 % The other pixel count, n1, indicates the total number of colors
2815 % within the cubic volume which the node represents. This includes n1 -
2816 % n2 pixels whose colors should be defined by nodes at a lower level in
2819 % The format of the ReduceImageColors method is:
2821 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2823 % A description of each parameter follows.
2825 % o image: the image.
2827 % o cube_info: A pointer to the Cube structure.
2830 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2832 #define ReduceImageTag "Reduce/Image"
2843 cube_info->next_threshold=0.0;
2844 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2846 cube_info->pruning_threshold=cube_info->next_threshold;
2847 cube_info->next_threshold=cube_info->root->quantize_error-1;
2848 cube_info->colors=0;
2849 Reduce(image,cube_info,cube_info->root);
2850 offset=(MagickOffsetType) span-cube_info->colors;
2851 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2852 cube_info->maximum_colors+1);
2853 if (proceed == MagickFalse)
2859 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2863 % R e m a p I m a g e %
2867 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2869 % RemapImage() replaces the colors of an image with the closest color from
2870 % a reference image.
2872 % The format of the RemapImage method is:
2874 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2875 % Image *image,const Image *remap_image)
2877 % A description of each parameter follows:
2879 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2881 % o image: the image.
2883 % o remap_image: the reference image.
2886 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2887 Image *image,const Image *remap_image)
2896 Initialize color cube.
2898 assert(image != (Image *) NULL);
2899 assert(image->signature == MagickSignature);
2900 if (image->debug != MagickFalse)
2901 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2902 assert(remap_image != (Image *) NULL);
2903 assert(remap_image->signature == MagickSignature);
2904 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2905 quantize_info->number_colors);
2906 if (cube_info == (CubeInfo *) NULL)
2907 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2909 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2910 if (status != MagickFalse)
2913 Classify image colors from the reference image.
2915 cube_info->quantize_info->number_colors=cube_info->colors;
2916 status=AssignImageColors(image,cube_info);
2918 DestroyCubeInfo(cube_info);
2923 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2927 % R e m a p I m a g e s %
2931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2933 % RemapImages() replaces the colors of a sequence of images with the
2934 % closest color from a reference image.
2936 % The format of the RemapImage method is:
2938 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2939 % Image *images,Image *remap_image)
2941 % A description of each parameter follows:
2943 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2945 % o images: the image sequence.
2947 % o remap_image: the reference image.
2950 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2951 Image *images,const Image *remap_image)
2962 assert(images != (Image *) NULL);
2963 assert(images->signature == MagickSignature);
2964 if (images->debug != MagickFalse)
2965 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2967 if (remap_image == (Image *) NULL)
2970 Create a global colormap for an image sequence.
2972 status=QuantizeImages(quantize_info,images);
2976 Classify image colors from the reference image.
2978 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2979 quantize_info->number_colors);
2980 if (cube_info == (CubeInfo *) NULL)
2981 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2983 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2984 if (status != MagickFalse)
2987 Classify image colors from the reference image.
2989 cube_info->quantize_info->number_colors=cube_info->colors;
2991 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
2993 status=AssignImageColors(image,cube_info);
2994 if (status == MagickFalse)
2998 DestroyCubeInfo(cube_info);
3003 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3007 % S e t G r a y s c a l e I m a g e %
3011 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3013 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3015 % The format of the SetGrayscaleImage method is:
3017 % MagickBooleanType SetGrayscaleImage(Image *image)
3019 % A description of each parameter follows:
3021 % o image: The image.
3025 #if defined(__cplusplus) || defined(c_plusplus)
3029 static int IntensityCompare(const void *x,const void *y)
3038 color_1=(PixelPacket *) x;
3039 color_2=(PixelPacket *) y;
3040 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3041 PixelIntensityToQuantum(color_2);
3042 return((int) intensity);
3045 #if defined(__cplusplus) || defined(c_plusplus)
3049 static MagickBooleanType SetGrayscaleImage(Image *image)
3073 assert(image != (Image *) NULL);
3074 assert(image->signature == MagickSignature);
3075 if (image->type != GrayscaleType)
3076 (void) TransformImageColorspace(image,GRAYColorspace);
3077 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3078 sizeof(*colormap_index));
3079 if (colormap_index == (ssize_t *) NULL)
3080 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3082 if (image->storage_class != PseudoClass)
3087 for (i=0; i <= (ssize_t) MaxMap; i++)
3088 colormap_index[i]=(-1);
3089 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3090 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3094 exception=(&image->exception);
3095 image_view=AcquireCacheView(image);
3096 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3097 #pragma omp parallel for schedule(dynamic,4) shared(status)
3099 for (y=0; y < (ssize_t) image->rows; y++)
3101 register IndexPacket
3107 register const PixelPacket
3110 if (status == MagickFalse)
3112 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3114 if (q == (PixelPacket *) NULL)
3119 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3120 for (x=0; x < (ssize_t) image->columns; x++)
3125 intensity=ScaleQuantumToMap(q->red);
3126 if (colormap_index[intensity] < 0)
3128 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3129 #pragma omp critical (MagickCore_SetGrayscaleImage)
3131 if (colormap_index[intensity] < 0)
3133 colormap_index[intensity]=(ssize_t) image->colors;
3134 image->colormap[image->colors]=(*q);
3138 indexes[x]=(IndexPacket) colormap_index[intensity];
3141 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3144 image_view=DestroyCacheView(image_view);
3146 for (i=0; i < (ssize_t) image->colors; i++)
3147 image->colormap[i].opacity=(unsigned short) i;
3148 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3150 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3152 if (colormap == (PixelPacket *) NULL)
3153 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3156 colormap[j]=image->colormap[0];
3157 for (i=0; i < (ssize_t) image->colors; i++)
3159 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3162 colormap[j]=image->colormap[i];
3164 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3166 image->colors=(size_t) (j+1);
3167 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3168 image->colormap=colormap;
3170 exception=(&image->exception);
3171 image_view=AcquireCacheView(image);
3172 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3173 #pragma omp parallel for schedule(dynamic,4) shared(status)
3175 for (y=0; y < (ssize_t) image->rows; y++)
3177 register IndexPacket
3183 register const PixelPacket
3186 if (status == MagickFalse)
3188 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3189 if (q == (PixelPacket *) NULL)
3194 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3195 for (x=0; x < (ssize_t) image->columns; x++)
3196 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3197 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3200 image_view=DestroyCacheView(image_view);
3201 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3202 image->type=GrayscaleType;
3203 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3204 image->type=BilevelType;