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-2018 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 % https://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 (vertex
65 % nearest the origin in RGB space and the vertex farthest from the origin).
67 % The tree's root node represents the entire domain, (0,0,0) through
68 % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
69 % subdividing one node's cube into eight smaller cubes of equal size.
70 % This corresponds to bisecting the parent cube with planes passing
71 % through the midpoints of each edge.
73 % The basic algorithm operates in three phases: Classification,
74 % Reduction, and Assignment. Classification builds a color description
75 % tree for the image. Reduction collapses the tree until the number it
76 % represents, at most, the number of colors desired in the output image.
77 % Assignment defines the output image's color map and sets each pixel's
78 % color by restorage_class in the reduced tree. Our goal is to minimize
79 % the numerical discrepancies between the original colors and quantized
80 % colors (quantization error).
82 % Classification begins by initializing a color description tree of
83 % sufficient depth to represent each possible input color in a leaf.
84 % However, it is impractical to generate a fully-formed color description
85 % tree in the storage_class phase for realistic values of Cmax. If
86 % colors components in the input image are quantized to k-bit precision,
87 % so that Cmax= 2k-1, the tree would need k levels below the root node to
88 % allow representing each possible input color in a leaf. This becomes
89 % prohibitive because the tree's total number of nodes is 1 +
92 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
93 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
94 % Initializes data structures for nodes only as they are needed; (2)
95 % Chooses a maximum depth for the tree as a function of the desired
96 % number of colors in the output image (currently log2(colormap size)).
98 % For each pixel in the input image, storage_class scans downward from
99 % the root of the color description tree. At each level of the tree it
100 % identifies the single node which represents a cube in RGB space
101 % containing the pixel's color. It updates the following data for each
104 % n1: Number of pixels whose color is contained in the RGB cube which
105 % this node represents;
107 % n2: Number of pixels whose color is not represented in a node at
108 % lower depth in the tree; initially, n2 = 0 for all nodes except
109 % leaves of the tree.
111 % Sr, Sg, Sb: Sums of the red, green, and blue component values for all
112 % pixels not classified at a lower depth. The combination of these sums
113 % and n2 will ultimately characterize the mean color of a set of pixels
114 % represented by this node.
116 % E: the distance squared in RGB space between each pixel contained
117 % within a node and the nodes' center. This represents the
118 % quantization error for a node.
120 % Reduction repeatedly prunes the tree until the number of nodes with n2
121 % > 0 is less than or equal to the maximum number of colors allowed in
122 % the output image. On any given iteration over the tree, it selects
123 % those nodes whose E count is minimal for pruning and merges their color
124 % statistics upward. It uses a pruning threshold, Ep, to govern node
125 % selection as follows:
128 % while number of nodes with (n2 > 0) > required maximum number of colors
129 % prune all nodes such that E <= Ep
130 % Set Ep to minimum E in remaining nodes
132 % This has the effect of minimizing any quantization error when merging
133 % two nodes together.
135 % When a node to be pruned has offspring, the pruning procedure invokes
136 % itself recursively in order to prune the tree from the leaves upward.
137 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
138 % corresponding data in that node's parent. This retains the pruned
139 % node's color characteristics for later averaging.
141 % For each node, n2 pixels exist for which that node represents the
142 % smallest volume in RGB space containing those pixel's colors. When n2
143 % > 0 the node will uniquely define a color in the output image. At the
144 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
145 % the tree which represent colors present in the input image.
147 % The other pixel count, n1, indicates the total number of colors within
148 % the cubic volume which the node represents. This includes n1 - n2
149 % pixels whose colors should be defined by nodes at a lower level in the
152 % Assignment generates the output image from the pruned tree. The output
153 % image consists of two parts: (1) A color map, which is an array of
154 % color descriptions (RGB triples) for each color present in the output
155 % image; (2) A pixel array, which represents each pixel as an index
156 % into the color map array.
158 % First, the assignment phase makes one pass over the pruned color
159 % description tree to establish the image's color map. For each node
160 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
161 % color of all pixels that classify no lower than this node. Each of
162 % these colors becomes an entry in the color map.
164 % Finally, the assignment phase reclassifies each pixel in the pruned
165 % tree to identify the deepest node containing the pixel's color. The
166 % pixel's value in the pixel array becomes the index of this node's mean
167 % color in the color map.
169 % This method is based on a similar algorithm written by Paul Raveling.
174 Include declarations.
176 #include "MagickCore/studio.h"
177 #include "MagickCore/attribute.h"
178 #include "MagickCore/cache-view.h"
179 #include "MagickCore/color.h"
180 #include "MagickCore/color-private.h"
181 #include "MagickCore/colormap.h"
182 #include "MagickCore/colorspace.h"
183 #include "MagickCore/colorspace-private.h"
184 #include "MagickCore/enhance.h"
185 #include "MagickCore/exception.h"
186 #include "MagickCore/exception-private.h"
187 #include "MagickCore/histogram.h"
188 #include "MagickCore/image.h"
189 #include "MagickCore/image-private.h"
190 #include "MagickCore/list.h"
191 #include "MagickCore/memory_.h"
192 #include "MagickCore/memory-private.h"
193 #include "MagickCore/monitor.h"
194 #include "MagickCore/monitor-private.h"
195 #include "MagickCore/option.h"
196 #include "MagickCore/pixel-accessor.h"
197 #include "MagickCore/pixel-private.h"
198 #include "MagickCore/quantize.h"
199 #include "MagickCore/quantum.h"
200 #include "MagickCore/quantum-private.h"
201 #include "MagickCore/resource_.h"
202 #include "MagickCore/string_.h"
203 #include "MagickCore/thread-private.h"
208 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
213 #define ErrorQueueLength 16
214 #define MaxNodes 266817
215 #define MaxTreeDepth 8
216 #define NodesInAList 1920
221 typedef struct _DoublePixelPacket
230 typedef struct _NodeInfo
251 typedef struct _Nodes
260 typedef struct _CubeInfo
301 error[ErrorQueueLength];
304 weights[ErrorQueueLength];
330 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
333 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
335 static MagickBooleanType
336 AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
337 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
338 DitherImage(Image *,CubeInfo *,ExceptionInfo *),
339 SetGrayscaleImage(Image *,ExceptionInfo *);
342 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
345 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
346 DestroyCubeInfo(CubeInfo *),
347 PruneLevel(CubeInfo *,const NodeInfo *),
348 PruneToCubeDepth(CubeInfo *,const NodeInfo *),
349 ReduceImageColors(const Image *,CubeInfo *);
352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
356 % A c q u i r e Q u a n t i z e I n f o %
360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
362 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
364 % The format of the AcquireQuantizeInfo method is:
366 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
368 % A description of each parameter follows:
370 % o image_info: the image info.
373 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
378 quantize_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*quantize_info));
379 GetQuantizeInfo(quantize_info);
380 if (image_info != (ImageInfo *) NULL)
385 quantize_info->dither_method=image_info->dither == MagickFalse ?
386 NoDitherMethod : RiemersmaDitherMethod;
387 option=GetImageOption(image_info,"dither");
388 if (option != (const char *) NULL)
389 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
390 MagickDitherOptions,MagickFalse,option);
391 quantize_info->measure_error=image_info->verbose;
393 return(quantize_info);
397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
401 + A s s i g n I m a g e C o l o r s %
405 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
407 % AssignImageColors() generates the output image from the pruned tree. The
408 % output image consists of two parts: (1) A color map, which is an array
409 % of color descriptions (RGB triples) for each color present in the
410 % output image; (2) A pixel array, which represents each pixel as an
411 % index into the color map array.
413 % First, the assignment phase makes one pass over the pruned color
414 % description tree to establish the image's color map. For each node
415 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
416 % color of all pixels that classify no lower than this node. Each of
417 % these colors becomes an entry in the color map.
419 % Finally, the assignment phase reclassifies each pixel in the pruned
420 % tree to identify the deepest node containing the pixel's color. The
421 % pixel's value in the pixel array becomes the index of this node's mean
422 % color in the color map.
424 % The format of the AssignImageColors() method is:
426 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
428 % A description of each parameter follows.
430 % o image: the image.
432 % o cube_info: A pointer to the Cube structure.
436 static inline void AssociateAlphaPixel(const Image *image,
437 const CubeInfo *cube_info,const Quantum *pixel,DoublePixelPacket *alpha_pixel)
442 if ((cube_info->associate_alpha == MagickFalse) ||
443 (GetPixelAlpha(image,pixel) == OpaqueAlpha))
445 alpha_pixel->red=(double) GetPixelRed(image,pixel);
446 alpha_pixel->green=(double) GetPixelGreen(image,pixel);
447 alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
448 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
451 alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
452 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
453 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
454 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
455 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
458 static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
459 const PixelInfo *pixel,DoublePixelPacket *alpha_pixel)
464 if ((cube_info->associate_alpha == MagickFalse) ||
465 (pixel->alpha == OpaqueAlpha))
467 alpha_pixel->red=(double) pixel->red;
468 alpha_pixel->green=(double) pixel->green;
469 alpha_pixel->blue=(double) pixel->blue;
470 alpha_pixel->alpha=(double) pixel->alpha;
473 alpha=(double) (QuantumScale*pixel->alpha);
474 alpha_pixel->red=alpha*pixel->red;
475 alpha_pixel->green=alpha*pixel->green;
476 alpha_pixel->blue=alpha*pixel->blue;
477 alpha_pixel->alpha=(double) pixel->alpha;
480 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
481 const DoublePixelPacket *pixel,size_t index)
486 id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
487 ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
488 ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
489 if (cube_info->associate_alpha != MagickFalse)
490 id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
494 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
495 ExceptionInfo *exception)
497 #define AssignImageTag "Assign/Image"
503 Allocate image colormap.
505 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
506 (cube_info->quantize_info->colorspace != CMYKColorspace))
507 (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace,
510 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
511 (void) TransformImageColorspace(image,sRGBColorspace,exception);
512 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
513 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
516 cube_info->transparent_pixels=0;
517 cube_info->transparent_index=(-1);
518 (void) DefineImageColormap(image,cube_info,cube_info->root);
520 Create a reduced color image.
522 if (cube_info->quantize_info->dither_method != NoDitherMethod)
523 (void) DitherImage(image,cube_info,exception);
533 image_view=AcquireAuthenticCacheView(image,exception);
534 #if defined(MAGICKCORE_OPENMP_SUPPORT)
535 #pragma omp parallel for schedule(static,4) shared(status) \
536 magick_number_threads(image,image,image->rows,1)
538 for (y=0; y < (ssize_t) image->rows; y++)
552 if (status == MagickFalse)
554 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
556 if (q == (Quantum *) NULL)
562 for (x=0; x < (ssize_t) image->columns; x+=count)
567 register const NodeInfo
578 Identify the deepest node containing the pixel's color.
580 for (count=1; (x+count) < (ssize_t) image->columns; count++)
585 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
586 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
589 AssociateAlphaPixel(image,&cube,q,&pixel);
591 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
593 id=ColorToNodeId(&cube,&pixel,index);
594 if (node_info->child[id] == (NodeInfo *) NULL)
596 node_info=node_info->child[id];
599 Find closest color among siblings and their children.
602 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
604 ClosestColor(image,&cube,node_info->parent);
605 index=cube.color_number;
606 for (i=0; i < (ssize_t) count; i++)
608 if (image->storage_class == PseudoClass)
609 SetPixelIndex(image,(Quantum) index,q);
610 if (cube.quantize_info->measure_error == MagickFalse)
612 SetPixelRed(image,ClampToQuantum(
613 image->colormap[index].red),q);
614 SetPixelGreen(image,ClampToQuantum(
615 image->colormap[index].green),q);
616 SetPixelBlue(image,ClampToQuantum(
617 image->colormap[index].blue),q);
618 if (cube.associate_alpha != MagickFalse)
619 SetPixelAlpha(image,ClampToQuantum(
620 image->colormap[index].alpha),q);
622 q+=GetPixelChannels(image);
625 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
627 if (image->progress_monitor != (MagickProgressMonitor) NULL)
632 #if defined(MAGICKCORE_OPENMP_SUPPORT)
633 #pragma omp critical (MagickCore_AssignImageColors)
635 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
637 if (proceed == MagickFalse)
641 image_view=DestroyCacheView(image_view);
643 if (cube_info->quantize_info->measure_error != MagickFalse)
644 (void) GetImageQuantizeError(image,exception);
645 if ((cube_info->quantize_info->number_colors == 2) &&
646 ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) ||
647 (cube_info->quantize_info->colorspace == GRAYColorspace)))
656 if ((image->colors > 1) &&
657 (GetPixelInfoLuma(image->colormap+0) >
658 GetPixelInfoLuma(image->colormap+1)))
659 intensity=(double) QuantumRange;
660 image->colormap[0].red=intensity;
661 image->colormap[0].green=intensity;
662 image->colormap[0].blue=intensity;
663 if (image->colors > 1)
665 image->colormap[1].red=(double) QuantumRange-intensity;
666 image->colormap[1].green=(double) QuantumRange-intensity;
667 image->colormap[1].blue=(double) QuantumRange-intensity;
670 (void) SyncImage(image,exception);
671 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
672 (cube_info->quantize_info->colorspace != CMYKColorspace))
673 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
678 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
682 + C l a s s i f y I m a g e C o l o r s %
686 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
688 % ClassifyImageColors() begins by initializing a color description tree
689 % of sufficient depth to represent each possible input color in a leaf.
690 % However, it is impractical to generate a fully-formed color
691 % description tree in the storage_class phase for realistic values of
692 % Cmax. If colors components in the input image are quantized to k-bit
693 % precision, so that Cmax= 2k-1, the tree would need k levels below the
694 % root node to allow representing each possible input color in a leaf.
695 % This becomes prohibitive because the tree's total number of nodes is
698 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
699 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
700 % Initializes data structures for nodes only as they are needed; (2)
701 % Chooses a maximum depth for the tree as a function of the desired
702 % number of colors in the output image (currently log2(colormap size)).
704 % For each pixel in the input image, storage_class scans downward from
705 % the root of the color description tree. At each level of the tree it
706 % identifies the single node which represents a cube in RGB space
707 % containing It updates the following data for each such node:
709 % n1 : Number of pixels whose color is contained in the RGB cube
710 % which this node represents;
712 % n2 : Number of pixels whose color is not represented in a node at
713 % lower depth in the tree; initially, n2 = 0 for all nodes except
714 % leaves of the tree.
716 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
717 % all pixels not classified at a lower depth. The combination of
718 % these sums and n2 will ultimately characterize the mean color of a
719 % set of pixels represented by this node.
721 % E: the distance squared in RGB space between each pixel contained
722 % within a node and the nodes' center. This represents the quantization
725 % The format of the ClassifyImageColors() method is:
727 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
728 % const Image *image,ExceptionInfo *exception)
730 % A description of each parameter follows.
732 % o cube_info: A pointer to the Cube structure.
734 % o image: the image.
738 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
743 associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
745 if ((cube_info->quantize_info->number_colors == 2) &&
746 ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) ||
747 (cube_info->quantize_info->colorspace == GRAYColorspace)))
748 associate_alpha=MagickFalse;
749 cube_info->associate_alpha=associate_alpha;
752 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
753 const Image *image,ExceptionInfo *exception)
755 #define ClassifyImageTag "Classify/Image"
785 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
787 SetAssociatedAlpha(image,cube_info);
788 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
789 (cube_info->quantize_info->colorspace != CMYKColorspace))
790 (void) TransformImageColorspace((Image *) image,
791 cube_info->quantize_info->colorspace,exception);
793 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
794 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
795 midpoint.red=(double) QuantumRange/2.0;
796 midpoint.green=(double) QuantumRange/2.0;
797 midpoint.blue=(double) QuantumRange/2.0;
798 midpoint.alpha=(double) QuantumRange/2.0;
800 image_view=AcquireVirtualCacheView(image,exception);
801 for (y=0; y < (ssize_t) image->rows; y++)
803 register const Quantum
809 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
810 if (p == (const Quantum *) NULL)
812 if (cube_info->nodes > MaxNodes)
815 Prune one level if the color tree is too large.
817 PruneLevel(cube_info,cube_info->root);
820 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
823 Start at the root and descend the color cube tree.
825 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
830 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
831 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
834 AssociateAlphaPixel(image,cube_info,p,&pixel);
835 index=MaxTreeDepth-1;
836 bisect=((double) QuantumRange+1.0)/2.0;
838 node_info=cube_info->root;
839 for (level=1; level <= MaxTreeDepth; level++)
845 id=ColorToNodeId(cube_info,&pixel,index);
846 mid.red+=(id & 1) != 0 ? bisect : -bisect;
847 mid.green+=(id & 2) != 0 ? bisect : -bisect;
848 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
849 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
850 if (node_info->child[id] == (NodeInfo *) NULL)
853 Set colors of new node to contain pixel.
855 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
856 if (node_info->child[id] == (NodeInfo *) NULL)
858 (void) ThrowMagickException(exception,GetMagickModule(),
859 ResourceLimitError,"MemoryAllocationFailed","`%s'",
863 if (level == MaxTreeDepth)
867 Approximate the quantization error represented by this node.
869 node_info=node_info->child[id];
870 error.red=QuantumScale*(pixel.red-mid.red);
871 error.green=QuantumScale*(pixel.green-mid.green);
872 error.blue=QuantumScale*(pixel.blue-mid.blue);
873 if (cube_info->associate_alpha != MagickFalse)
874 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
875 distance=(double) (error.red*error.red+error.green*error.green+
876 error.blue*error.blue+error.alpha*error.alpha);
879 node_info->quantize_error+=count*sqrt(distance);
880 cube_info->root->quantize_error+=node_info->quantize_error;
884 Sum RGB for this leaf for later derivation of the mean cube color.
886 node_info->number_unique+=count;
887 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
888 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
889 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
890 if (cube_info->associate_alpha != MagickFalse)
891 node_info->total_color.alpha+=count*QuantumScale*
892 ClampPixel(pixel.alpha);
894 node_info->total_color.alpha+=count*QuantumScale*
895 ClampPixel(OpaqueAlpha);
896 p+=count*GetPixelChannels(image);
898 if (cube_info->colors > cube_info->maximum_colors)
900 PruneToCubeDepth(cube_info,cube_info->root);
903 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
905 if (proceed == MagickFalse)
908 for (y++; y < (ssize_t) image->rows; y++)
910 register const Quantum
916 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
917 if (p == (const Quantum *) NULL)
919 if (cube_info->nodes > MaxNodes)
922 Prune one level if the color tree is too large.
924 PruneLevel(cube_info,cube_info->root);
927 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
930 Start at the root and descend the color cube tree.
932 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
937 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
938 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
941 AssociateAlphaPixel(image,cube_info,p,&pixel);
942 index=MaxTreeDepth-1;
943 bisect=((double) QuantumRange+1.0)/2.0;
945 node_info=cube_info->root;
946 for (level=1; level <= cube_info->depth; level++)
952 id=ColorToNodeId(cube_info,&pixel,index);
953 mid.red+=(id & 1) != 0 ? bisect : -bisect;
954 mid.green+=(id & 2) != 0 ? bisect : -bisect;
955 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
956 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
957 if (node_info->child[id] == (NodeInfo *) NULL)
960 Set colors of new node to contain pixel.
962 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
963 if (node_info->child[id] == (NodeInfo *) NULL)
965 (void) ThrowMagickException(exception,GetMagickModule(),
966 ResourceLimitError,"MemoryAllocationFailed","%s",
970 if (level == cube_info->depth)
974 Approximate the quantization error represented by this node.
976 node_info=node_info->child[id];
977 error.red=QuantumScale*(pixel.red-mid.red);
978 error.green=QuantumScale*(pixel.green-mid.green);
979 error.blue=QuantumScale*(pixel.blue-mid.blue);
980 if (cube_info->associate_alpha != MagickFalse)
981 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
982 distance=(double) (error.red*error.red+error.green*error.green+
983 error.blue*error.blue+error.alpha*error.alpha);
984 if (IsNaN(distance) != MagickFalse)
986 node_info->quantize_error+=count*sqrt(distance);
987 cube_info->root->quantize_error+=node_info->quantize_error;
991 Sum RGB for this leaf for later derivation of the mean cube color.
993 node_info->number_unique+=count;
994 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
995 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
996 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
997 if (cube_info->associate_alpha != MagickFalse)
998 node_info->total_color.alpha+=count*QuantumScale*
999 ClampPixel(pixel.alpha);
1001 node_info->total_color.alpha+=count*QuantumScale*
1002 ClampPixel(OpaqueAlpha);
1003 p+=count*GetPixelChannels(image);
1005 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1007 if (proceed == MagickFalse)
1010 image_view=DestroyCacheView(image_view);
1011 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1012 (cube_info->quantize_info->colorspace != CMYKColorspace))
1013 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1014 return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1018 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1022 % C l o n e Q u a n t i z e I n f o %
1026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1028 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1029 % or if quantize info is NULL, a new one.
1031 % The format of the CloneQuantizeInfo method is:
1033 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1035 % A description of each parameter follows:
1037 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1038 % quantize info, or if image info is NULL a new one.
1040 % o quantize_info: a structure of type info.
1043 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1048 clone_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*clone_info));
1049 GetQuantizeInfo(clone_info);
1050 if (quantize_info == (QuantizeInfo *) NULL)
1052 clone_info->number_colors=quantize_info->number_colors;
1053 clone_info->tree_depth=quantize_info->tree_depth;
1054 clone_info->dither_method=quantize_info->dither_method;
1055 clone_info->colorspace=quantize_info->colorspace;
1056 clone_info->measure_error=quantize_info->measure_error;
1061 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1065 + C l o s e s t C o l o r %
1069 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1071 % ClosestColor() traverses the color cube tree at a particular node and
1072 % determines which colormap entry best represents the input color.
1074 % The format of the ClosestColor method is:
1076 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1077 % const NodeInfo *node_info)
1079 % A description of each parameter follows.
1081 % o image: the image.
1083 % o cube_info: A pointer to the Cube structure.
1085 % o node_info: the address of a structure of type NodeInfo which points to a
1086 % node in the color cube tree that is to be pruned.
1089 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1090 const NodeInfo *node_info)
1099 Traverse any children.
1101 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1102 for (i=0; i < (ssize_t) number_children; i++)
1103 if (node_info->child[i] != (NodeInfo *) NULL)
1104 ClosestColor(image,cube_info,node_info->child[i]);
1105 if (node_info->number_unique != 0)
1115 register DoublePixelPacket
1122 Determine if this color is "closest".
1124 p=image->colormap+node_info->color_number;
1125 q=(&cube_info->target);
1128 if (cube_info->associate_alpha != MagickFalse)
1130 alpha=(double) (QuantumScale*p->alpha);
1131 beta=(double) (QuantumScale*q->alpha);
1133 pixel=alpha*p->red-beta*q->red;
1134 distance=pixel*pixel;
1135 if (distance <= cube_info->distance)
1137 pixel=alpha*p->green-beta*q->green;
1138 distance+=pixel*pixel;
1139 if (distance <= cube_info->distance)
1141 pixel=alpha*p->blue-beta*q->blue;
1142 distance+=pixel*pixel;
1143 if (distance <= cube_info->distance)
1145 if (cube_info->associate_alpha != MagickFalse)
1147 pixel=p->alpha-q->alpha;
1148 distance+=pixel*pixel;
1150 if (distance <= cube_info->distance)
1152 cube_info->distance=distance;
1153 cube_info->color_number=node_info->color_number;
1162 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1166 % C o m p r e s s I m a g e C o l o r m a p %
1170 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1172 % CompressImageColormap() compresses an image colormap by removing any
1173 % duplicate or unused color entries.
1175 % The format of the CompressImageColormap method is:
1177 % MagickBooleanType CompressImageColormap(Image *image,
1178 % ExceptionInfo *exception)
1180 % A description of each parameter follows:
1182 % o image: the image.
1184 % o exception: return any errors or warnings in this structure.
1187 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1188 ExceptionInfo *exception)
1193 assert(image != (Image *) NULL);
1194 assert(image->signature == MagickCoreSignature);
1195 if (image->debug != MagickFalse)
1196 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1197 if (IsPaletteImage(image) == MagickFalse)
1198 return(MagickFalse);
1199 GetQuantizeInfo(&quantize_info);
1200 quantize_info.number_colors=image->colors;
1201 quantize_info.tree_depth=MaxTreeDepth;
1202 return(QuantizeImage(&quantize_info,image,exception));
1206 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1210 + D e f i n e I m a g e C o l o r m a p %
1214 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1216 % DefineImageColormap() traverses the color cube tree and notes each colormap
1217 % entry. A colormap entry is any node in the color cube tree where the
1218 % of unique colors is not zero. DefineImageColormap() returns the number of
1219 % colors in the image colormap.
1221 % The format of the DefineImageColormap method is:
1223 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1224 % NodeInfo *node_info)
1226 % A description of each parameter follows.
1228 % o image: the image.
1230 % o cube_info: A pointer to the Cube structure.
1232 % o node_info: the address of a structure of type NodeInfo which points to a
1233 % node in the color cube tree that is to be pruned.
1236 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1237 NodeInfo *node_info)
1246 Traverse any children.
1248 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1249 for (i=0; i < (ssize_t) number_children; i++)
1250 if (node_info->child[i] != (NodeInfo *) NULL)
1251 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1252 if (node_info->number_unique != 0)
1261 Colormap entry is defined by the mean color in this cube.
1263 q=image->colormap+image->colors;
1264 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1265 alpha=PerceptibleReciprocal(alpha);
1266 if (cube_info->associate_alpha == MagickFalse)
1268 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1269 node_info->total_color.red);
1270 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1271 node_info->total_color.green);
1272 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1273 node_info->total_color.blue);
1274 q->alpha=(double) OpaqueAlpha;
1281 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1282 q->alpha=(double) ClampToQuantum(opacity);
1283 if (q->alpha == OpaqueAlpha)
1285 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1286 node_info->total_color.red);
1287 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1288 node_info->total_color.green);
1289 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1290 node_info->total_color.blue);
1297 gamma=(double) (QuantumScale*q->alpha);
1298 gamma=PerceptibleReciprocal(gamma);
1299 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1300 node_info->total_color.red);
1301 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1302 node_info->total_color.green);
1303 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1304 node_info->total_color.blue);
1305 if (node_info->number_unique > cube_info->transparent_pixels)
1307 cube_info->transparent_pixels=node_info->number_unique;
1308 cube_info->transparent_index=(ssize_t) image->colors;
1312 node_info->color_number=image->colors++;
1314 return(image->colors);
1318 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1322 + D e s t r o y C u b e I n f o %
1326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1328 % DestroyCubeInfo() deallocates memory associated with an image.
1330 % The format of the DestroyCubeInfo method is:
1332 % DestroyCubeInfo(CubeInfo *cube_info)
1334 % A description of each parameter follows:
1336 % o cube_info: the address of a structure of type CubeInfo.
1339 static void DestroyCubeInfo(CubeInfo *cube_info)
1345 Release color cube tree storage.
1349 nodes=cube_info->node_queue->next;
1350 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1351 cube_info->node_queue->nodes);
1352 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1353 cube_info->node_queue);
1354 cube_info->node_queue=nodes;
1355 } while (cube_info->node_queue != (Nodes *) NULL);
1356 if (cube_info->memory_info != (MemoryInfo *) NULL)
1357 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1358 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1359 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1363 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1367 % D e s t r o y Q u a n t i z e I n f o %
1371 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1373 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1376 % The format of the DestroyQuantizeInfo method is:
1378 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1380 % A description of each parameter follows:
1382 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1385 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1387 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1388 assert(quantize_info != (QuantizeInfo *) NULL);
1389 assert(quantize_info->signature == MagickCoreSignature);
1390 quantize_info->signature=(~MagickCoreSignature);
1391 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1392 return(quantize_info);
1396 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1400 + D i t h e r I m a g e %
1404 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1406 % DitherImage() distributes the difference between an original image and
1407 % the corresponding color reduced algorithm to neighboring pixels using
1408 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1409 % MagickTrue if the image is dithered otherwise MagickFalse.
1411 % The format of the DitherImage method is:
1413 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1414 % ExceptionInfo *exception)
1416 % A description of each parameter follows.
1418 % o image: the image.
1420 % o cube_info: A pointer to the Cube structure.
1422 % o exception: return any errors or warnings in this structure.
1426 static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels)
1431 assert(pixels != (DoublePixelPacket **) NULL);
1432 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1433 if (pixels[i] != (DoublePixelPacket *) NULL)
1434 pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]);
1435 pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels);
1439 static DoublePixelPacket **AcquirePixelThreadSet(const size_t count)
1450 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1451 pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads,
1453 if (pixels == (DoublePixelPacket **) NULL)
1454 return((DoublePixelPacket **) NULL);
1455 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1456 for (i=0; i < (ssize_t) number_threads; i++)
1458 pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count,2*
1460 if (pixels[i] == (DoublePixelPacket *) NULL)
1461 return(DestroyPixelThreadSet(pixels));
1466 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1467 const DoublePixelPacket *pixel)
1469 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1470 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1471 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1472 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1477 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1478 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1479 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1480 if (cube_info->associate_alpha != MagickFalse)
1481 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1485 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1486 ExceptionInfo *exception)
1488 #define DitherImageTag "Dither/Image"
1503 Distribute quantization error using Floyd-Steinberg.
1505 pixels=AcquirePixelThreadSet(image->columns);
1506 if (pixels == (DoublePixelPacket **) NULL)
1507 return(MagickFalse);
1509 image_view=AcquireAuthenticCacheView(image,exception);
1510 for (y=0; y < (ssize_t) image->rows; y++)
1513 id = GetOpenMPThreadId();
1534 if (status == MagickFalse)
1536 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1537 if (q == (Quantum *) NULL)
1543 current=pixels[id]+(y & 0x01)*image->columns;
1544 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1545 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1546 for (x=0; x < (ssize_t) image->columns; x++)
1558 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1559 AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel);
1562 pixel.red+=7*current[u-v].red/16;
1563 pixel.green+=7*current[u-v].green/16;
1564 pixel.blue+=7*current[u-v].blue/16;
1565 if (cube.associate_alpha != MagickFalse)
1566 pixel.alpha+=7*current[u-v].alpha/16;
1570 if (x < (ssize_t) (image->columns-1))
1572 pixel.red+=previous[u+v].red/16;
1573 pixel.green+=previous[u+v].green/16;
1574 pixel.blue+=previous[u+v].blue/16;
1575 if (cube.associate_alpha != MagickFalse)
1576 pixel.alpha+=previous[u+v].alpha/16;
1578 pixel.red+=5*previous[u].red/16;
1579 pixel.green+=5*previous[u].green/16;
1580 pixel.blue+=5*previous[u].blue/16;
1581 if (cube.associate_alpha != MagickFalse)
1582 pixel.alpha+=5*previous[u].alpha/16;
1585 pixel.red+=3*previous[u-v].red/16;
1586 pixel.green+=3*previous[u-v].green/16;
1587 pixel.blue+=3*previous[u-v].blue/16;
1588 if (cube.associate_alpha != MagickFalse)
1589 pixel.alpha+=3*previous[u-v].alpha/16;
1592 pixel.red=(double) ClampPixel(pixel.red);
1593 pixel.green=(double) ClampPixel(pixel.green);
1594 pixel.blue=(double) ClampPixel(pixel.blue);
1595 if (cube.associate_alpha != MagickFalse)
1596 pixel.alpha=(double) ClampPixel(pixel.alpha);
1597 i=CacheOffset(&cube,&pixel);
1598 if (cube.cache[i] < 0)
1607 Identify the deepest node containing the pixel's color.
1609 node_info=cube.root;
1610 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1612 node_id=ColorToNodeId(&cube,&pixel,index);
1613 if (node_info->child[node_id] == (NodeInfo *) NULL)
1615 node_info=node_info->child[node_id];
1618 Find closest color among siblings and their children.
1621 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1623 ClosestColor(image,&cube,node_info->parent);
1624 cube.cache[i]=(ssize_t) cube.color_number;
1627 Assign pixel to closest colormap entry.
1629 index=(size_t) cube.cache[i];
1630 if (image->storage_class == PseudoClass)
1631 SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image));
1632 if (cube.quantize_info->measure_error == MagickFalse)
1634 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),
1635 q+u*GetPixelChannels(image));
1636 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),
1637 q+u*GetPixelChannels(image));
1638 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),
1639 q+u*GetPixelChannels(image));
1640 if (cube.associate_alpha != MagickFalse)
1641 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),
1642 q+u*GetPixelChannels(image));
1644 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1649 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1650 current[u].red=pixel.red-color.red;
1651 current[u].green=pixel.green-color.green;
1652 current[u].blue=pixel.blue-color.blue;
1653 if (cube.associate_alpha != MagickFalse)
1654 current[u].alpha=pixel.alpha-color.alpha;
1655 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1660 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1662 if (proceed == MagickFalse)
1667 image_view=DestroyCacheView(image_view);
1668 pixels=DestroyPixelThreadSet(pixels);
1672 static MagickBooleanType
1673 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1676 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1677 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1684 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1686 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1688 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1694 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1696 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1698 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1704 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1714 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1716 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1718 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1730 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1732 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1734 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1736 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1738 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1740 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1742 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1748 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1750 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1752 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1754 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1756 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1758 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1760 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1766 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1768 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1770 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1772 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1774 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1776 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1778 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1784 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1786 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1788 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1790 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1792 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1794 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1796 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1805 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1806 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1808 #define DitherImageTag "Dither/Image"
1824 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1825 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1836 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1837 if (q == (Quantum *) NULL)
1838 return(MagickFalse);
1839 AssociateAlphaPixel(image,cube_info,q,&pixel);
1840 for (i=0; i < ErrorQueueLength; i++)
1842 pixel.red+=p->weights[i]*p->error[i].red;
1843 pixel.green+=p->weights[i]*p->error[i].green;
1844 pixel.blue+=p->weights[i]*p->error[i].blue;
1845 if (cube_info->associate_alpha != MagickFalse)
1846 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1848 pixel.red=(double) ClampPixel(pixel.red);
1849 pixel.green=(double) ClampPixel(pixel.green);
1850 pixel.blue=(double) ClampPixel(pixel.blue);
1851 if (cube_info->associate_alpha != MagickFalse)
1852 pixel.alpha=(double) ClampPixel(pixel.alpha);
1853 i=CacheOffset(cube_info,&pixel);
1854 if (p->cache[i] < 0)
1863 Identify the deepest node containing the pixel's color.
1866 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1868 id=ColorToNodeId(cube_info,&pixel,index);
1869 if (node_info->child[id] == (NodeInfo *) NULL)
1871 node_info=node_info->child[id];
1874 Find closest color among siblings and their children.
1877 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1878 QuantumRange+1.0)+1.0);
1879 ClosestColor(image,p,node_info->parent);
1880 p->cache[i]=(ssize_t) p->color_number;
1883 Assign pixel to closest colormap entry.
1885 index=(size_t) p->cache[i];
1886 if (image->storage_class == PseudoClass)
1887 SetPixelIndex(image,(Quantum) index,q);
1888 if (cube_info->quantize_info->measure_error == MagickFalse)
1890 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1891 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1892 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1893 if (cube_info->associate_alpha != MagickFalse)
1894 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1896 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1897 return(MagickFalse);
1899 Propagate the error as the last entry of the error queue.
1901 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1902 sizeof(p->error[0]));
1903 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1904 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1905 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1906 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1907 if (cube_info->associate_alpha != MagickFalse)
1908 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1909 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1910 if (proceed == MagickFalse)
1911 return(MagickFalse);
1916 case WestGravity: p->x--; break;
1917 case EastGravity: p->x++; break;
1918 case NorthGravity: p->y--; break;
1919 case SouthGravity: p->y++; break;
1924 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1925 ExceptionInfo *exception)
1939 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1940 return(FloydSteinbergDither(image,cube_info,exception));
1942 Distribute quantization error along a Hilbert curve.
1944 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1945 sizeof(*cube_info->error));
1948 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1949 for (depth=1; i != 0; depth++)
1951 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1953 cube_info->offset=0;
1954 cube_info->span=(MagickSizeType) image->columns*image->rows;
1955 image_view=AcquireAuthenticCacheView(image,exception);
1957 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1958 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1959 image_view=DestroyCacheView(image_view);
1964 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1968 + G e t C u b e I n f o %
1972 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1974 % GetCubeInfo() initialize the Cube data structure.
1976 % The format of the GetCubeInfo method is:
1978 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1979 % const size_t depth,const size_t maximum_colors)
1981 % A description of each parameter follows.
1983 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1985 % o depth: Normally, this integer value is zero or one. A zero or
1986 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1987 % A tree of this depth generally allows the best representation of the
1988 % reference image with the least amount of memory and the fastest
1989 % computational speed. In some cases, such as an image with low color
1990 % dispersion (a few number of colors), a value other than
1991 % Log4(number_colors) is required. To expand the color tree completely,
1994 % o maximum_colors: maximum colors.
1997 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1998 const size_t depth,const size_t maximum_colors)
2014 Initialize tree to describe color cube_info.
2016 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2017 if (cube_info == (CubeInfo *) NULL)
2018 return((CubeInfo *) NULL);
2019 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2020 cube_info->depth=depth;
2021 if (cube_info->depth > MaxTreeDepth)
2022 cube_info->depth=MaxTreeDepth;
2023 if (cube_info->depth < 2)
2025 cube_info->maximum_colors=maximum_colors;
2027 Initialize root node.
2029 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2030 if (cube_info->root == (NodeInfo *) NULL)
2031 return((CubeInfo *) NULL);
2032 cube_info->root->parent=cube_info->root;
2033 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2034 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2037 Initialize dither resources.
2039 length=(size_t) (1UL << (4*(8-CacheShift)));
2040 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2041 if (cube_info->memory_info == (MemoryInfo *) NULL)
2042 return((CubeInfo *) NULL);
2043 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2045 Initialize color cache.
2047 (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)*
2050 Distribute weights along a curve of exponential decay.
2053 for (i=0; i < ErrorQueueLength; i++)
2055 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2056 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2059 Normalize the weighting factors.
2062 for (i=0; i < ErrorQueueLength; i++)
2063 weight+=cube_info->weights[i];
2065 for (i=0; i < ErrorQueueLength; i++)
2067 cube_info->weights[i]/=weight;
2068 sum+=cube_info->weights[i];
2070 cube_info->weights[0]+=1.0-sum;
2075 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2079 + G e t N o d e I n f o %
2083 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2085 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2086 % presets all fields to zero.
2088 % The format of the GetNodeInfo method is:
2090 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2091 % const size_t level,NodeInfo *parent)
2093 % A description of each parameter follows.
2095 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2097 % o id: Specifies the child number of the node.
2099 % o level: Specifies the level in the storage_class the node resides.
2102 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2103 const size_t level,NodeInfo *parent)
2108 if (cube_info->free_nodes == 0)
2114 Allocate a new queue of nodes.
2116 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2117 if (nodes == (Nodes *) NULL)
2118 return((NodeInfo *) NULL);
2119 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2120 sizeof(*nodes->nodes));
2121 if (nodes->nodes == (NodeInfo *) NULL)
2122 return((NodeInfo *) NULL);
2123 nodes->next=cube_info->node_queue;
2124 cube_info->node_queue=nodes;
2125 cube_info->next_node=nodes->nodes;
2126 cube_info->free_nodes=NodesInAList;
2129 cube_info->free_nodes--;
2130 node_info=cube_info->next_node++;
2131 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2132 node_info->parent=parent;
2134 node_info->level=level;
2139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2143 % G e t I m a g e Q u a n t i z e E r r o r %
2147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2149 % GetImageQuantizeError() measures the difference between the original
2150 % and quantized images. This difference is the total quantization error.
2151 % The error is computed by summing over all pixels in an image the distance
2152 % squared in RGB space between each reference pixel value and its quantized
2153 % value. These values are computed:
2155 % o mean_error_per_pixel: This value is the mean error for any single
2156 % pixel in the image.
2158 % o normalized_mean_square_error: This value is the normalized mean
2159 % quantization error for any single pixel in the image. This distance
2160 % measure is normalized to a range between 0 and 1. It is independent
2161 % of the range of red, green, and blue values in the image.
2163 % o normalized_maximum_square_error: Thsi value is the normalized
2164 % maximum quantization error for any single pixel in the image. This
2165 % distance measure is normalized to a range between 0 and 1. It is
2166 % independent of the range of red, green, and blue values in your image.
2168 % The format of the GetImageQuantizeError method is:
2170 % MagickBooleanType GetImageQuantizeError(Image *image,
2171 % ExceptionInfo *exception)
2173 % A description of each parameter follows.
2175 % o image: the image.
2177 % o exception: return any errors or warnings in this structure.
2180 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2181 ExceptionInfo *exception)
2193 mean_error_per_pixel;
2201 assert(image != (Image *) NULL);
2202 assert(image->signature == MagickCoreSignature);
2203 if (image->debug != MagickFalse)
2204 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2205 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2206 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2207 if (image->storage_class == DirectClass)
2211 area=3.0*image->columns*image->rows;
2213 mean_error_per_pixel=0.0;
2215 image_view=AcquireVirtualCacheView(image,exception);
2216 for (y=0; y < (ssize_t) image->rows; y++)
2218 register const Quantum
2224 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2225 if (p == (const Quantum *) NULL)
2227 for (x=0; x < (ssize_t) image->columns; x++)
2229 index=GetPixelIndex(image,p);
2230 if (image->alpha_trait == BlendPixelTrait)
2232 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2233 beta=(double) (QuantumScale*image->colormap[index].alpha);
2235 distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
2236 image->colormap[index].red));
2237 mean_error_per_pixel+=distance;
2238 mean_error+=distance*distance;
2239 if (distance > maximum_error)
2240 maximum_error=distance;
2241 distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
2242 image->colormap[index].green));
2243 mean_error_per_pixel+=distance;
2244 mean_error+=distance*distance;
2245 if (distance > maximum_error)
2246 maximum_error=distance;
2247 distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta*
2248 image->colormap[index].blue));
2249 mean_error_per_pixel+=distance;
2250 mean_error+=distance*distance;
2251 if (distance > maximum_error)
2252 maximum_error=distance;
2253 p+=GetPixelChannels(image);
2256 image_view=DestroyCacheView(image_view);
2257 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2258 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2260 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2265 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2269 % G e t Q u a n t i z e I n f o %
2273 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2275 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2277 % The format of the GetQuantizeInfo method is:
2279 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2281 % A description of each parameter follows:
2283 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2286 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2288 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2289 assert(quantize_info != (QuantizeInfo *) NULL);
2290 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2291 quantize_info->number_colors=256;
2292 quantize_info->dither_method=RiemersmaDitherMethod;
2293 quantize_info->colorspace=UndefinedColorspace;
2294 quantize_info->measure_error=MagickFalse;
2295 quantize_info->signature=MagickCoreSignature;
2299 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2303 % P o s t e r i z e I m a g e %
2307 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2309 % PosterizeImage() reduces the image to a limited number of colors for a
2312 % The format of the PosterizeImage method is:
2314 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2315 % const DitherMethod dither_method,ExceptionInfo *exception)
2317 % A description of each parameter follows:
2319 % o image: Specifies a pointer to an Image structure.
2321 % o levels: Number of color levels allowed in each channel. Very low values
2322 % (2, 3, or 4) have the most visible effect.
2324 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2325 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2327 % o exception: return any errors or warnings in this structure.
2331 static inline double MagickRound(double x)
2334 Round the fraction to nearest integer.
2336 if ((x-floor(x)) < (ceil(x)-x))
2341 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2342 const DitherMethod dither_method,ExceptionInfo *exception)
2344 #define PosterizeImageTag "Posterize/Image"
2345 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2346 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2366 assert(image != (Image *) NULL);
2367 assert(image->signature == MagickCoreSignature);
2368 if (image->debug != MagickFalse)
2369 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2370 assert(exception != (ExceptionInfo *) NULL);
2371 assert(exception->signature == MagickCoreSignature);
2372 if (image->storage_class == PseudoClass)
2373 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2374 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2375 magick_number_threads(image,image,image->colors,1)
2377 for (i=0; i < (ssize_t) image->colors; i++)
2382 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2383 image->colormap[i].red=(double)
2384 PosterizePixel(image->colormap[i].red);
2385 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2386 image->colormap[i].green=(double)
2387 PosterizePixel(image->colormap[i].green);
2388 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2389 image->colormap[i].blue=(double)
2390 PosterizePixel(image->colormap[i].blue);
2391 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2392 image->colormap[i].alpha=(double)
2393 PosterizePixel(image->colormap[i].alpha);
2400 image_view=AcquireAuthenticCacheView(image,exception);
2401 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2402 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2403 magick_number_threads(image,image,image->rows,1)
2405 for (y=0; y < (ssize_t) image->rows; y++)
2413 if (status == MagickFalse)
2415 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2416 if (q == (Quantum *) NULL)
2421 for (x=0; x < (ssize_t) image->columns; x++)
2423 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2424 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2425 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2426 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2427 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2428 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2429 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2430 (image->colorspace == CMYKColorspace))
2431 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2432 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2433 (image->alpha_trait == BlendPixelTrait))
2434 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2435 q+=GetPixelChannels(image);
2437 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2439 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2444 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2445 #pragma omp critical (MagickCore_PosterizeImage)
2447 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2449 if (proceed == MagickFalse)
2453 image_view=DestroyCacheView(image_view);
2454 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2455 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2456 levels,MaxColormapSize+1);
2457 quantize_info->dither_method=dither_method;
2458 quantize_info->tree_depth=MaxTreeDepth;
2459 status=QuantizeImage(quantize_info,image,exception);
2460 quantize_info=DestroyQuantizeInfo(quantize_info);
2465 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2469 + P r u n e C h i l d %
2473 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2475 % PruneChild() deletes the given node and merges its statistics into its
2478 % The format of the PruneSubtree method is:
2480 % PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
2482 % A description of each parameter follows.
2484 % o cube_info: A pointer to the Cube structure.
2486 % o node_info: pointer to node in color cube tree that is to be pruned.
2489 static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
2501 Traverse any children.
2503 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2504 for (i=0; i < (ssize_t) number_children; i++)
2505 if (node_info->child[i] != (NodeInfo *) NULL)
2506 PruneChild(cube_info,node_info->child[i]);
2508 Merge color statistics into parent.
2510 parent=node_info->parent;
2511 parent->number_unique+=node_info->number_unique;
2512 parent->total_color.red+=node_info->total_color.red;
2513 parent->total_color.green+=node_info->total_color.green;
2514 parent->total_color.blue+=node_info->total_color.blue;
2515 parent->total_color.alpha+=node_info->total_color.alpha;
2516 parent->child[node_info->id]=(NodeInfo *) NULL;
2521 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2525 + P r u n e L e v e l %
2529 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2531 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2532 % their color statistics into their parent node.
2534 % The format of the PruneLevel method is:
2536 % PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
2538 % A description of each parameter follows.
2540 % o cube_info: A pointer to the Cube structure.
2542 % o node_info: pointer to node in color cube tree that is to be pruned.
2545 static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
2554 Traverse any children.
2556 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2557 for (i=0; i < (ssize_t) number_children; i++)
2558 if (node_info->child[i] != (NodeInfo *) NULL)
2559 PruneLevel(cube_info,node_info->child[i]);
2560 if (node_info->level == cube_info->depth)
2561 PruneChild(cube_info,node_info);
2565 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2569 + P r u n e T o C u b e D e p t h %
2573 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2575 % PruneToCubeDepth() deletes any nodes at a depth greater than
2576 % cube_info->depth while merging their color statistics into their parent
2579 % The format of the PruneToCubeDepth method is:
2581 % PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
2583 % A description of each parameter follows.
2585 % o cube_info: A pointer to the Cube structure.
2587 % o node_info: pointer to node in color cube tree that is to be pruned.
2590 static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
2599 Traverse any children.
2601 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2602 for (i=0; i < (ssize_t) number_children; i++)
2603 if (node_info->child[i] != (NodeInfo *) NULL)
2604 PruneToCubeDepth(cube_info,node_info->child[i]);
2605 if (node_info->level > cube_info->depth)
2606 PruneChild(cube_info,node_info);
2610 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2614 % Q u a n t i z e I m a g e %
2618 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2620 % QuantizeImage() analyzes the colors within a reference image and chooses a
2621 % fixed number of colors to represent the image. The goal of the algorithm
2622 % is to minimize the color difference between the input and output image while
2623 % minimizing the processing time.
2625 % The format of the QuantizeImage method is:
2627 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2628 % Image *image,ExceptionInfo *exception)
2630 % A description of each parameter follows:
2632 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2634 % o image: the image.
2636 % o exception: return any errors or warnings in this structure.
2639 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2640 Image *image,ExceptionInfo *exception)
2652 assert(quantize_info != (const QuantizeInfo *) NULL);
2653 assert(quantize_info->signature == MagickCoreSignature);
2654 assert(image != (Image *) NULL);
2655 assert(image->signature == MagickCoreSignature);
2656 if (image->debug != MagickFalse)
2657 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2658 assert(exception != (ExceptionInfo *) NULL);
2659 assert(exception->signature == MagickCoreSignature);
2660 maximum_colors=quantize_info->number_colors;
2661 if (maximum_colors == 0)
2662 maximum_colors=MaxColormapSize;
2663 if (maximum_colors > MaxColormapSize)
2664 maximum_colors=MaxColormapSize;
2665 if (image->alpha_trait != BlendPixelTrait)
2667 if (SetImageGray(image,exception) != MagickFalse)
2668 (void) SetGrayscaleImage(image,exception);
2670 if ((image->storage_class == PseudoClass) &&
2671 (image->colors <= maximum_colors))
2673 if ((quantize_info->colorspace != UndefinedColorspace) &&
2674 (quantize_info->colorspace != CMYKColorspace))
2675 (void) TransformImageColorspace(image,quantize_info->colorspace,
2679 depth=quantize_info->tree_depth;
2686 Depth of color tree is: Log4(colormap size)+2.
2688 colors=maximum_colors;
2689 for (depth=1; colors != 0; depth++)
2691 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2693 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2695 if (SetImageGray(image,exception) != MagickFalse)
2699 Initialize color cube.
2701 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2702 if (cube_info == (CubeInfo *) NULL)
2703 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2705 status=ClassifyImageColors(cube_info,image,exception);
2706 if (status != MagickFalse)
2709 Reduce the number of colors in the image if it contains more than the
2710 maximum, otherwise we can disable dithering to improve the performance.
2712 if (cube_info->colors > cube_info->maximum_colors)
2713 ReduceImageColors(image,cube_info);
2715 cube_info->quantize_info->dither_method=NoDitherMethod;
2716 status=AssignImageColors(image,cube_info,exception);
2718 DestroyCubeInfo(cube_info);
2723 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2727 % Q u a n t i z e I m a g e s %
2731 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2733 % QuantizeImages() analyzes the colors within a set of reference images and
2734 % chooses a fixed number of colors to represent the set. The goal of the
2735 % algorithm is to minimize the color difference between the input and output
2736 % images while minimizing the processing time.
2738 % The format of the QuantizeImages method is:
2740 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2741 % Image *images,ExceptionInfo *exception)
2743 % A description of each parameter follows:
2745 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2747 % o images: Specifies a pointer to a list of Image structures.
2749 % o exception: return any errors or warnings in this structure.
2752 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2753 Image *images,ExceptionInfo *exception)
2765 MagickProgressMonitor
2776 assert(quantize_info != (const QuantizeInfo *) NULL);
2777 assert(quantize_info->signature == MagickCoreSignature);
2778 assert(images != (Image *) NULL);
2779 assert(images->signature == MagickCoreSignature);
2780 if (images->debug != MagickFalse)
2781 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2782 assert(exception != (ExceptionInfo *) NULL);
2783 assert(exception->signature == MagickCoreSignature);
2784 if (GetNextImageInList(images) == (Image *) NULL)
2787 Handle a single image with QuantizeImage.
2789 status=QuantizeImage(quantize_info,images,exception);
2793 maximum_colors=quantize_info->number_colors;
2794 if (maximum_colors == 0)
2795 maximum_colors=MaxColormapSize;
2796 if (maximum_colors > MaxColormapSize)
2797 maximum_colors=MaxColormapSize;
2798 depth=quantize_info->tree_depth;
2805 Depth of color tree is: Log4(colormap size)+2.
2807 colors=maximum_colors;
2808 for (depth=1; colors != 0; depth++)
2810 if (quantize_info->dither_method != NoDitherMethod)
2814 Initialize color cube.
2816 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2817 if (cube_info == (CubeInfo *) NULL)
2819 (void) ThrowMagickException(exception,GetMagickModule(),
2820 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2821 return(MagickFalse);
2823 number_images=GetImageListLength(images);
2825 for (i=0; image != (Image *) NULL; i++)
2827 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2828 image->client_data);
2829 status=ClassifyImageColors(cube_info,image,exception);
2830 if (status == MagickFalse)
2832 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2833 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2835 if (proceed == MagickFalse)
2837 image=GetNextImageInList(image);
2839 if (status != MagickFalse)
2842 Reduce the number of colors in an image sequence.
2844 ReduceImageColors(images,cube_info);
2846 for (i=0; image != (Image *) NULL; i++)
2848 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2849 NULL,image->client_data);
2850 status=AssignImageColors(image,cube_info,exception);
2851 if (status == MagickFalse)
2853 (void) SetImageProgressMonitor(image,progress_monitor,
2854 image->client_data);
2855 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2857 if (proceed == MagickFalse)
2859 image=GetNextImageInList(image);
2862 DestroyCubeInfo(cube_info);
2867 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2871 + Q u a n t i z e E r r o r F l a t t e n %
2875 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2877 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2878 % error into a sorted 1D array. This accelerates the color reduction process.
2880 % Contributed by Yoya.
2882 % The format of the QuantizeErrorFlatten method is:
2884 % size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
2885 % const NodeInfo *node_info,const ssize_t offset,
2886 % double *quantize_error)
2888 % A description of each parameter follows.
2890 % o cube_info: A pointer to the Cube structure.
2892 % o node_info: pointer to node in color cube tree that is current pointer.
2894 % o offset: quantize error offset.
2896 % o quantize_error: the quantization error vector.
2899 static size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
2900 const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
2909 if (offset >= (ssize_t) cube_info->nodes)
2911 quantize_error[offset]=node_info->quantize_error;
2913 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2914 for (i=0; i < (ssize_t) number_children ; i++)
2915 if (node_info->child[i] != (NodeInfo *) NULL)
2916 n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n,
2922 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2930 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2932 % Reduce() traverses the color cube tree and prunes any node whose
2933 % quantization error falls below a particular threshold.
2935 % The format of the Reduce method is:
2937 % Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
2939 % A description of each parameter follows.
2941 % o cube_info: A pointer to the Cube structure.
2943 % o node_info: pointer to node in color cube tree that is to be pruned.
2946 static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
2955 Traverse any children.
2957 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2958 for (i=0; i < (ssize_t) number_children; i++)
2959 if (node_info->child[i] != (NodeInfo *) NULL)
2960 Reduce(cube_info,node_info->child[i]);
2961 if (node_info->quantize_error <= cube_info->pruning_threshold)
2962 PruneChild(cube_info,node_info);
2966 Find minimum pruning threshold.
2968 if (node_info->number_unique > 0)
2969 cube_info->colors++;
2970 if (node_info->quantize_error < cube_info->next_threshold)
2971 cube_info->next_threshold=node_info->quantize_error;
2976 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2980 + R e d u c e I m a g e C o l o r s %
2984 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2986 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2987 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2988 % in the output image. On any given iteration over the tree, it selects
2989 % those nodes whose E value is minimal for pruning and merges their
2990 % color statistics upward. It uses a pruning threshold, Ep, to govern
2991 % node selection as follows:
2994 % while number of nodes with (n2 > 0) > required maximum number of colors
2995 % prune all nodes such that E <= Ep
2996 % Set Ep to minimum E in remaining nodes
2998 % This has the effect of minimizing any quantization error when merging
2999 % two nodes together.
3001 % When a node to be pruned has offspring, the pruning procedure invokes
3002 % itself recursively in order to prune the tree from the leaves upward.
3003 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3004 % corresponding data in that node's parent. This retains the pruned
3005 % node's color characteristics for later averaging.
3007 % For each node, n2 pixels exist for which that node represents the
3008 % smallest volume in RGB space containing those pixel's colors. When n2
3009 % > 0 the node will uniquely define a color in the output image. At the
3010 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3011 % the tree which represent colors present in the input image.
3013 % The other pixel count, n1, indicates the total number of colors
3014 % within the cubic volume which the node represents. This includes n1 -
3015 % n2 pixels whose colors should be defined by nodes at a lower level in
3018 % The format of the ReduceImageColors method is:
3020 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3022 % A description of each parameter follows.
3024 % o image: the image.
3026 % o cube_info: A pointer to the Cube structure.
3030 static int QuantizeErrorCompare(const void *error_p,const void *error_q)
3036 p=(double *) error_p;
3037 q=(double *) error_q;
3040 if (fabs(*q-*p) <= MagickEpsilon)
3045 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3047 #define ReduceImageTag "Reduce/Image"
3058 cube_info->next_threshold=0.0;
3059 if (cube_info->colors > cube_info->maximum_colors)
3065 Enable rapid reduction of the number of unique colors.
3067 quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
3068 sizeof(*quantize_error));
3069 if (quantize_error != (double *) NULL)
3071 (void) QuantizeErrorFlatten(cube_info,cube_info->root,0,
3073 qsort(quantize_error,cube_info->nodes,sizeof(double),
3074 QuantizeErrorCompare);
3075 if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
3076 cube_info->next_threshold=quantize_error[cube_info->nodes-110*
3077 (cube_info->maximum_colors+1)/100];
3078 quantize_error=(double *) RelinquishMagickMemory(quantize_error);
3081 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3083 cube_info->pruning_threshold=cube_info->next_threshold;
3084 cube_info->next_threshold=cube_info->root->quantize_error-1;
3085 cube_info->colors=0;
3086 Reduce(cube_info,cube_info->root);
3087 offset=(MagickOffsetType) span-cube_info->colors;
3088 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3089 cube_info->maximum_colors+1);
3090 if (proceed == MagickFalse)
3096 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3100 % R e m a p I m a g e %
3104 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3106 % RemapImage() replaces the colors of an image with the closest of the colors
3107 % from the reference image.
3109 % The format of the RemapImage method is:
3111 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3112 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3114 % A description of each parameter follows:
3116 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3118 % o image: the image.
3120 % o remap_image: the reference image.
3122 % o exception: return any errors or warnings in this structure.
3125 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3126 Image *image,const Image *remap_image,ExceptionInfo *exception)
3135 Initialize color cube.
3137 assert(image != (Image *) NULL);
3138 assert(image->signature == MagickCoreSignature);
3139 if (image->debug != MagickFalse)
3140 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3141 assert(remap_image != (Image *) NULL);
3142 assert(remap_image->signature == MagickCoreSignature);
3143 assert(exception != (ExceptionInfo *) NULL);
3144 assert(exception->signature == MagickCoreSignature);
3145 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3146 quantize_info->number_colors);
3147 if (cube_info == (CubeInfo *) NULL)
3148 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3150 status=ClassifyImageColors(cube_info,remap_image,exception);
3151 if (status != MagickFalse)
3154 Classify image colors from the reference image.
3156 cube_info->quantize_info->number_colors=cube_info->colors;
3157 status=AssignImageColors(image,cube_info,exception);
3159 DestroyCubeInfo(cube_info);
3164 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3168 % R e m a p I m a g e s %
3172 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3174 % RemapImages() replaces the colors of a sequence of images with the
3175 % closest color from a reference image.
3177 % The format of the RemapImage method is:
3179 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3180 % Image *images,Image *remap_image,ExceptionInfo *exception)
3182 % A description of each parameter follows:
3184 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3186 % o images: the image sequence.
3188 % o remap_image: the reference image.
3190 % o exception: return any errors or warnings in this structure.
3193 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3194 Image *images,const Image *remap_image,ExceptionInfo *exception)
3205 assert(images != (Image *) NULL);
3206 assert(images->signature == MagickCoreSignature);
3207 if (images->debug != MagickFalse)
3208 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3209 assert(exception != (ExceptionInfo *) NULL);
3210 assert(exception->signature == MagickCoreSignature);
3212 if (remap_image == (Image *) NULL)
3215 Create a global colormap for an image sequence.
3217 status=QuantizeImages(quantize_info,images,exception);
3221 Classify image colors from the reference image.
3223 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3224 quantize_info->number_colors);
3225 if (cube_info == (CubeInfo *) NULL)
3226 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3228 status=ClassifyImageColors(cube_info,remap_image,exception);
3229 if (status != MagickFalse)
3232 Classify image colors from the reference image.
3234 cube_info->quantize_info->number_colors=cube_info->colors;
3236 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3238 status=AssignImageColors(image,cube_info,exception);
3239 if (status == MagickFalse)
3243 DestroyCubeInfo(cube_info);
3248 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3252 % S e t G r a y s c a l e I m a g e %
3256 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3258 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3260 % The format of the SetGrayscaleImage method is:
3262 % MagickBooleanType SetGrayscaleImage(Image *image,
3263 % ExceptionInfo *exception)
3265 % A description of each parameter follows:
3267 % o image: The image.
3269 % o exception: return any errors or warnings in this structure.
3273 #if defined(__cplusplus) || defined(c_plusplus)
3277 static int IntensityCompare(const void *x,const void *y)
3286 color_1=(PixelInfo *) x;
3287 color_2=(PixelInfo *) y;
3288 intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
3289 GetPixelInfoIntensity((const Image *) NULL,color_2);
3290 return((int) intensity);
3293 #if defined(__cplusplus) || defined(c_plusplus)
3297 static MagickBooleanType SetGrayscaleImage(Image *image,
3298 ExceptionInfo *exception)
3317 assert(image != (Image *) NULL);
3318 assert(image->signature == MagickCoreSignature);
3319 if (image->type != GrayscaleType)
3320 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3321 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
3322 sizeof(*colormap_index));
3323 if (colormap_index == (ssize_t *) NULL)
3324 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3326 if (image->storage_class != PseudoClass)
3328 (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
3329 sizeof(*colormap_index));
3330 if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
3332 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3333 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3338 image_view=AcquireAuthenticCacheView(image,exception);
3339 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3340 #pragma omp parallel for schedule(static,4) shared(status) \
3341 magick_number_threads(image,image,image->rows,1)
3343 for (y=0; y < (ssize_t) image->rows; y++)
3351 if (status == MagickFalse)
3353 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3355 if (q == (Quantum *) NULL)
3360 for (x=0; x < (ssize_t) image->columns; x++)
3365 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3366 if (colormap_index[intensity] < 0)
3368 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3369 #pragma omp critical (MagickCore_SetGrayscaleImage)
3371 if (colormap_index[intensity] < 0)
3373 colormap_index[intensity]=(ssize_t) image->colors;
3374 image->colormap[image->colors].red=(double)
3375 GetPixelRed(image,q);
3376 image->colormap[image->colors].green=(double)
3377 GetPixelGreen(image,q);
3378 image->colormap[image->colors].blue=(double)
3379 GetPixelBlue(image,q);
3383 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3384 q+=GetPixelChannels(image);
3386 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3389 image_view=DestroyCacheView(image_view);
3391 for (i=0; i < (ssize_t) image->colors; i++)
3392 image->colormap[i].alpha=(double) i;
3393 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3395 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3396 if (colormap == (PixelInfo *) NULL)
3398 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3399 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3403 colormap[j]=image->colormap[0];
3404 for (i=0; i < (ssize_t) image->colors; i++)
3406 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3409 colormap[j]=image->colormap[i];
3411 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3413 image->colors=(size_t) (j+1);
3414 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3415 image->colormap=colormap;
3417 image_view=AcquireAuthenticCacheView(image,exception);
3418 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3419 #pragma omp parallel for schedule(static,4) shared(status) \
3420 magick_number_threads(image,image,image->rows,1)
3422 for (y=0; y < (ssize_t) image->rows; y++)
3430 if (status == MagickFalse)
3432 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3433 if (q == (Quantum *) NULL)
3438 for (x=0; x < (ssize_t) image->columns; x++)
3440 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3441 GetPixelIndex(image,q))],q);
3442 q+=GetPixelChannels(image);
3444 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3447 image_view=DestroyCacheView(image_view);
3448 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3449 image->type=GrayscaleType;
3450 if (SetImageMonochrome(image,exception) != MagickFalse)
3451 image->type=BilevelType;