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/colorspace.h"
182 #include "magick/enhance.h"
183 #include "magick/exception.h"
184 #include "magick/exception-private.h"
185 #include "magick/histogram.h"
186 #include "magick/image.h"
187 #include "magick/image-private.h"
188 #include "magick/list.h"
189 #include "magick/memory_.h"
190 #include "magick/monitor.h"
191 #include "magick/monitor-private.h"
192 #include "magick/option.h"
193 #include "magick/pixel-private.h"
194 #include "magick/quantize.h"
195 #include "magick/quantum.h"
196 #include "magick/string_.h"
202 #define ErrorQueueLength 16
203 #define MaxNodes 266817
204 #define MaxTreeDepth 8
205 #define NodesInAList 1920
210 typedef struct _RealPixelPacket
219 typedef struct _NodeInfo
240 typedef struct _Nodes
249 typedef struct _CubeInfo
287 error[ErrorQueueLength];
290 weights[ErrorQueueLength];
316 *GetCubeInfo(const QuantizeInfo *,const unsigned long,const unsigned long);
319 *GetNodeInfo(CubeInfo *,const unsigned long,const unsigned long,NodeInfo *);
321 static MagickBooleanType
322 AssignImageColors(Image *,CubeInfo *),
323 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
324 DitherImage(Image *,CubeInfo *),
325 SetGrayscaleImage(Image *);
328 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
331 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
332 DestroyCubeInfo(CubeInfo *),
333 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
334 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
335 ReduceImageColors(const Image *,CubeInfo *);
338 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
342 % A c q u i r e Q u a n t i z e I n f o %
346 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
348 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
350 % The format of the AcquireQuantizeInfo method is:
352 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
354 % A description of each parameter follows:
356 % o image_info: the image info.
359 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
364 quantize_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*quantize_info));
365 if (quantize_info == (QuantizeInfo *) NULL)
366 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
367 GetQuantizeInfo(quantize_info);
368 if (image_info != (ImageInfo *) NULL)
373 quantize_info->dither=image_info->dither;
374 option=GetImageOption(image_info,"dither");
375 if (option != (const char *) NULL)
376 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
377 MagickDitherOptions,MagickFalse,option);
378 quantize_info->measure_error=image_info->verbose;
380 return(quantize_info);
384 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
388 + A s s i g n I m a g e C o l o r s %
392 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
394 % AssignImageColors() generates the output image from the pruned tree. The
395 % output image consists of two parts: (1) A color map, which is an array
396 % of color descriptions (RGB triples) for each color present in the
397 % output image; (2) A pixel array, which represents each pixel as an
398 % index into the color map array.
400 % First, the assignment phase makes one pass over the pruned color
401 % description tree to establish the image's color map. For each node
402 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
403 % color of all pixels that classify no lower than this node. Each of
404 % these colors becomes an entry in the color map.
406 % Finally, the assignment phase reclassifies each pixel in the pruned
407 % tree to identify the deepest node containing the pixel's color. The
408 % pixel's value in the pixel array becomes the index of this node's mean
409 % color in the color map.
411 % The format of the AssignImageColors() method is:
413 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
415 % A description of each parameter follows.
417 % o image: the image.
419 % o cube_info: A pointer to the Cube structure.
423 static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
424 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
429 if ((cube_info->associate_alpha == MagickFalse) ||
430 (pixel->opacity == OpaqueOpacity))
432 alpha_pixel->red=(MagickRealType) pixel->red;
433 alpha_pixel->green=(MagickRealType) pixel->green;
434 alpha_pixel->blue=(MagickRealType) pixel->blue;
435 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
438 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
439 alpha_pixel->red=alpha*pixel->red;
440 alpha_pixel->green=alpha*pixel->green;
441 alpha_pixel->blue=alpha*pixel->blue;
442 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
445 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
449 if (value >= QuantumRange)
450 return((Quantum) QuantumRange);
451 return((Quantum) (value+0.5));
454 static inline unsigned long ColorToNodeId(const CubeInfo *cube_info,
455 const RealPixelPacket *pixel,unsigned long index)
461 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
462 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
463 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
464 if (cube_info->associate_alpha != MagickFalse)
465 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
470 static inline MagickBooleanType IsSameColor(const Image *image,
471 const PixelPacket *p,const PixelPacket *q)
473 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
475 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
480 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
482 #define AssignImageTag "Assign/Image"
497 register const NodeInfo
508 Allocate image colormap.
510 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
511 (cube_info->quantize_info->colorspace != CMYKColorspace))
512 (void) TransformImageColorspace((Image *) image,
513 cube_info->quantize_info->colorspace);
515 if ((image->colorspace != GRAYColorspace) &&
516 (image->colorspace != RGBColorspace) &&
517 (image->colorspace != CMYColorspace))
518 (void) TransformImageColorspace((Image *) image,RGBColorspace);
519 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
520 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
523 cube_info->transparent_pixels=0;
524 cube_info->transparent_index=(-1);
525 (void) DefineImageColormap(image,cube_info,cube_info->root);
527 Create a reduced color image.
529 if ((cube_info->quantize_info->dither != MagickFalse) &&
530 (cube_info->quantize_info->dither_method != NoDitherMethod))
531 (void) DitherImage(image,cube_info);
540 exception=(&image->exception);
541 image_view=AcquireCacheView(image);
542 for (y=0; y < (long) image->rows; y++)
550 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
552 if (q == (PixelPacket *) NULL)
554 indexes=GetCacheViewAuthenticIndexQueue(image_view);
555 for (x=0; x < (long) image->columns; x+=count)
558 Identify the deepest node containing the pixel's color.
560 for (count=1; (x+count) < (long) image->columns; count++)
561 if (IsSameColor(image,q,q+count) == MagickFalse)
563 AssociateAlphaPixel(cube_info,q,&pixel);
564 node_info=cube_info->root;
565 for (index=MaxTreeDepth-1; (long) index > 0; index--)
567 id=ColorToNodeId(cube_info,&pixel,index);
568 if (node_info->child[id] == (NodeInfo *) NULL)
570 node_info=node_info->child[id];
573 Find closest color among siblings and their children.
575 cube_info->target=pixel;
576 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
577 (QuantumRange+1.0)+1.0);
578 ClosestColor(image,cube_info,node_info->parent);
579 index=cube_info->color_number;
580 for (i=0; i < (long) count; i++)
582 if (image->storage_class == PseudoClass)
583 indexes[x+i]=(IndexPacket) index;
584 if (cube_info->quantize_info->measure_error == MagickFalse)
586 q->red=image->colormap[index].red;
587 q->green=image->colormap[index].green;
588 q->blue=image->colormap[index].blue;
589 if (cube_info->associate_alpha != MagickFalse)
590 q->opacity=image->colormap[index].opacity;
595 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
597 proceed=SetImageProgress(image,AssignImageTag,y,image->rows);
598 if (proceed == MagickFalse)
601 image_view=DestroyCacheView(image_view);
603 if (cube_info->quantize_info->measure_error != MagickFalse)
604 (void) GetImageQuantizeError(image);
605 if ((cube_info->quantize_info->number_colors == 2) &&
606 (cube_info->quantize_info->colorspace == GRAYColorspace))
618 for (i=0; i < (long) image->colors; i++)
620 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
621 QuantumRange/2.0) ? 0 : QuantumRange);
628 (void) SyncImage(image);
629 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
630 (cube_info->quantize_info->colorspace != CMYKColorspace))
631 (void) TransformImageColorspace((Image *) image,RGBColorspace);
636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
640 + C l a s s i f y I m a g e C o l o r s %
644 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
646 % ClassifyImageColors() begins by initializing a color description tree
647 % of sufficient depth to represent each possible input color in a leaf.
648 % However, it is impractical to generate a fully-formed color
649 % description tree in the storage_class phase for realistic values of
650 % Cmax. If colors components in the input image are quantized to k-bit
651 % precision, so that Cmax= 2k-1, the tree would need k levels below the
652 % root node to allow representing each possible input color in a leaf.
653 % This becomes prohibitive because the tree's total number of nodes is
656 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
657 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
658 % Initializes data structures for nodes only as they are needed; (2)
659 % Chooses a maximum depth for the tree as a function of the desired
660 % number of colors in the output image (currently log2(colormap size)).
662 % For each pixel in the input image, storage_class scans downward from
663 % the root of the color description tree. At each level of the tree it
664 % identifies the single node which represents a cube in RGB space
665 % containing It updates the following data for each such node:
667 % n1 : Number of pixels whose color is contained in the RGB cube
668 % which this node represents;
670 % n2 : Number of pixels whose color is not represented in a node at
671 % lower depth in the tree; initially, n2 = 0 for all nodes except
672 % leaves of the tree.
674 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
675 % all pixels not classified at a lower depth. The combination of
676 % these sums and n2 will ultimately characterize the mean color of a
677 % set of pixels represented by this node.
679 % E: the distance squared in RGB space between each pixel contained
680 % within a node and the nodes' center. This represents the quantization
683 % The format of the ClassifyImageColors() method is:
685 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
686 % const Image *image,ExceptionInfo *exception)
688 % A description of each parameter follows.
690 % o cube_info: A pointer to the Cube structure.
692 % o image: the image.
696 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
701 associate_alpha=image->matte;
702 if (cube_info->quantize_info->colorspace == TransparentColorspace)
703 associate_alpha=MagickFalse;
704 if ((cube_info->quantize_info->number_colors == 2) &&
705 (cube_info->quantize_info->colorspace == GRAYColorspace))
706 associate_alpha=MagickFalse;
707 cube_info->associate_alpha=associate_alpha;
710 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
711 const Image *image,ExceptionInfo *exception)
713 #define ClassifyImageTag "Classify/Image"
745 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
747 SetAssociatedAlpha(image,cube_info);
748 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
749 (cube_info->quantize_info->colorspace != CMYKColorspace))
750 (void) TransformImageColorspace((Image *) image,
751 cube_info->quantize_info->colorspace);
753 if ((image->colorspace != GRAYColorspace) &&
754 (image->colorspace != CMYColorspace) &&
755 (image->colorspace != RGBColorspace))
756 (void) TransformImageColorspace((Image *) image,RGBColorspace);
757 midpoint.red=(MagickRealType) QuantumRange/2.0;
758 midpoint.green=(MagickRealType) QuantumRange/2.0;
759 midpoint.blue=(MagickRealType) QuantumRange/2.0;
760 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
762 image_view=AcquireCacheView(image);
763 for (y=0; y < (long) image->rows; y++)
765 register const PixelPacket
771 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
772 if (p == (const PixelPacket *) NULL)
774 if (cube_info->nodes > MaxNodes)
777 Prune one level if the color tree is too large.
779 PruneLevel(image,cube_info,cube_info->root);
782 for (x=0; x < (long) image->columns; x+=(long) count)
785 Start at the root and descend the color cube tree.
787 for (count=1; (x+count) < image->columns; count++)
788 if (IsSameColor(image,p,p+count) == MagickFalse)
790 AssociateAlphaPixel(cube_info,p,&pixel);
791 index=MaxTreeDepth-1;
792 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
794 node_info=cube_info->root;
795 for (level=1; level <= MaxTreeDepth; level++)
798 id=ColorToNodeId(cube_info,&pixel,index);
799 mid.red+=(id & 1) != 0 ? bisect : -bisect;
800 mid.green+=(id & 2) != 0 ? bisect : -bisect;
801 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
802 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
803 if (node_info->child[id] == (NodeInfo *) NULL)
806 Set colors of new node to contain pixel.
808 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
809 if (node_info->child[id] == (NodeInfo *) NULL)
810 (void) ThrowMagickException(exception,GetMagickModule(),
811 ResourceLimitError,"MemoryAllocationFailed","`%s'",
813 if (level == MaxTreeDepth)
817 Approximate the quantization error represented by this node.
819 node_info=node_info->child[id];
820 error.red=QuantumScale*(pixel.red-mid.red);
821 error.green=QuantumScale*(pixel.green-mid.green);
822 error.blue=QuantumScale*(pixel.blue-mid.blue);
823 if (cube_info->associate_alpha != MagickFalse)
824 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
825 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
826 count*error.green*error.green+count*error.blue*error.blue+
827 count*error.opacity*error.opacity));
828 cube_info->root->quantize_error+=node_info->quantize_error;
832 Sum RGB for this leaf for later derivation of the mean cube color.
834 node_info->number_unique+=count;
835 node_info->total_color.red+=count*QuantumScale*pixel.red;
836 node_info->total_color.green+=count*QuantumScale*pixel.green;
837 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
838 if (cube_info->associate_alpha != MagickFalse)
839 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
842 if (cube_info->colors > cube_info->maximum_colors)
844 PruneToCubeDepth(image,cube_info,cube_info->root);
847 proceed=SetImageProgress(image,ClassifyImageTag,y,image->rows);
848 if (proceed == MagickFalse)
851 for (y++; y < (long) image->rows; y++)
853 register const PixelPacket
859 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
860 if (p == (const PixelPacket *) NULL)
862 if (cube_info->nodes > MaxNodes)
865 Prune one level if the color tree is too large.
867 PruneLevel(image,cube_info,cube_info->root);
870 for (x=0; x < (long) image->columns; x+=(long) count)
873 Start at the root and descend the color cube tree.
875 for (count=1; (x+count) < image->columns; count++)
876 if (IsSameColor(image,p,p+count) == MagickFalse)
878 AssociateAlphaPixel(cube_info,p,&pixel);
879 index=MaxTreeDepth-1;
880 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
882 node_info=cube_info->root;
883 for (level=1; level <= cube_info->depth; level++)
886 id=ColorToNodeId(cube_info,&pixel,index);
887 mid.red+=(id & 1) != 0 ? bisect : -bisect;
888 mid.green+=(id & 2) != 0 ? bisect : -bisect;
889 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
890 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
891 if (node_info->child[id] == (NodeInfo *) NULL)
894 Set colors of new node to contain pixel.
896 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
897 if (node_info->child[id] == (NodeInfo *) NULL)
898 (void) ThrowMagickException(exception,GetMagickModule(),
899 ResourceLimitError,"MemoryAllocationFailed","%s",
901 if (level == cube_info->depth)
905 Approximate the quantization error represented by this node.
907 node_info=node_info->child[id];
908 error.red=QuantumScale*(pixel.red-mid.red);
909 error.green=QuantumScale*(pixel.green-mid.green);
910 error.blue=QuantumScale*(pixel.blue-mid.blue);
911 if (cube_info->associate_alpha != MagickFalse)
912 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
913 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
914 count*error.green*error.green+error.blue*error.blue+
915 count*error.opacity*error.opacity));
916 cube_info->root->quantize_error+=node_info->quantize_error;
920 Sum RGB for this leaf for later derivation of the mean cube color.
922 node_info->number_unique+=count;
923 node_info->total_color.red+=count*QuantumScale*pixel.red;
924 node_info->total_color.green+=count*QuantumScale*pixel.green;
925 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
926 if (cube_info->associate_alpha != MagickFalse)
927 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
930 proceed=SetImageProgress(image,ClassifyImageTag,y,image->rows);
931 if (proceed == MagickFalse)
934 image_view=DestroyCacheView(image_view);
935 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
936 (cube_info->quantize_info->colorspace != CMYKColorspace))
937 (void) TransformImageColorspace((Image *) image,RGBColorspace);
942 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
946 % C l o n e Q u a n t i z e I n f o %
950 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
952 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
953 % or if quantize info is NULL, a new one.
955 % The format of the CloneQuantizeInfo method is:
957 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
959 % A description of each parameter follows:
961 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
962 % quantize info, or if image info is NULL a new one.
964 % o quantize_info: a structure of type info.
967 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
972 clone_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*clone_info));
973 if (clone_info == (QuantizeInfo *) NULL)
974 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
975 GetQuantizeInfo(clone_info);
976 if (quantize_info == (QuantizeInfo *) NULL)
978 clone_info->number_colors=quantize_info->number_colors;
979 clone_info->tree_depth=quantize_info->tree_depth;
980 clone_info->dither=quantize_info->dither;
981 clone_info->dither_method=quantize_info->dither_method;
982 clone_info->colorspace=quantize_info->colorspace;
983 clone_info->measure_error=quantize_info->measure_error;
988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
992 + C l o s e s t C o l o r %
996 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
998 % ClosestColor() traverses the color cube tree at a particular node and
999 % determines which colormap entry best represents the input color.
1001 % The format of the ClosestColor method is:
1003 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1004 % const NodeInfo *node_info)
1006 % A description of each parameter follows.
1008 % o image: the image.
1010 % o cube_info: A pointer to the Cube structure.
1012 % o node_info: the address of a structure of type NodeInfo which points to a
1013 % node in the color cube tree that is to be pruned.
1016 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1017 const NodeInfo *node_info)
1026 Traverse any children.
1028 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1029 for (i=0; i < (long) number_children; i++)
1030 if (node_info->child[i] != (NodeInfo *) NULL)
1031 ClosestColor(image,cube_info,node_info->child[i]);
1032 if (node_info->number_unique != 0)
1037 register MagickRealType
1042 register PixelPacket
1045 register RealPixelPacket
1049 Determine if this color is "closest".
1051 p=image->colormap+node_info->color_number;
1052 q=(&cube_info->target);
1055 if (cube_info->associate_alpha == MagickFalse)
1057 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1058 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1060 pixel=alpha*p->red-beta*q->red;
1061 distance=pixel*pixel;
1062 if (distance < cube_info->distance)
1064 pixel=alpha*p->green-beta*q->green;
1065 distance+=pixel*pixel;
1066 if (distance < cube_info->distance)
1068 pixel=alpha*p->blue-beta*q->blue;
1069 distance+=pixel*pixel;
1070 if (distance < cube_info->distance)
1073 distance+=pixel*pixel;
1074 if (distance < cube_info->distance)
1076 cube_info->distance=distance;
1077 cube_info->color_number=node_info->color_number;
1086 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1090 % C o m p r e s s I m a g e C o l o r m a p %
1094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1096 % CompressImageColormap() compresses an image colormap by removing any
1097 % duplicate or unused color entries.
1099 % The format of the CompressImageColormap method is:
1101 % MagickBooleanType CompressImageColormap(Image *image)
1103 % A description of each parameter follows:
1105 % o image: the image.
1108 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1113 assert(image != (Image *) NULL);
1114 assert(image->signature == MagickSignature);
1115 if (image->debug != MagickFalse)
1116 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1117 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1118 return(MagickFalse);
1119 GetQuantizeInfo(&quantize_info);
1120 quantize_info.number_colors=image->colors;
1121 quantize_info.tree_depth=MaxTreeDepth;
1122 return(QuantizeImage(&quantize_info,image));
1126 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1130 + D e f i n e I m a g e C o l o r m a p %
1134 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1136 % DefineImageColormap() traverses the color cube tree and notes each colormap
1137 % entry. A colormap entry is any node in the color cube tree where the
1138 % of unique colors is not zero. DefineImageColormap() returns the number of
1139 % colors in the image colormap.
1141 % The format of the DefineImageColormap method is:
1143 % unsigned long DefineImageColormap(Image *image,CubeInfo *cube_info,
1144 % NodeInfo *node_info)
1146 % A description of each parameter follows.
1148 % o image: the image.
1150 % o cube_info: A pointer to the Cube structure.
1152 % o node_info: the address of a structure of type NodeInfo which points to a
1153 % node in the color cube tree that is to be pruned.
1156 static unsigned long DefineImageColormap(Image *image,CubeInfo *cube_info,
1157 NodeInfo *node_info)
1166 Traverse any children.
1168 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1169 for (i=0; i < (long) number_children; i++)
1170 if (node_info->child[i] != (NodeInfo *) NULL)
1171 DefineImageColormap(image,cube_info,node_info->child[i]);
1172 if (node_info->number_unique != 0)
1174 register MagickRealType
1177 register PixelPacket
1181 Colormap entry is defined by the mean color in this cube.
1183 q=image->colormap+image->colors;
1184 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1185 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1186 if (cube_info->associate_alpha == MagickFalse)
1188 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1189 node_info->total_color.red));
1190 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1191 node_info->total_color.green));
1192 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1193 node_info->total_color.blue));
1194 SetOpacityPixelComponent(q,OpaqueOpacity);
1201 opacity=(MagickRealType) (alpha*QuantumRange*
1202 node_info->total_color.opacity);
1203 q->opacity=ClampToQuantum(opacity);
1204 if (q->opacity == OpaqueOpacity)
1206 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1207 node_info->total_color.red));
1208 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1209 node_info->total_color.green));
1210 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1211 node_info->total_color.blue));
1218 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1219 (MagickRealType) q->opacity));
1220 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1221 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1222 node_info->total_color.red));
1223 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1224 QuantumRange*node_info->total_color.green));
1225 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1226 node_info->total_color.blue));
1227 if (node_info->number_unique > cube_info->transparent_pixels)
1229 cube_info->transparent_pixels=node_info->number_unique;
1230 cube_info->transparent_index=(long) image->colors;
1234 node_info->color_number=image->colors++;
1236 return(image->colors);
1240 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1244 + D e s t r o y C u b e I n f o %
1248 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1250 % DestroyCubeInfo() deallocates memory associated with an image.
1252 % The format of the DestroyCubeInfo method is:
1254 % DestroyCubeInfo(CubeInfo *cube_info)
1256 % A description of each parameter follows:
1258 % o cube_info: the address of a structure of type CubeInfo.
1261 static void DestroyCubeInfo(CubeInfo *cube_info)
1267 Release color cube tree storage.
1271 nodes=cube_info->node_queue->next;
1272 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1273 cube_info->node_queue->nodes);
1274 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1275 cube_info->node_queue);
1276 cube_info->node_queue=nodes;
1277 } while (cube_info->node_queue != (Nodes *) NULL);
1278 if (cube_info->cache != (long *) NULL)
1279 cube_info->cache=(long *) RelinquishMagickMemory(cube_info->cache);
1280 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1281 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1285 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1289 % D e s t r o y Q u a n t i z e I n f o %
1293 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1295 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1298 % The format of the DestroyQuantizeInfo method is:
1300 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1302 % A description of each parameter follows:
1304 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1307 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1309 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1310 assert(quantize_info != (QuantizeInfo *) NULL);
1311 assert(quantize_info->signature == MagickSignature);
1312 quantize_info->signature=(~MagickSignature);
1313 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1314 return(quantize_info);
1318 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1322 + D i t h e r I m a g e %
1326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1328 % DitherImage() distributes the difference between an original image and
1329 % the corresponding color reduced algorithm to neighboring pixels using
1330 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1331 % MagickTrue if the image is dithered otherwise MagickFalse.
1333 % The format of the DitherImage method is:
1335 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1337 % A description of each parameter follows.
1339 % o image: the image.
1341 % o cube_info: A pointer to the Cube structure.
1345 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1347 #define DitherImageTag "Dither/Image"
1377 Distribute quantization error using Floyd-Steinberg.
1379 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1380 2*sizeof(*scanlines));
1381 if (scanlines == (RealPixelPacket *) NULL)
1382 return(MagickFalse);
1384 exception=(&image->exception);
1385 image_view=AcquireCacheView(image);
1386 for (y=0; y < (long) image->rows; y++)
1388 register IndexPacket
1395 register PixelPacket
1398 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1399 if (q == (PixelPacket *) NULL)
1400 return(MagickFalse);
1401 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1402 current=scanlines+(y & 0x01)*image->columns;
1403 previous=scanlines+((y+1) & 0x01)*image->columns;
1404 v=(y & 0x01) ? -1 : 1;
1405 for (x=0; x < (long) image->columns; x++)
1407 u=(y & 0x01) ? (long) image->columns-1-x : x;
1408 AssociateAlphaPixel(cube_info,q+u,&pixel);
1411 pixel.red+=7*current[u-v].red/16;
1412 pixel.green+=7*current[u-v].green/16;
1413 pixel.blue+=7*current[u-v].blue/16;
1414 if (cube_info->associate_alpha != MagickFalse)
1415 pixel.opacity+=7*current[u-v].opacity/16;
1419 if (x < (long) (image->columns-1))
1421 pixel.red+=previous[u+v].red/16;
1422 pixel.green+=previous[u+v].green/16;
1423 pixel.blue+=previous[u+v].blue/16;
1424 if (cube_info->associate_alpha != MagickFalse)
1425 pixel.opacity+=previous[u+v].opacity/16;
1427 pixel.red+=5*previous[u].red/16;
1428 pixel.green+=5*previous[u].green/16;
1429 pixel.blue+=5*previous[u].blue/16;
1430 if (cube_info->associate_alpha != MagickFalse)
1431 pixel.opacity+=5*previous[u].opacity/16;
1434 pixel.red+=3*previous[u-v].red/16;
1435 pixel.green+=3*previous[u-v].green/16;
1436 pixel.blue+=3*previous[u-v].blue/16;
1437 if (cube_info->associate_alpha != MagickFalse)
1438 pixel.opacity+=3*previous[u-v].opacity/16;
1441 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1442 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1443 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1444 if (cube_info->associate_alpha != MagickFalse)
1445 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1446 i=(long) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
1447 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1448 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
1449 if (cube_info->associate_alpha != MagickFalse)
1450 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
1452 if (p->cache[i] < 0)
1457 register unsigned long
1461 Identify the deepest node containing the pixel's color.
1464 for (index=MaxTreeDepth-1; (long) index > 0; index--)
1466 id=ColorToNodeId(cube_info,&pixel,index);
1467 if (node_info->child[id] == (NodeInfo *) NULL)
1469 node_info=node_info->child[id];
1472 Find closest color among siblings and their children.
1475 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1477 ClosestColor(image,p,node_info->parent);
1478 p->cache[i]=(long) p->color_number;
1481 Assign pixel to closest colormap entry.
1483 index=(unsigned long) p->cache[i];
1484 if (image->storage_class == PseudoClass)
1485 indexes[u]=(IndexPacket) index;
1486 if (cube_info->quantize_info->measure_error == MagickFalse)
1488 (q+u)->red=image->colormap[index].red;
1489 (q+u)->green=image->colormap[index].green;
1490 (q+u)->blue=image->colormap[index].blue;
1491 if (cube_info->associate_alpha != MagickFalse)
1492 (q+u)->opacity=image->colormap[index].opacity;
1494 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1495 return(MagickFalse);
1499 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1500 current[u].red=pixel.red-color.red;
1501 current[u].green=pixel.green-color.green;
1502 current[u].blue=pixel.blue-color.blue;
1503 if (cube_info->associate_alpha != MagickFalse)
1504 current[u].opacity=pixel.opacity-color.opacity;
1505 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1506 if (proceed == MagickFalse)
1507 return(MagickFalse);
1511 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1512 image_view=DestroyCacheView(image_view);
1516 static MagickBooleanType
1517 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1519 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1520 const unsigned long level,const unsigned int direction)
1527 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1528 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1529 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1534 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1535 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1536 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1541 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1542 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1543 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1548 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1549 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1550 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1561 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1562 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1563 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1564 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1565 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1566 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1567 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1572 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1573 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1574 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1575 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1576 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1577 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1578 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1583 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1584 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1585 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1586 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1587 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1588 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1589 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1594 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1595 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1596 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1597 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1598 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1599 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1600 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1608 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1609 CubeInfo *cube_info,const unsigned int direction)
1611 #define DitherImageTag "Dither/Image"
1627 if ((p->x >= 0) && (p->x < (long) image->columns) &&
1628 (p->y >= 0) && (p->y < (long) image->rows))
1633 register IndexPacket
1639 register PixelPacket
1645 exception=(&image->exception);
1646 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1647 if (q == (PixelPacket *) NULL)
1648 return(MagickFalse);
1649 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1650 AssociateAlphaPixel(cube_info,q,&pixel);
1651 for (i=0; i < ErrorQueueLength; i++)
1653 pixel.red+=p->weights[i]*p->error[i].red;
1654 pixel.green+=p->weights[i]*p->error[i].green;
1655 pixel.blue+=p->weights[i]*p->error[i].blue;
1656 if (cube_info->associate_alpha != MagickFalse)
1657 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1659 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1660 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1661 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1662 if (cube_info->associate_alpha != MagickFalse)
1663 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1664 i=(long) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
1665 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1666 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
1667 if (cube_info->associate_alpha != MagickFalse)
1668 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
1670 if (p->cache[i] < 0)
1675 register unsigned long
1679 Identify the deepest node containing the pixel's color.
1682 for (index=MaxTreeDepth-1; (long) index > 0; index--)
1684 id=ColorToNodeId(cube_info,&pixel,index);
1685 if (node_info->child[id] == (NodeInfo *) NULL)
1687 node_info=node_info->child[id];
1690 Find closest color among siblings and their children.
1693 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1694 QuantumRange+1.0)+1.0);
1695 ClosestColor(image,p,node_info->parent);
1696 p->cache[i]=(long) p->color_number;
1699 Assign pixel to closest colormap entry.
1701 index=(unsigned long) (1*p->cache[i]);
1702 if (image->storage_class == PseudoClass)
1703 *indexes=(IndexPacket) index;
1704 if (cube_info->quantize_info->measure_error == MagickFalse)
1706 q->red=image->colormap[index].red;
1707 q->green=image->colormap[index].green;
1708 q->blue=image->colormap[index].blue;
1709 if (cube_info->associate_alpha != MagickFalse)
1710 q->opacity=image->colormap[index].opacity;
1712 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1713 return(MagickFalse);
1715 Propagate the error as the last entry of the error queue.
1717 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1718 sizeof(p->error[0]));
1719 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1720 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1721 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1722 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1723 if (cube_info->associate_alpha != MagickFalse)
1724 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1725 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1726 if (proceed == MagickFalse)
1727 return(MagickFalse);
1732 case WestGravity: p->x--; break;
1733 case EastGravity: p->x++; break;
1734 case NorthGravity: p->y--; break;
1735 case SouthGravity: p->y++; break;
1740 static inline long MagickMax(const long x,const long y)
1747 static inline long MagickMin(const long x,const long y)
1754 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1768 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1769 return(FloydSteinbergDither(image,cube_info));
1771 Distribute quantization error along a Hilbert curve.
1773 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1774 sizeof(*cube_info->error));
1777 i=MagickMax((long) image->columns,(long) image->rows);
1778 for (depth=1; i != 0; depth++)
1780 if ((long) (1L << depth) < MagickMax((long) image->columns,(long) image->rows))
1782 cube_info->offset=0;
1783 cube_info->span=(MagickSizeType) image->columns*image->rows;
1784 image_view=AcquireCacheView(image);
1786 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1787 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1788 image_view=DestroyCacheView(image_view);
1793 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1797 + G e t C u b e I n f o %
1801 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1803 % GetCubeInfo() initialize the Cube data structure.
1805 % The format of the GetCubeInfo method is:
1807 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1808 % const unsigned long depth,const unsigned long maximum_colors)
1810 % A description of each parameter follows.
1812 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1814 % o depth: Normally, this integer value is zero or one. A zero or
1815 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1816 % A tree of this depth generally allows the best representation of the
1817 % reference image with the least amount of memory and the fastest
1818 % computational speed. In some cases, such as an image with low color
1819 % dispersion (a few number of colors), a value other than
1820 % Log4(number_colors) is required. To expand the color tree completely,
1823 % o maximum_colors: maximum colors.
1826 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1827 const unsigned long depth,const unsigned long maximum_colors)
1843 Initialize tree to describe color cube_info.
1845 cube_info=(CubeInfo *) AcquireAlignedMemory(1,sizeof(*cube_info));
1846 if (cube_info == (CubeInfo *) NULL)
1847 return((CubeInfo *) NULL);
1848 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1849 cube_info->depth=depth;
1850 if (cube_info->depth > MaxTreeDepth)
1851 cube_info->depth=MaxTreeDepth;
1852 if (cube_info->depth < 2)
1854 cube_info->maximum_colors=maximum_colors;
1856 Initialize root node.
1858 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1859 if (cube_info->root == (NodeInfo *) NULL)
1860 return((CubeInfo *) NULL);
1861 cube_info->root->parent=cube_info->root;
1862 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1863 if (cube_info->quantize_info->dither == MagickFalse)
1866 Initialize dither resources.
1868 length=(size_t) (1UL << (4*(8-CacheShift)));
1869 cube_info->cache=(long *) AcquireQuantumMemory(length,
1870 sizeof(*cube_info->cache));
1871 if (cube_info->cache == (long *) NULL)
1872 return((CubeInfo *) NULL);
1874 Initialize color cache.
1876 for (i=0; i < (long) length; i++)
1877 cube_info->cache[i]=(-1);
1879 Distribute weights along a curve of exponential decay.
1882 for (i=0; i < ErrorQueueLength; i++)
1884 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1885 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1888 Normalize the weighting factors.
1891 for (i=0; i < ErrorQueueLength; i++)
1892 weight+=cube_info->weights[i];
1894 for (i=0; i < ErrorQueueLength; i++)
1896 cube_info->weights[i]/=weight;
1897 sum+=cube_info->weights[i];
1899 cube_info->weights[0]+=1.0-sum;
1904 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1908 + G e t N o d e I n f o %
1912 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1914 % GetNodeInfo() allocates memory for a new node in the color cube tree and
1915 % presets all fields to zero.
1917 % The format of the GetNodeInfo method is:
1919 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const unsigned long id,
1920 % const unsigned long level,NodeInfo *parent)
1922 % A description of each parameter follows.
1924 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1926 % o id: Specifies the child number of the node.
1928 % o level: Specifies the level in the storage_class the node resides.
1931 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const unsigned long id,
1932 const unsigned long level,NodeInfo *parent)
1937 if (cube_info->free_nodes == 0)
1943 Allocate a new queue of nodes.
1945 nodes=(Nodes *) AcquireAlignedMemory(1,sizeof(*nodes));
1946 if (nodes == (Nodes *) NULL)
1947 return((NodeInfo *) NULL);
1948 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1949 sizeof(*nodes->nodes));
1950 if (nodes->nodes == (NodeInfo *) NULL)
1951 return((NodeInfo *) NULL);
1952 nodes->next=cube_info->node_queue;
1953 cube_info->node_queue=nodes;
1954 cube_info->next_node=nodes->nodes;
1955 cube_info->free_nodes=NodesInAList;
1958 cube_info->free_nodes--;
1959 node_info=cube_info->next_node++;
1960 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1961 node_info->parent=parent;
1963 node_info->level=level;
1968 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1972 % G e t I m a g e Q u a n t i z e E r r o r %
1976 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1978 % GetImageQuantizeError() measures the difference between the original
1979 % and quantized images. This difference is the total quantization error.
1980 % The error is computed by summing over all pixels in an image the distance
1981 % squared in RGB space between each reference pixel value and its quantized
1982 % value. These values are computed:
1984 % o mean_error_per_pixel: This value is the mean error for any single
1985 % pixel in the image.
1987 % o normalized_mean_square_error: This value is the normalized mean
1988 % quantization error for any single pixel in the image. This distance
1989 % measure is normalized to a range between 0 and 1. It is independent
1990 % of the range of red, green, and blue values in the image.
1992 % o normalized_maximum_square_error: Thsi value is the normalized
1993 % maximum quantization error for any single pixel in the image. This
1994 % distance measure is normalized to a range between 0 and 1. It is
1995 % independent of the range of red, green, and blue values in your image.
1997 % The format of the GetImageQuantizeError method is:
1999 % MagickBooleanType GetImageQuantizeError(Image *image)
2001 % A description of each parameter follows.
2003 % o image: the image.
2006 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2027 mean_error_per_pixel;
2032 assert(image != (Image *) NULL);
2033 assert(image->signature == MagickSignature);
2034 if (image->debug != MagickFalse)
2035 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2036 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2037 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2038 if (image->storage_class == DirectClass)
2042 area=3.0*image->columns*image->rows;
2044 mean_error_per_pixel=0.0;
2046 exception=(&image->exception);
2047 image_view=AcquireCacheView(image);
2048 for (y=0; y < (long) image->rows; y++)
2050 register const PixelPacket
2056 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2057 if (p == (const PixelPacket *) NULL)
2059 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2060 for (x=0; x < (long) image->columns; x++)
2062 index=1UL*indexes[x];
2063 if (image->matte != MagickFalse)
2065 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2066 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2067 image->colormap[index].opacity));
2069 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2070 mean_error_per_pixel+=distance;
2071 mean_error+=distance*distance;
2072 if (distance > maximum_error)
2073 maximum_error=distance;
2074 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2075 mean_error_per_pixel+=distance;
2076 mean_error+=distance*distance;
2077 if (distance > maximum_error)
2078 maximum_error=distance;
2079 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2080 mean_error_per_pixel+=distance;
2081 mean_error+=distance*distance;
2082 if (distance > maximum_error)
2083 maximum_error=distance;
2087 image_view=DestroyCacheView(image_view);
2088 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2089 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2091 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2096 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2100 % G e t Q u a n t i z e I n f o %
2104 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2106 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2108 % The format of the GetQuantizeInfo method is:
2110 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2112 % A description of each parameter follows:
2114 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2117 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2119 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2120 assert(quantize_info != (QuantizeInfo *) NULL);
2121 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2122 quantize_info->number_colors=256;
2123 quantize_info->dither=MagickTrue;
2124 quantize_info->dither_method=RiemersmaDitherMethod;
2125 quantize_info->colorspace=UndefinedColorspace;
2126 quantize_info->measure_error=MagickFalse;
2127 quantize_info->signature=MagickSignature;
2131 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2135 % P o s t e r i z e I m a g e %
2139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2141 % PosterizeImage() reduces the image to a limited number of colors for a
2144 % The format of the PosterizeImage method is:
2146 % MagickBooleanType PosterizeImage(Image *image,const unsigned long levels,
2147 % const MagickBooleanType dither)
2149 % A description of each parameter follows:
2151 % o image: Specifies a pointer to an Image structure.
2153 % o levels: Number of color levels allowed in each channel. Very low values
2154 % (2, 3, or 4) have the most visible effect.
2156 % o dither: Set this integer value to something other than zero to
2157 % dither the mapped image.
2160 MagickExport MagickBooleanType PosterizeImage(Image *image,
2161 const unsigned long levels,const MagickBooleanType dither)
2190 register PixelPacket
2196 assert(image != (Image *) NULL);
2197 assert(image->signature == MagickSignature);
2198 if (image->debug != MagickFalse)
2199 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2200 posterize_image=AcquireImage((ImageInfo *) NULL);
2201 if (posterize_image == (Image *) NULL)
2202 return(MagickFalse);
2204 while ((l*l*l) < (long) MagickMin((long) levels*levels*levels,MaxColormapSize+1))
2206 status=SetImageExtent(posterize_image,(unsigned long) (l*l*l),1);
2207 if (status == MagickFalse)
2209 posterize_image=DestroyImage(posterize_image);
2210 return(MagickFalse);
2212 status=AcquireImageColormap(posterize_image,levels*levels*levels);
2213 if (status == MagickFalse)
2215 posterize_image=DestroyImage(posterize_image);
2216 return(MagickFalse);
2218 posterize_view=AcquireCacheView(posterize_image);
2219 exception=(&image->exception);
2220 q=QueueCacheViewAuthenticPixels(posterize_view,0,0,posterize_image->columns,1,
2222 if (q == (PixelPacket *) NULL)
2224 posterize_view=DestroyCacheView(posterize_view);
2225 posterize_image=DestroyImage(posterize_image);
2226 return(MagickFalse);
2228 indexes=GetCacheViewAuthenticIndexQueue(posterize_view);
2230 for (i=0; i < l; i++)
2231 for (j=0; j < l; j++)
2232 for (k=0; k < l; k++)
2234 posterize_image->colormap[n].red=(Quantum) (QuantumRange*i/
2235 MagickMax(l-1L,1L));
2236 posterize_image->colormap[n].green=(Quantum)
2237 (QuantumRange*j/MagickMax(l-1L,1L));
2238 posterize_image->colormap[n].blue=(Quantum) (QuantumRange*k/
2239 MagickMax(l-1L,1L));
2240 posterize_image->colormap[n].opacity=OpaqueOpacity;
2241 *q++=posterize_image->colormap[n];
2242 indexes[n]=(IndexPacket) n;
2245 if (SyncCacheViewAuthenticPixels(posterize_view,exception) == MagickFalse)
2247 posterize_view=DestroyCacheView(posterize_view);
2248 posterize_image=DestroyImage(posterize_image);
2249 return(MagickFalse);
2251 posterize_view=DestroyCacheView(posterize_view);
2252 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2253 quantize_info->dither=dither;
2254 status=RemapImage(quantize_info,image,posterize_image);
2255 quantize_info=DestroyQuantizeInfo(quantize_info);
2256 posterize_image=DestroyImage(posterize_image);
2261 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2265 + P r u n e C h i l d %
2269 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2271 % PruneChild() deletes the given node and merges its statistics into its
2274 % The format of the PruneSubtree method is:
2276 % PruneChild(const Image *image,CubeInfo *cube_info,
2277 % const NodeInfo *node_info)
2279 % A description of each parameter follows.
2281 % o image: the image.
2283 % o cube_info: A pointer to the Cube structure.
2285 % o node_info: pointer to node in color cube tree that is to be pruned.
2288 static void PruneChild(const Image *image,CubeInfo *cube_info,
2289 const NodeInfo *node_info)
2301 Traverse any children.
2303 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2304 for (i=0; i < (long) number_children; i++)
2305 if (node_info->child[i] != (NodeInfo *) NULL)
2306 PruneChild(image,cube_info,node_info->child[i]);
2308 Merge color statistics into parent.
2310 parent=node_info->parent;
2311 parent->number_unique+=node_info->number_unique;
2312 parent->total_color.red+=node_info->total_color.red;
2313 parent->total_color.green+=node_info->total_color.green;
2314 parent->total_color.blue+=node_info->total_color.blue;
2315 parent->total_color.opacity+=node_info->total_color.opacity;
2316 parent->child[node_info->id]=(NodeInfo *) NULL;
2321 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2325 + P r u n e L e v e l %
2329 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2331 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2332 % their color statistics into their parent node.
2334 % The format of the PruneLevel method is:
2336 % PruneLevel(const Image *image,CubeInfo *cube_info,
2337 % const NodeInfo *node_info)
2339 % A description of each parameter follows.
2341 % o image: the image.
2343 % o cube_info: A pointer to the Cube structure.
2345 % o node_info: pointer to node in color cube tree that is to be pruned.
2348 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2349 const NodeInfo *node_info)
2358 Traverse any children.
2360 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2361 for (i=0; i < (long) number_children; i++)
2362 if (node_info->child[i] != (NodeInfo *) NULL)
2363 PruneLevel(image,cube_info,node_info->child[i]);
2364 if (node_info->level == cube_info->depth)
2365 PruneChild(image,cube_info,node_info);
2369 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2373 + P r u n e T o C u b e D e p t h %
2377 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2379 % PruneToCubeDepth() deletes any nodes at a depth greater than
2380 % cube_info->depth while merging their color statistics into their parent
2383 % The format of the PruneToCubeDepth method is:
2385 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2386 % const NodeInfo *node_info)
2388 % A description of each parameter follows.
2390 % o cube_info: A pointer to the Cube structure.
2392 % o node_info: pointer to node in color cube tree that is to be pruned.
2395 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2396 const NodeInfo *node_info)
2405 Traverse any children.
2407 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2408 for (i=0; i < (long) number_children; i++)
2409 if (node_info->child[i] != (NodeInfo *) NULL)
2410 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2411 if (node_info->level > cube_info->depth)
2412 PruneChild(image,cube_info,node_info);
2416 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2420 % Q u a n t i z e I m a g e %
2424 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2426 % QuantizeImage() analyzes the colors within a reference image and chooses a
2427 % fixed number of colors to represent the image. The goal of the algorithm
2428 % is to minimize the color difference between the input and output image while
2429 % minimizing the processing time.
2431 % The format of the QuantizeImage method is:
2433 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2436 % A description of each parameter follows:
2438 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2440 % o image: the image.
2443 static MagickBooleanType DirectToColormapImage(Image *image,
2444 ExceptionInfo *exception)
2462 number_colors=(unsigned long) (image->columns*image->rows);
2463 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2464 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2467 image_view=AcquireCacheView(image);
2468 for (y=0; y < (long) image->rows; y++)
2470 register const PixelPacket
2476 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2477 if (p == (const PixelPacket *) NULL)
2479 for (x=0; x < (long) image->columns; x++)
2480 image->colormap[i++]=(*p++);
2482 image_view=DestroyCacheView(image_view);
2486 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2499 assert(quantize_info != (const QuantizeInfo *) NULL);
2500 assert(quantize_info->signature == MagickSignature);
2501 assert(image != (Image *) NULL);
2502 assert(image->signature == MagickSignature);
2503 if (image->debug != MagickFalse)
2504 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2505 maximum_colors=quantize_info->number_colors;
2506 if (maximum_colors == 0)
2507 maximum_colors=MaxColormapSize;
2508 if (maximum_colors > MaxColormapSize)
2509 maximum_colors=MaxColormapSize;
2510 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2511 (image->matte == MagickFalse))
2512 (void) SetGrayscaleImage(image);
2513 if ((image->storage_class == PseudoClass) &&
2514 (image->colors <= maximum_colors))
2516 if ((image->columns*image->rows) <= maximum_colors)
2517 return(DirectToColormapImage(image,&image->exception));
2518 depth=quantize_info->tree_depth;
2525 Depth of color tree is: Log4(colormap size)+2.
2527 colors=maximum_colors;
2528 for (depth=1; colors != 0; depth++)
2530 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2532 if ((image->matte != MagickFalse) && (depth > 5))
2536 Initialize color cube.
2538 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2539 if (cube_info == (CubeInfo *) NULL)
2540 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2542 status=ClassifyImageColors(cube_info,image,&image->exception);
2543 if (status != MagickFalse)
2546 Reduce the number of colors in the image.
2548 ReduceImageColors(image,cube_info);
2549 status=AssignImageColors(image,cube_info);
2551 DestroyCubeInfo(cube_info);
2556 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2560 % Q u a n t i z e I m a g e s %
2564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2566 % QuantizeImages() analyzes the colors within a set of reference images and
2567 % chooses a fixed number of colors to represent the set. The goal of the
2568 % algorithm is to minimize the color difference between the input and output
2569 % images while minimizing the processing time.
2571 % The format of the QuantizeImages method is:
2573 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2576 % A description of each parameter follows:
2578 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2580 % o images: Specifies a pointer to a list of Image structures.
2583 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2596 MagickProgressMonitor
2607 assert(quantize_info != (const QuantizeInfo *) NULL);
2608 assert(quantize_info->signature == MagickSignature);
2609 assert(images != (Image *) NULL);
2610 assert(images->signature == MagickSignature);
2611 if (images->debug != MagickFalse)
2612 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2613 if (GetNextImageInList(images) == (Image *) NULL)
2616 Handle a single image with QuantizeImage.
2618 status=QuantizeImage(quantize_info,images);
2622 maximum_colors=quantize_info->number_colors;
2623 if (maximum_colors == 0)
2624 maximum_colors=MaxColormapSize;
2625 if (maximum_colors > MaxColormapSize)
2626 maximum_colors=MaxColormapSize;
2627 depth=quantize_info->tree_depth;
2634 Depth of color tree is: Log4(colormap size)+2.
2636 colors=maximum_colors;
2637 for (depth=1; colors != 0; depth++)
2639 if (quantize_info->dither != MagickFalse)
2643 Initialize color cube.
2645 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2646 if (cube_info == (CubeInfo *) NULL)
2648 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2649 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2650 return(MagickFalse);
2652 number_images=GetImageListLength(images);
2654 for (i=0; image != (Image *) NULL; i++)
2656 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2657 image->client_data);
2658 status=ClassifyImageColors(cube_info,image,&image->exception);
2659 if (status == MagickFalse)
2661 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2662 proceed=SetImageProgress(image,AssignImageTag,i,number_images);
2663 if (proceed == MagickFalse)
2665 image=GetNextImageInList(image);
2667 if (status != MagickFalse)
2670 Reduce the number of colors in an image sequence.
2672 ReduceImageColors(images,cube_info);
2674 for (i=0; image != (Image *) NULL; i++)
2676 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2677 NULL,image->client_data);
2678 status=AssignImageColors(image,cube_info);
2679 if (status == MagickFalse)
2681 (void) SetImageProgressMonitor(image,progress_monitor,
2682 image->client_data);
2683 proceed=SetImageProgress(image,AssignImageTag,i,number_images);
2684 if (proceed == MagickFalse)
2686 image=GetNextImageInList(image);
2689 DestroyCubeInfo(cube_info);
2694 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2702 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2704 % Reduce() traverses the color cube tree and prunes any node whose
2705 % quantization error falls below a particular threshold.
2707 % The format of the Reduce method is:
2709 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2711 % A description of each parameter follows.
2713 % o image: the image.
2715 % o cube_info: A pointer to the Cube structure.
2717 % o node_info: pointer to node in color cube tree that is to be pruned.
2720 static void Reduce(const Image *image,CubeInfo *cube_info,
2721 const NodeInfo *node_info)
2730 Traverse any children.
2732 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2733 for (i=0; i < (long) number_children; i++)
2734 if (node_info->child[i] != (NodeInfo *) NULL)
2735 Reduce(image,cube_info,node_info->child[i]);
2736 if (node_info->quantize_error <= cube_info->pruning_threshold)
2737 PruneChild(image,cube_info,node_info);
2741 Find minimum pruning threshold.
2743 if (node_info->number_unique > 0)
2744 cube_info->colors++;
2745 if (node_info->quantize_error < cube_info->next_threshold)
2746 cube_info->next_threshold=node_info->quantize_error;
2751 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2755 + R e d u c e I m a g e C o l o r s %
2759 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2761 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2762 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2763 % in the output image. On any given iteration over the tree, it selects
2764 % those nodes whose E value is minimal for pruning and merges their
2765 % color statistics upward. It uses a pruning threshold, Ep, to govern
2766 % node selection as follows:
2769 % while number of nodes with (n2 > 0) > required maximum number of colors
2770 % prune all nodes such that E <= Ep
2771 % Set Ep to minimum E in remaining nodes
2773 % This has the effect of minimizing any quantization error when merging
2774 % two nodes together.
2776 % When a node to be pruned has offspring, the pruning procedure invokes
2777 % itself recursively in order to prune the tree from the leaves upward.
2778 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2779 % corresponding data in that node's parent. This retains the pruned
2780 % node's color characteristics for later averaging.
2782 % For each node, n2 pixels exist for which that node represents the
2783 % smallest volume in RGB space containing those pixel's colors. When n2
2784 % > 0 the node will uniquely define a color in the output image. At the
2785 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2786 % the tree which represent colors present in the input image.
2788 % The other pixel count, n1, indicates the total number of colors
2789 % within the cubic volume which the node represents. This includes n1 -
2790 % n2 pixels whose colors should be defined by nodes at a lower level in
2793 % The format of the ReduceImageColors method is:
2795 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2797 % A description of each parameter follows.
2799 % o image: the image.
2801 % o cube_info: A pointer to the Cube structure.
2804 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2806 #define ReduceImageTag "Reduce/Image"
2817 cube_info->next_threshold=0.0;
2818 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2820 cube_info->pruning_threshold=cube_info->next_threshold;
2821 cube_info->next_threshold=cube_info->root->quantize_error-1;
2822 cube_info->colors=0;
2823 Reduce(image,cube_info,cube_info->root);
2824 offset=(MagickOffsetType) span-cube_info->colors;
2825 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2826 cube_info->maximum_colors+1);
2827 if (proceed == MagickFalse)
2833 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2837 % R e m a p I m a g e %
2841 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2843 % RemapImage() replaces the colors of an image with the closest color from
2844 % a reference image.
2846 % The format of the RemapImage method is:
2848 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2849 % Image *image,const Image *remap_image)
2851 % A description of each parameter follows:
2853 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2855 % o image: the image.
2857 % o remap_image: the reference image.
2860 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2861 Image *image,const Image *remap_image)
2870 Initialize color cube.
2872 assert(image != (Image *) NULL);
2873 assert(image->signature == MagickSignature);
2874 if (image->debug != MagickFalse)
2875 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2876 assert(remap_image != (Image *) NULL);
2877 assert(remap_image->signature == MagickSignature);
2878 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2879 quantize_info->number_colors);
2880 if (cube_info == (CubeInfo *) NULL)
2881 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2883 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2884 if (status != MagickFalse)
2887 Classify image colors from the reference image.
2889 cube_info->quantize_info->number_colors=cube_info->colors;
2890 status=AssignImageColors(image,cube_info);
2892 DestroyCubeInfo(cube_info);
2897 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2901 % R e m a p I m a g e s %
2905 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2907 % RemapImages() replaces the colors of a sequence of images with the
2908 % closest color from a reference image.
2910 % The format of the RemapImage method is:
2912 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2913 % Image *images,Image *remap_image)
2915 % A description of each parameter follows:
2917 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2919 % o images: the image sequence.
2921 % o remap_image: the reference image.
2924 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2925 Image *images,const Image *remap_image)
2936 assert(images != (Image *) NULL);
2937 assert(images->signature == MagickSignature);
2938 if (images->debug != MagickFalse)
2939 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2941 if (remap_image == (Image *) NULL)
2944 Create a global colormap for an image sequence.
2946 status=QuantizeImages(quantize_info,images);
2950 Classify image colors from the reference image.
2952 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2953 quantize_info->number_colors);
2954 if (cube_info == (CubeInfo *) NULL)
2955 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2957 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2958 if (status != MagickFalse)
2961 Classify image colors from the reference image.
2963 cube_info->quantize_info->number_colors=cube_info->colors;
2965 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
2967 status=AssignImageColors(image,cube_info);
2968 if (status == MagickFalse)
2972 DestroyCubeInfo(cube_info);
2977 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2981 % S e t G r a y s c a l e I m a g e %
2985 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2987 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
2989 % The format of the SetGrayscaleImage method is:
2991 % MagickBooleanType SetGrayscaleImage(Image *image)
2993 % A description of each parameter follows:
2995 % o image: The image.
2999 #if defined(__cplusplus) || defined(c_plusplus)
3003 static int IntensityCompare(const void *x,const void *y)
3012 color_1=(PixelPacket *) x;
3013 color_2=(PixelPacket *) y;
3014 intensity=PixelIntensityToQuantum(color_1)-(long)
3015 PixelIntensityToQuantum(color_2);
3019 #if defined(__cplusplus) || defined(c_plusplus)
3023 static MagickBooleanType SetGrayscaleImage(Image *image)
3047 assert(image != (Image *) NULL);
3048 assert(image->signature == MagickSignature);
3049 if (image->type != GrayscaleType)
3050 (void) TransformImageColorspace(image,GRAYColorspace);
3051 colormap_index=(long *) AcquireQuantumMemory(MaxMap+1,
3052 sizeof(*colormap_index));
3053 if (colormap_index == (long *) NULL)
3054 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3056 if (image->storage_class != PseudoClass)
3061 for (i=0; i <= (long) MaxMap; i++)
3062 colormap_index[i]=(-1);
3063 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3064 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3068 exception=(&image->exception);
3069 image_view=AcquireCacheView(image);
3070 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3071 #pragma omp parallel for schedule(dynamic,4) shared(status)
3073 for (y=0; y < (long) image->rows; y++)
3075 register IndexPacket
3081 register const PixelPacket
3084 if (status == MagickFalse)
3086 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3088 if (q == (PixelPacket *) NULL)
3093 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3094 for (x=0; x < (long) image->columns; x++)
3096 register unsigned long
3099 intensity=ScaleQuantumToMap(q->red);
3100 if (colormap_index[intensity] < 0)
3102 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3103 #pragma omp critical (MagickCore_SetGrayscaleImage)
3105 if (colormap_index[intensity] < 0)
3107 colormap_index[intensity]=(long) image->colors;
3108 image->colormap[image->colors]=(*q);
3112 indexes[x]=(IndexPacket) colormap_index[intensity];
3115 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3118 image_view=DestroyCacheView(image_view);
3120 for (i=0; i < (long) image->colors; i++)
3121 image->colormap[i].opacity=(unsigned short) i;
3122 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3124 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3126 if (colormap == (PixelPacket *) NULL)
3127 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3130 colormap[j]=image->colormap[0];
3131 for (i=0; i < (long) image->colors; i++)
3133 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3136 colormap[j]=image->colormap[i];
3138 colormap_index[(long) image->colormap[i].opacity]=j;
3140 image->colors=(unsigned long) (j+1);
3141 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3142 image->colormap=colormap;
3144 exception=(&image->exception);
3145 image_view=AcquireCacheView(image);
3146 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3147 #pragma omp parallel for schedule(dynamic,4) shared(status)
3149 for (y=0; y < (long) image->rows; y++)
3151 register IndexPacket
3157 register const PixelPacket
3160 if (status == MagickFalse)
3162 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3163 if (q == (PixelPacket *) NULL)
3168 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3169 for (x=0; x < (long) image->columns; x++)
3170 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3171 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3174 image_view=DestroyCacheView(image_view);
3175 colormap_index=(long *) RelinquishMagickMemory(colormap_index);
3176 image->type=GrayscaleType;
3177 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3178 image->type=BilevelType;