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-2015 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 (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
114 % pixels 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/monitor.h"
193 #include "MagickCore/monitor-private.h"
194 #include "MagickCore/option.h"
195 #include "MagickCore/pixel-accessor.h"
196 #include "MagickCore/pixel-private.h"
197 #include "MagickCore/quantize.h"
198 #include "MagickCore/quantum.h"
199 #include "MagickCore/quantum-private.h"
200 #include "MagickCore/resource_.h"
201 #include "MagickCore/string_.h"
202 #include "MagickCore/thread-private.h"
207 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
212 #define ErrorQueueLength 16
213 #define MaxNodes 266817
214 #define MaxTreeDepth 8
215 #define NodesInAList 1920
220 typedef struct _RealPixelInfo
229 typedef struct _NodeInfo
250 typedef struct _Nodes
259 typedef struct _CubeInfo
300 error[ErrorQueueLength];
303 weights[ErrorQueueLength];
329 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
332 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
334 static MagickBooleanType
335 AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
336 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
337 DitherImage(Image *,CubeInfo *,ExceptionInfo *),
338 SetGrayscaleImage(Image *,ExceptionInfo *);
341 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
344 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
345 DestroyCubeInfo(CubeInfo *),
346 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
347 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
348 ReduceImageColors(const Image *,CubeInfo *);
351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
355 % A c q u i r e Q u a n t i z e I n f o %
359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
361 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
363 % The format of the AcquireQuantizeInfo method is:
365 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
367 % A description of each parameter follows:
369 % o image_info: the image info.
372 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
377 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
378 if (quantize_info == (QuantizeInfo *) NULL)
379 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
380 GetQuantizeInfo(quantize_info);
381 if (image_info != (ImageInfo *) NULL)
386 quantize_info->dither_method=image_info->dither == MagickFalse ?
387 NoDitherMethod : RiemersmaDitherMethod;
388 option=GetImageOption(image_info,"dither");
389 if (option != (const char *) NULL)
390 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
391 MagickDitherOptions,MagickFalse,option);
392 quantize_info->measure_error=image_info->verbose;
394 return(quantize_info);
398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
402 + A s s i g n I m a g e C o l o r s %
406 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
408 % AssignImageColors() generates the output image from the pruned tree. The
409 % output image consists of two parts: (1) A color map, which is an array
410 % of color descriptions (RGB triples) for each color present in the
411 % output image; (2) A pixel array, which represents each pixel as an
412 % index into the color map array.
414 % First, the assignment phase makes one pass over the pruned color
415 % description tree to establish the image's color map. For each node
416 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
417 % color of all pixels that classify no lower than this node. Each of
418 % these colors becomes an entry in the color map.
420 % Finally, the assignment phase reclassifies each pixel in the pruned
421 % tree to identify the deepest node containing the pixel's color. The
422 % pixel's value in the pixel array becomes the index of this node's mean
423 % color in the color map.
425 % The format of the AssignImageColors() method is:
427 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
429 % A description of each parameter follows.
431 % o image: the image.
433 % o cube_info: A pointer to the Cube structure.
437 static inline void AssociateAlphaPixel(const Image *image,
438 const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
443 if ((cube_info->associate_alpha == MagickFalse) ||
444 (GetPixelAlpha(image,pixel) == OpaqueAlpha))
446 alpha_pixel->red=(double) GetPixelRed(image,pixel);
447 alpha_pixel->green=(double) GetPixelGreen(image,pixel);
448 alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
449 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
452 alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
453 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
454 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
455 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
456 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
459 static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
460 const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
465 if ((cube_info->associate_alpha == MagickFalse) ||
466 (pixel->alpha == OpaqueAlpha))
468 alpha_pixel->red=(double) pixel->red;
469 alpha_pixel->green=(double) pixel->green;
470 alpha_pixel->blue=(double) pixel->blue;
471 alpha_pixel->alpha=(double) pixel->alpha;
474 alpha=(double) (QuantumScale*pixel->alpha);
475 alpha_pixel->red=alpha*pixel->red;
476 alpha_pixel->green=alpha*pixel->green;
477 alpha_pixel->blue=alpha*pixel->blue;
478 alpha_pixel->alpha=(double) pixel->alpha;
481 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
482 const RealPixelInfo *pixel,size_t index)
487 id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
488 ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
489 ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
490 if (cube_info->associate_alpha != MagickFalse)
491 id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
495 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
496 ExceptionInfo *exception)
498 #define AssignImageTag "Assign/Image"
504 Allocate image colormap.
506 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
507 (cube_info->quantize_info->colorspace != CMYKColorspace))
508 (void) TransformImageColorspace((Image *) image,
509 cube_info->quantize_info->colorspace,exception);
511 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
512 (void) TransformImageColorspace((Image *) image,sRGBColorspace,
514 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
515 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
518 cube_info->transparent_pixels=0;
519 cube_info->transparent_index=(-1);
520 (void) DefineImageColormap(image,cube_info,cube_info->root);
522 Create a reduced color image.
524 if (cube_info->quantize_info->dither_method != NoDitherMethod)
525 (void) DitherImage(image,cube_info,exception);
535 image_view=AcquireAuthenticCacheView(image,exception);
536 #if defined(MAGICKCORE_OPENMP_SUPPORT)
537 #pragma omp parallel for schedule(static,4) shared(status) \
538 magick_threads(image,image,image->rows,1)
540 for (y=0; y < (ssize_t) image->rows; y++)
554 if (status == MagickFalse)
556 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
558 if (q == (Quantum *) NULL)
564 for (x=0; x < (ssize_t) image->columns; x+=count)
569 register const NodeInfo
580 Identify the deepest node containing the pixel's color.
582 for (count=1; (x+count) < (ssize_t) image->columns; count++)
587 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
588 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
591 AssociateAlphaPixel(image,&cube,q,&pixel);
593 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
595 id=ColorToNodeId(&cube,&pixel,index);
596 if (node_info->child[id] == (NodeInfo *) NULL)
598 node_info=node_info->child[id];
601 Find closest color among siblings and their children.
604 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
606 ClosestColor(image,&cube,node_info->parent);
607 index=cube.color_number;
608 for (i=0; i < (ssize_t) count; i++)
610 if (image->storage_class == PseudoClass)
611 SetPixelIndex(image,(Quantum) index,q);
612 if (cube.quantize_info->measure_error == MagickFalse)
614 SetPixelRed(image,ClampToQuantum(
615 image->colormap[index].red),q);
616 SetPixelGreen(image,ClampToQuantum(
617 image->colormap[index].green),q);
618 SetPixelBlue(image,ClampToQuantum(
619 image->colormap[index].blue),q);
620 if (cube.associate_alpha != MagickFalse)
621 SetPixelAlpha(image,ClampToQuantum(
622 image->colormap[index].alpha),q);
624 q+=GetPixelChannels(image);
627 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
629 if (image->progress_monitor != (MagickProgressMonitor) NULL)
634 #if defined(MAGICKCORE_OPENMP_SUPPORT)
635 #pragma omp critical (MagickCore_AssignImageColors)
637 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
639 if (proceed == MagickFalse)
643 image_view=DestroyCacheView(image_view);
645 if (cube_info->quantize_info->measure_error != MagickFalse)
646 (void) GetImageQuantizeError(image,exception);
647 if ((cube_info->quantize_info->number_colors == 2) &&
648 (cube_info->quantize_info->colorspace == GRAYColorspace))
663 for (i=0; i < (ssize_t) image->colors; i++)
665 intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
673 (void) SyncImage(image,exception);
674 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
675 (cube_info->quantize_info->colorspace != CMYKColorspace))
676 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
681 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
685 + C l a s s i f y I m a g e C o l o r s %
689 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
691 % ClassifyImageColors() begins by initializing a color description tree
692 % of sufficient depth to represent each possible input color in a leaf.
693 % However, it is impractical to generate a fully-formed color
694 % description tree in the storage_class phase for realistic values of
695 % Cmax. If colors components in the input image are quantized to k-bit
696 % precision, so that Cmax= 2k-1, the tree would need k levels below the
697 % root node to allow representing each possible input color in a leaf.
698 % This becomes prohibitive because the tree's total number of nodes is
701 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
702 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
703 % Initializes data structures for nodes only as they are needed; (2)
704 % Chooses a maximum depth for the tree as a function of the desired
705 % number of colors in the output image (currently log2(colormap size)).
707 % For each pixel in the input image, storage_class scans downward from
708 % the root of the color description tree. At each level of the tree it
709 % identifies the single node which represents a cube in RGB space
710 % containing It updates the following data for each such node:
712 % n1 : Number of pixels whose color is contained in the RGB cube
713 % which this node represents;
715 % n2 : Number of pixels whose color is not represented in a node at
716 % lower depth in the tree; initially, n2 = 0 for all nodes except
717 % leaves of the tree.
719 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
720 % all pixels not classified at a lower depth. The combination of
721 % these sums and n2 will ultimately characterize the mean color of a
722 % set of pixels represented by this node.
724 % E: the distance squared in RGB space between each pixel contained
725 % within a node and the nodes' center. This represents the quantization
728 % The format of the ClassifyImageColors() method is:
730 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
731 % const Image *image,ExceptionInfo *exception)
733 % A description of each parameter follows.
735 % o cube_info: A pointer to the Cube structure.
737 % o image: the image.
741 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
746 associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
748 if ((cube_info->quantize_info->number_colors == 2) &&
749 (cube_info->quantize_info->colorspace == GRAYColorspace))
750 associate_alpha=MagickFalse;
751 cube_info->associate_alpha=associate_alpha;
754 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
755 const Image *image,ExceptionInfo *exception)
757 #define ClassifyImageTag "Classify/Image"
787 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
789 SetAssociatedAlpha(image,cube_info);
790 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
791 (cube_info->quantize_info->colorspace != CMYKColorspace))
792 (void) TransformImageColorspace((Image *) image,
793 cube_info->quantize_info->colorspace,exception);
795 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
796 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
797 midpoint.red=(double) QuantumRange/2.0;
798 midpoint.green=(double) QuantumRange/2.0;
799 midpoint.blue=(double) QuantumRange/2.0;
800 midpoint.alpha=(double) QuantumRange/2.0;
802 image_view=AcquireVirtualCacheView(image,exception);
803 for (y=0; y < (ssize_t) image->rows; y++)
805 register const Quantum
811 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
812 if (p == (const Quantum *) NULL)
814 if (cube_info->nodes > MaxNodes)
817 Prune one level if the color tree is too large.
819 PruneLevel(image,cube_info,cube_info->root);
822 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
825 Start at the root and descend the color cube tree.
827 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
832 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
833 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
836 AssociateAlphaPixel(image,cube_info,p,&pixel);
837 index=MaxTreeDepth-1;
838 bisect=((double) QuantumRange+1.0)/2.0;
840 node_info=cube_info->root;
841 for (level=1; level <= MaxTreeDepth; level++)
847 id=ColorToNodeId(cube_info,&pixel,index);
848 mid.red+=(id & 1) != 0 ? bisect : -bisect;
849 mid.green+=(id & 2) != 0 ? bisect : -bisect;
850 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
851 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
852 if (node_info->child[id] == (NodeInfo *) NULL)
855 Set colors of new node to contain pixel.
857 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
858 if (node_info->child[id] == (NodeInfo *) NULL)
860 (void) ThrowMagickException(exception,GetMagickModule(),
861 ResourceLimitError,"MemoryAllocationFailed","`%s'",
865 if (level == MaxTreeDepth)
869 Approximate the quantization error represented by this node.
871 node_info=node_info->child[id];
872 error.red=QuantumScale*(pixel.red-mid.red);
873 error.green=QuantumScale*(pixel.green-mid.green);
874 error.blue=QuantumScale*(pixel.blue-mid.blue);
875 if (cube_info->associate_alpha != MagickFalse)
876 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
877 distance=(double) (error.red*error.red+error.green*error.green+
878 error.blue*error.blue+error.alpha*error.alpha);
879 if (IsNaN(distance) != MagickFalse)
881 node_info->quantize_error+=count*sqrt(distance);
882 cube_info->root->quantize_error+=node_info->quantize_error;
886 Sum RGB for this leaf for later derivation of the mean cube color.
888 node_info->number_unique+=count;
889 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
890 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
891 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
892 if (cube_info->associate_alpha != MagickFalse)
893 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
895 p+=count*GetPixelChannels(image);
897 if (cube_info->colors > cube_info->maximum_colors)
899 PruneToCubeDepth(image,cube_info,cube_info->root);
902 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
904 if (proceed == MagickFalse)
907 for (y++; y < (ssize_t) image->rows; y++)
909 register const Quantum
915 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
916 if (p == (const Quantum *) NULL)
918 if (cube_info->nodes > MaxNodes)
921 Prune one level if the color tree is too large.
923 PruneLevel(image,cube_info,cube_info->root);
926 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
929 Start at the root and descend the color cube tree.
931 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
936 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
937 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
940 AssociateAlphaPixel(image,cube_info,p,&pixel);
941 index=MaxTreeDepth-1;
942 bisect=((double) QuantumRange+1.0)/2.0;
944 node_info=cube_info->root;
945 for (level=1; level <= cube_info->depth; level++)
951 id=ColorToNodeId(cube_info,&pixel,index);
952 mid.red+=(id & 1) != 0 ? bisect : -bisect;
953 mid.green+=(id & 2) != 0 ? bisect : -bisect;
954 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
955 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
956 if (node_info->child[id] == (NodeInfo *) NULL)
959 Set colors of new node to contain pixel.
961 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
962 if (node_info->child[id] == (NodeInfo *) NULL)
964 (void) ThrowMagickException(exception,GetMagickModule(),
965 ResourceLimitError,"MemoryAllocationFailed","%s",
969 if (level == cube_info->depth)
973 Approximate the quantization error represented by this node.
975 node_info=node_info->child[id];
976 error.red=QuantumScale*(pixel.red-mid.red);
977 error.green=QuantumScale*(pixel.green-mid.green);
978 error.blue=QuantumScale*(pixel.blue-mid.blue);
979 if (cube_info->associate_alpha != MagickFalse)
980 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
981 distance=(double) (error.red*error.red+error.green*error.green+
982 error.blue*error.blue+error.alpha*error.alpha);
983 if (IsNaN(distance) != MagickFalse)
985 node_info->quantize_error+=count*sqrt(distance);
986 cube_info->root->quantize_error+=node_info->quantize_error;
990 Sum RGB for this leaf for later derivation of the mean cube color.
992 node_info->number_unique+=count;
993 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
994 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
995 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
996 if (cube_info->associate_alpha != MagickFalse)
997 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
999 p+=count*GetPixelChannels(image);
1001 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1003 if (proceed == MagickFalse)
1006 image_view=DestroyCacheView(image_view);
1007 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1008 (cube_info->quantize_info->colorspace != CMYKColorspace))
1009 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1010 return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1014 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1018 % C l o n e Q u a n t i z e I n f o %
1022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1024 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1025 % or if quantize info is NULL, a new one.
1027 % The format of the CloneQuantizeInfo method is:
1029 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1031 % A description of each parameter follows:
1033 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1034 % quantize info, or if image info is NULL a new one.
1036 % o quantize_info: a structure of type info.
1039 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1044 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1045 if (clone_info == (QuantizeInfo *) NULL)
1046 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1047 GetQuantizeInfo(clone_info);
1048 if (quantize_info == (QuantizeInfo *) NULL)
1050 clone_info->number_colors=quantize_info->number_colors;
1051 clone_info->tree_depth=quantize_info->tree_depth;
1052 clone_info->dither_method=quantize_info->dither_method;
1053 clone_info->colorspace=quantize_info->colorspace;
1054 clone_info->measure_error=quantize_info->measure_error;
1059 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1063 + C l o s e s t C o l o r %
1067 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1069 % ClosestColor() traverses the color cube tree at a particular node and
1070 % determines which colormap entry best represents the input color.
1072 % The format of the ClosestColor method is:
1074 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1075 % const NodeInfo *node_info)
1077 % A description of each parameter follows.
1079 % o image: the image.
1081 % o cube_info: A pointer to the Cube structure.
1083 % o node_info: the address of a structure of type NodeInfo which points to a
1084 % node in the color cube tree that is to be pruned.
1087 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1088 const NodeInfo *node_info)
1097 Traverse any children.
1099 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1100 for (i=0; i < (ssize_t) number_children; i++)
1101 if (node_info->child[i] != (NodeInfo *) NULL)
1102 ClosestColor(image,cube_info,node_info->child[i]);
1103 if (node_info->number_unique != 0)
1116 register RealPixelInfo
1120 Determine if this color is "closest".
1122 p=image->colormap+node_info->color_number;
1123 q=(&cube_info->target);
1126 if (cube_info->associate_alpha != MagickFalse)
1128 alpha=(double) (QuantumScale*p->alpha);
1129 beta=(double) (QuantumScale*q->alpha);
1131 pixel=alpha*p->red-beta*q->red;
1132 distance=pixel*pixel;
1133 if (distance <= cube_info->distance)
1135 pixel=alpha*p->green-beta*q->green;
1136 distance+=pixel*pixel;
1137 if (distance <= cube_info->distance)
1139 pixel=alpha*p->blue-beta*q->blue;
1140 distance+=pixel*pixel;
1141 if (distance <= cube_info->distance)
1144 distance+=pixel*pixel;
1145 if (distance <= cube_info->distance)
1147 cube_info->distance=distance;
1148 cube_info->color_number=node_info->color_number;
1157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1161 % C o m p r e s s I m a g e C o l o r m a p %
1165 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1167 % CompressImageColormap() compresses an image colormap by removing any
1168 % duplicate or unused color entries.
1170 % The format of the CompressImageColormap method is:
1172 % MagickBooleanType CompressImageColormap(Image *image,
1173 % ExceptionInfo *exception)
1175 % A description of each parameter follows:
1177 % o image: the image.
1179 % o exception: return any errors or warnings in this structure.
1182 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1183 ExceptionInfo *exception)
1188 assert(image != (Image *) NULL);
1189 assert(image->signature == MagickCoreSignature);
1190 if (image->debug != MagickFalse)
1191 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1192 if (IsPaletteImage(image,exception) == MagickFalse)
1193 return(MagickFalse);
1194 GetQuantizeInfo(&quantize_info);
1195 quantize_info.number_colors=image->colors;
1196 quantize_info.tree_depth=MaxTreeDepth;
1197 return(QuantizeImage(&quantize_info,image,exception));
1201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1205 + D e f i n e I m a g e C o l o r m a p %
1209 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1211 % DefineImageColormap() traverses the color cube tree and notes each colormap
1212 % entry. A colormap entry is any node in the color cube tree where the
1213 % of unique colors is not zero. DefineImageColormap() returns the number of
1214 % colors in the image colormap.
1216 % The format of the DefineImageColormap method is:
1218 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1219 % NodeInfo *node_info)
1221 % A description of each parameter follows.
1223 % o image: the image.
1225 % o cube_info: A pointer to the Cube structure.
1227 % o node_info: the address of a structure of type NodeInfo which points to a
1228 % node in the color cube tree that is to be pruned.
1231 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1232 NodeInfo *node_info)
1241 Traverse any children.
1243 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1244 for (i=0; i < (ssize_t) number_children; i++)
1245 if (node_info->child[i] != (NodeInfo *) NULL)
1246 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1247 if (node_info->number_unique != 0)
1256 Colormap entry is defined by the mean color in this cube.
1258 q=image->colormap+image->colors;
1259 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1260 alpha=PerceptibleReciprocal(alpha);
1261 if (cube_info->associate_alpha == MagickFalse)
1263 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1264 node_info->total_color.red);
1265 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1266 node_info->total_color.green);
1267 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1268 node_info->total_color.blue);
1269 q->alpha=(double) OpaqueAlpha;
1276 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1277 q->alpha=(double) ClampToQuantum(opacity);
1278 if (q->alpha == OpaqueAlpha)
1280 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1281 node_info->total_color.red);
1282 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1283 node_info->total_color.green);
1284 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1285 node_info->total_color.blue);
1292 gamma=(double) (QuantumScale*q->alpha);
1293 gamma=PerceptibleReciprocal(gamma);
1294 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1295 node_info->total_color.red);
1296 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1297 node_info->total_color.green);
1298 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1299 node_info->total_color.blue);
1300 if (node_info->number_unique > cube_info->transparent_pixels)
1302 cube_info->transparent_pixels=node_info->number_unique;
1303 cube_info->transparent_index=(ssize_t) image->colors;
1307 node_info->color_number=image->colors++;
1309 return(image->colors);
1313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1317 + D e s t r o y C u b e I n f o %
1321 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1323 % DestroyCubeInfo() deallocates memory associated with an image.
1325 % The format of the DestroyCubeInfo method is:
1327 % DestroyCubeInfo(CubeInfo *cube_info)
1329 % A description of each parameter follows:
1331 % o cube_info: the address of a structure of type CubeInfo.
1334 static void DestroyCubeInfo(CubeInfo *cube_info)
1340 Release color cube tree storage.
1344 nodes=cube_info->node_queue->next;
1345 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1346 cube_info->node_queue->nodes);
1347 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1348 cube_info->node_queue);
1349 cube_info->node_queue=nodes;
1350 } while (cube_info->node_queue != (Nodes *) NULL);
1351 if (cube_info->memory_info != (MemoryInfo *) NULL)
1352 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1353 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1354 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1358 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1362 % D e s t r o y Q u a n t i z e I n f o %
1366 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1368 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1371 % The format of the DestroyQuantizeInfo method is:
1373 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1375 % A description of each parameter follows:
1377 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1380 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1382 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1383 assert(quantize_info != (QuantizeInfo *) NULL);
1384 assert(quantize_info->signature == MagickCoreSignature);
1385 quantize_info->signature=(~MagickCoreSignature);
1386 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1387 return(quantize_info);
1391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1395 + D i t h e r I m a g e %
1399 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1401 % DitherImage() distributes the difference between an original image and
1402 % the corresponding color reduced algorithm to neighboring pixels using
1403 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1404 % MagickTrue if the image is dithered otherwise MagickFalse.
1406 % The format of the DitherImage method is:
1408 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1409 % ExceptionInfo *exception)
1411 % A description of each parameter follows.
1413 % o image: the image.
1415 % o cube_info: A pointer to the Cube structure.
1417 % o exception: return any errors or warnings in this structure.
1421 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1426 assert(pixels != (RealPixelInfo **) NULL);
1427 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1428 if (pixels[i] != (RealPixelInfo *) NULL)
1429 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1430 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1434 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1445 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1446 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1448 if (pixels == (RealPixelInfo **) NULL)
1449 return((RealPixelInfo **) NULL);
1450 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1451 for (i=0; i < (ssize_t) number_threads; i++)
1453 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1454 if (pixels[i] == (RealPixelInfo *) NULL)
1455 return(DestroyPixelThreadSet(pixels));
1460 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1461 const RealPixelInfo *pixel)
1463 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1464 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1465 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1466 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1471 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1472 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1473 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1474 if (cube_info->associate_alpha != MagickFalse)
1475 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1479 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1480 ExceptionInfo *exception)
1482 #define DitherImageTag "Dither/Image"
1497 Distribute quantization error using Floyd-Steinberg.
1499 pixels=AcquirePixelThreadSet(image->columns);
1500 if (pixels == (RealPixelInfo **) NULL)
1501 return(MagickFalse);
1503 image_view=AcquireAuthenticCacheView(image,exception);
1504 for (y=0; y < (ssize_t) image->rows; y++)
1507 id = GetOpenMPThreadId();
1528 if (status == MagickFalse)
1530 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1531 if (q == (Quantum *) NULL)
1537 current=pixels[id]+(y & 0x01)*image->columns;
1538 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1539 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1540 for (x=0; x < (ssize_t) image->columns; x++)
1552 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1553 AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel);
1556 pixel.red+=7*current[u-v].red/16;
1557 pixel.green+=7*current[u-v].green/16;
1558 pixel.blue+=7*current[u-v].blue/16;
1559 if (cube.associate_alpha != MagickFalse)
1560 pixel.alpha+=7*current[u-v].alpha/16;
1564 if (x < (ssize_t) (image->columns-1))
1566 pixel.red+=previous[u+v].red/16;
1567 pixel.green+=previous[u+v].green/16;
1568 pixel.blue+=previous[u+v].blue/16;
1569 if (cube.associate_alpha != MagickFalse)
1570 pixel.alpha+=previous[u+v].alpha/16;
1572 pixel.red+=5*previous[u].red/16;
1573 pixel.green+=5*previous[u].green/16;
1574 pixel.blue+=5*previous[u].blue/16;
1575 if (cube.associate_alpha != MagickFalse)
1576 pixel.alpha+=5*previous[u].alpha/16;
1579 pixel.red+=3*previous[u-v].red/16;
1580 pixel.green+=3*previous[u-v].green/16;
1581 pixel.blue+=3*previous[u-v].blue/16;
1582 if (cube.associate_alpha != MagickFalse)
1583 pixel.alpha+=3*previous[u-v].alpha/16;
1586 pixel.red=(double) ClampPixel(pixel.red);
1587 pixel.green=(double) ClampPixel(pixel.green);
1588 pixel.blue=(double) ClampPixel(pixel.blue);
1589 if (cube.associate_alpha != MagickFalse)
1590 pixel.alpha=(double) ClampPixel(pixel.alpha);
1591 i=CacheOffset(&cube,&pixel);
1592 if (cube.cache[i] < 0)
1601 Identify the deepest node containing the pixel's color.
1603 node_info=cube.root;
1604 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1606 id=ColorToNodeId(&cube,&pixel,index);
1607 if (node_info->child[id] == (NodeInfo *) NULL)
1609 node_info=node_info->child[id];
1612 Find closest color among siblings and their children.
1615 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1617 ClosestColor(image,&cube,node_info->parent);
1618 cube.cache[i]=(ssize_t) cube.color_number;
1621 Assign pixel to closest colormap entry.
1623 index=(size_t) cube.cache[i];
1624 if (image->storage_class == PseudoClass)
1625 SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image));
1626 if (cube.quantize_info->measure_error == MagickFalse)
1628 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),
1629 q+u*GetPixelChannels(image));
1630 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),
1631 q+u*GetPixelChannels(image));
1632 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),
1633 q+u*GetPixelChannels(image));
1634 if (cube.associate_alpha != MagickFalse)
1635 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),
1636 q+u*GetPixelChannels(image));
1638 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1643 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1644 current[u].red=pixel.red-color.red;
1645 current[u].green=pixel.green-color.green;
1646 current[u].blue=pixel.blue-color.blue;
1647 if (cube.associate_alpha != MagickFalse)
1648 current[u].alpha=pixel.alpha-color.alpha;
1649 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1654 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1656 if (proceed == MagickFalse)
1661 image_view=DestroyCacheView(image_view);
1662 pixels=DestroyPixelThreadSet(pixels);
1666 static MagickBooleanType
1667 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1670 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1671 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1678 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1680 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1682 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1688 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1690 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1692 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1698 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1700 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1702 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1710 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1712 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1724 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1726 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1728 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1730 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1732 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1734 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1736 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1742 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1744 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1746 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1748 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1750 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1752 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1754 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1760 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1762 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1764 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1766 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1768 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1770 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1772 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1778 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1780 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1782 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1784 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1786 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1788 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1790 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1799 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1800 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1802 #define DitherImageTag "Dither/Image"
1818 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1819 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1830 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1831 if (q == (Quantum *) NULL)
1832 return(MagickFalse);
1833 AssociateAlphaPixel(image,cube_info,q,&pixel);
1834 for (i=0; i < ErrorQueueLength; i++)
1836 pixel.red+=p->weights[i]*p->error[i].red;
1837 pixel.green+=p->weights[i]*p->error[i].green;
1838 pixel.blue+=p->weights[i]*p->error[i].blue;
1839 if (cube_info->associate_alpha != MagickFalse)
1840 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1842 pixel.red=(double) ClampPixel(pixel.red);
1843 pixel.green=(double) ClampPixel(pixel.green);
1844 pixel.blue=(double) ClampPixel(pixel.blue);
1845 if (cube_info->associate_alpha != MagickFalse)
1846 pixel.alpha=(double) ClampPixel(pixel.alpha);
1847 i=CacheOffset(cube_info,&pixel);
1848 if (p->cache[i] < 0)
1857 Identify the deepest node containing the pixel's color.
1860 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1862 id=ColorToNodeId(cube_info,&pixel,index);
1863 if (node_info->child[id] == (NodeInfo *) NULL)
1865 node_info=node_info->child[id];
1868 Find closest color among siblings and their children.
1871 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1872 QuantumRange+1.0)+1.0);
1873 ClosestColor(image,p,node_info->parent);
1874 p->cache[i]=(ssize_t) p->color_number;
1877 Assign pixel to closest colormap entry.
1879 index=(size_t) p->cache[i];
1880 if (image->storage_class == PseudoClass)
1881 SetPixelIndex(image,(Quantum) index,q);
1882 if (cube_info->quantize_info->measure_error == MagickFalse)
1884 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1885 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1886 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1887 if (cube_info->associate_alpha != MagickFalse)
1888 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1890 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1891 return(MagickFalse);
1893 Propagate the error as the last entry of the error queue.
1895 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1896 sizeof(p->error[0]));
1897 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1898 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1899 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1900 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1901 if (cube_info->associate_alpha != MagickFalse)
1902 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1903 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1904 if (proceed == MagickFalse)
1905 return(MagickFalse);
1910 case WestGravity: p->x--; break;
1911 case EastGravity: p->x++; break;
1912 case NorthGravity: p->y--; break;
1913 case SouthGravity: p->y++; break;
1918 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1919 ExceptionInfo *exception)
1933 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1934 return(FloydSteinbergDither(image,cube_info,exception));
1936 Distribute quantization error along a Hilbert curve.
1938 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1939 sizeof(*cube_info->error));
1942 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1943 for (depth=1; i != 0; depth++)
1945 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1947 cube_info->offset=0;
1948 cube_info->span=(MagickSizeType) image->columns*image->rows;
1949 image_view=AcquireAuthenticCacheView(image,exception);
1951 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1952 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1953 image_view=DestroyCacheView(image_view);
1958 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1962 + G e t C u b e I n f o %
1966 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1968 % GetCubeInfo() initialize the Cube data structure.
1970 % The format of the GetCubeInfo method is:
1972 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1973 % const size_t depth,const size_t maximum_colors)
1975 % A description of each parameter follows.
1977 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1979 % o depth: Normally, this integer value is zero or one. A zero or
1980 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1981 % A tree of this depth generally allows the best representation of the
1982 % reference image with the least amount of memory and the fastest
1983 % computational speed. In some cases, such as an image with low color
1984 % dispersion (a few number of colors), a value other than
1985 % Log4(number_colors) is required. To expand the color tree completely,
1988 % o maximum_colors: maximum colors.
1991 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1992 const size_t depth,const size_t maximum_colors)
2008 Initialize tree to describe color cube_info.
2010 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2011 if (cube_info == (CubeInfo *) NULL)
2012 return((CubeInfo *) NULL);
2013 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2014 cube_info->depth=depth;
2015 if (cube_info->depth > MaxTreeDepth)
2016 cube_info->depth=MaxTreeDepth;
2017 if (cube_info->depth < 2)
2019 cube_info->maximum_colors=maximum_colors;
2021 Initialize root node.
2023 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2024 if (cube_info->root == (NodeInfo *) NULL)
2025 return((CubeInfo *) NULL);
2026 cube_info->root->parent=cube_info->root;
2027 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2028 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2031 Initialize dither resources.
2033 length=(size_t) (1UL << (4*(8-CacheShift)));
2034 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2035 if (cube_info->memory_info == (MemoryInfo *) NULL)
2036 return((CubeInfo *) NULL);
2037 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2039 Initialize color cache.
2041 (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)*
2044 Distribute weights along a curve of exponential decay.
2047 for (i=0; i < ErrorQueueLength; i++)
2049 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2050 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2053 Normalize the weighting factors.
2056 for (i=0; i < ErrorQueueLength; i++)
2057 weight+=cube_info->weights[i];
2059 for (i=0; i < ErrorQueueLength; i++)
2061 cube_info->weights[i]/=weight;
2062 sum+=cube_info->weights[i];
2064 cube_info->weights[0]+=1.0-sum;
2069 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2073 + G e t N o d e I n f o %
2077 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2079 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2080 % presets all fields to zero.
2082 % The format of the GetNodeInfo method is:
2084 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2085 % const size_t level,NodeInfo *parent)
2087 % A description of each parameter follows.
2089 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2091 % o id: Specifies the child number of the node.
2093 % o level: Specifies the level in the storage_class the node resides.
2096 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2097 const size_t level,NodeInfo *parent)
2102 if (cube_info->free_nodes == 0)
2108 Allocate a new queue of nodes.
2110 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2111 if (nodes == (Nodes *) NULL)
2112 return((NodeInfo *) NULL);
2113 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2114 sizeof(*nodes->nodes));
2115 if (nodes->nodes == (NodeInfo *) NULL)
2116 return((NodeInfo *) NULL);
2117 nodes->next=cube_info->node_queue;
2118 cube_info->node_queue=nodes;
2119 cube_info->next_node=nodes->nodes;
2120 cube_info->free_nodes=NodesInAList;
2123 cube_info->free_nodes--;
2124 node_info=cube_info->next_node++;
2125 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2126 node_info->parent=parent;
2128 node_info->level=level;
2133 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2137 % G e t I m a g e Q u a n t i z e E r r o r %
2141 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2143 % GetImageQuantizeError() measures the difference between the original
2144 % and quantized images. This difference is the total quantization error.
2145 % The error is computed by summing over all pixels in an image the distance
2146 % squared in RGB space between each reference pixel value and its quantized
2147 % value. These values are computed:
2149 % o mean_error_per_pixel: This value is the mean error for any single
2150 % pixel in the image.
2152 % o normalized_mean_square_error: This value is the normalized mean
2153 % quantization error for any single pixel in the image. This distance
2154 % measure is normalized to a range between 0 and 1. It is independent
2155 % of the range of red, green, and blue values in the image.
2157 % o normalized_maximum_square_error: Thsi value is the normalized
2158 % maximum quantization error for any single pixel in the image. This
2159 % distance measure is normalized to a range between 0 and 1. It is
2160 % independent of the range of red, green, and blue values in your image.
2162 % The format of the GetImageQuantizeError method is:
2164 % MagickBooleanType GetImageQuantizeError(Image *image,
2165 % ExceptionInfo *exception)
2167 % A description of each parameter follows.
2169 % o image: the image.
2171 % o exception: return any errors or warnings in this structure.
2174 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2175 ExceptionInfo *exception)
2187 mean_error_per_pixel;
2195 assert(image != (Image *) NULL);
2196 assert(image->signature == MagickCoreSignature);
2197 if (image->debug != MagickFalse)
2198 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2199 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2200 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2201 if (image->storage_class == DirectClass)
2205 area=3.0*image->columns*image->rows;
2207 mean_error_per_pixel=0.0;
2209 image_view=AcquireVirtualCacheView(image,exception);
2210 for (y=0; y < (ssize_t) image->rows; y++)
2212 register const Quantum
2218 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2219 if (p == (const Quantum *) NULL)
2221 for (x=0; x < (ssize_t) image->columns; x++)
2223 index=GetPixelIndex(image,p);
2224 if (image->alpha_trait == BlendPixelTrait)
2226 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2227 beta=(double) (QuantumScale*image->colormap[index].alpha);
2229 distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
2230 image->colormap[index].red));
2231 mean_error_per_pixel+=distance;
2232 mean_error+=distance*distance;
2233 if (distance > maximum_error)
2234 maximum_error=distance;
2235 distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
2236 image->colormap[index].green));
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*GetPixelBlue(image,p)-beta*
2242 image->colormap[index].blue));
2243 mean_error_per_pixel+=distance;
2244 mean_error+=distance*distance;
2245 if (distance > maximum_error)
2246 maximum_error=distance;
2247 p+=GetPixelChannels(image);
2250 image_view=DestroyCacheView(image_view);
2251 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2252 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2254 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2259 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2263 % G e t Q u a n t i z e I n f o %
2267 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2269 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2271 % The format of the GetQuantizeInfo method is:
2273 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2275 % A description of each parameter follows:
2277 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2280 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2282 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2283 assert(quantize_info != (QuantizeInfo *) NULL);
2284 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2285 quantize_info->number_colors=256;
2286 quantize_info->dither_method=RiemersmaDitherMethod;
2287 quantize_info->colorspace=UndefinedColorspace;
2288 quantize_info->measure_error=MagickFalse;
2289 quantize_info->signature=MagickCoreSignature;
2293 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2297 % P o s t e r i z e I m a g e %
2301 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2303 % PosterizeImage() reduces the image to a limited number of colors for a
2306 % The format of the PosterizeImage method is:
2308 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2309 % const DitherMethod dither_method,ExceptionInfo *exception)
2311 % A description of each parameter follows:
2313 % o image: Specifies a pointer to an Image structure.
2315 % o levels: Number of color levels allowed in each channel. Very low values
2316 % (2, 3, or 4) have the most visible effect.
2318 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2319 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2321 % o exception: return any errors or warnings in this structure.
2325 static inline double MagickRound(double x)
2328 Round the fraction to nearest integer.
2330 if ((x-floor(x)) < (ceil(x)-x))
2335 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2336 const DitherMethod dither_method,ExceptionInfo *exception)
2338 #define PosterizeImageTag "Posterize/Image"
2339 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2340 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2360 assert(image != (Image *) NULL);
2361 assert(image->signature == MagickCoreSignature);
2362 if (image->debug != MagickFalse)
2363 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2364 assert(exception != (ExceptionInfo *) NULL);
2365 assert(exception->signature == MagickCoreSignature);
2366 if (image->storage_class == PseudoClass)
2367 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2368 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2369 magick_threads(image,image,1,1)
2371 for (i=0; i < (ssize_t) image->colors; i++)
2376 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2377 image->colormap[i].red=(double)
2378 PosterizePixel(image->colormap[i].red);
2379 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2380 image->colormap[i].green=(double)
2381 PosterizePixel(image->colormap[i].green);
2382 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2383 image->colormap[i].blue=(double)
2384 PosterizePixel(image->colormap[i].blue);
2385 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2386 image->colormap[i].alpha=(double)
2387 PosterizePixel(image->colormap[i].alpha);
2394 image_view=AcquireAuthenticCacheView(image,exception);
2395 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2396 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2397 magick_threads(image,image,image->rows,1)
2399 for (y=0; y < (ssize_t) image->rows; y++)
2407 if (status == MagickFalse)
2409 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2410 if (q == (Quantum *) NULL)
2415 for (x=0; x < (ssize_t) image->columns; x++)
2417 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2418 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2419 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2420 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2421 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2422 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2423 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2424 (image->colorspace == CMYKColorspace))
2425 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2426 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2427 (image->alpha_trait == BlendPixelTrait))
2428 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2429 q+=GetPixelChannels(image);
2431 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2433 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2438 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2439 #pragma omp critical (MagickCore_PosterizeImage)
2441 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2443 if (proceed == MagickFalse)
2447 image_view=DestroyCacheView(image_view);
2448 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2449 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2450 levels,MaxColormapSize+1);
2451 quantize_info->dither_method=dither_method;
2452 quantize_info->tree_depth=MaxTreeDepth;
2453 status=QuantizeImage(quantize_info,image,exception);
2454 quantize_info=DestroyQuantizeInfo(quantize_info);
2459 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2463 + P r u n e C h i l d %
2467 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2469 % PruneChild() deletes the given node and merges its statistics into its
2472 % The format of the PruneSubtree method is:
2474 % PruneChild(const Image *image,CubeInfo *cube_info,
2475 % const NodeInfo *node_info)
2477 % A description of each parameter follows.
2479 % o image: the image.
2481 % o cube_info: A pointer to the Cube structure.
2483 % o node_info: pointer to node in color cube tree that is to be pruned.
2486 static void PruneChild(const Image *image,CubeInfo *cube_info,
2487 const NodeInfo *node_info)
2499 Traverse any children.
2501 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2502 for (i=0; i < (ssize_t) number_children; i++)
2503 if (node_info->child[i] != (NodeInfo *) NULL)
2504 PruneChild(image,cube_info,node_info->child[i]);
2506 Merge color statistics into parent.
2508 parent=node_info->parent;
2509 parent->number_unique+=node_info->number_unique;
2510 parent->total_color.red+=node_info->total_color.red;
2511 parent->total_color.green+=node_info->total_color.green;
2512 parent->total_color.blue+=node_info->total_color.blue;
2513 parent->total_color.alpha+=node_info->total_color.alpha;
2514 parent->child[node_info->id]=(NodeInfo *) NULL;
2519 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2523 + P r u n e L e v e l %
2527 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2529 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2530 % their color statistics into their parent node.
2532 % The format of the PruneLevel method is:
2534 % PruneLevel(const Image *image,CubeInfo *cube_info,
2535 % const NodeInfo *node_info)
2537 % A description of each parameter follows.
2539 % o image: the image.
2541 % o cube_info: A pointer to the Cube structure.
2543 % o node_info: pointer to node in color cube tree that is to be pruned.
2546 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2547 const NodeInfo *node_info)
2556 Traverse any children.
2558 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2559 for (i=0; i < (ssize_t) number_children; i++)
2560 if (node_info->child[i] != (NodeInfo *) NULL)
2561 PruneLevel(image,cube_info,node_info->child[i]);
2562 if (node_info->level == cube_info->depth)
2563 PruneChild(image,cube_info,node_info);
2567 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2571 + P r u n e T o C u b e D e p t h %
2575 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2577 % PruneToCubeDepth() deletes any nodes at a depth greater than
2578 % cube_info->depth while merging their color statistics into their parent
2581 % The format of the PruneToCubeDepth method is:
2583 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2584 % const NodeInfo *node_info)
2586 % A description of each parameter follows.
2588 % o cube_info: A pointer to the Cube structure.
2590 % o node_info: pointer to node in color cube tree that is to be pruned.
2593 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2594 const NodeInfo *node_info)
2603 Traverse any children.
2605 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2606 for (i=0; i < (ssize_t) number_children; i++)
2607 if (node_info->child[i] != (NodeInfo *) NULL)
2608 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2609 if (node_info->level > cube_info->depth)
2610 PruneChild(image,cube_info,node_info);
2614 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2618 % Q u a n t i z e I m a g e %
2622 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2624 % QuantizeImage() analyzes the colors within a reference image and chooses a
2625 % fixed number of colors to represent the image. The goal of the algorithm
2626 % is to minimize the color difference between the input and output image while
2627 % minimizing the processing time.
2629 % The format of the QuantizeImage method is:
2631 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2632 % Image *image,ExceptionInfo *exception)
2634 % A description of each parameter follows:
2636 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2638 % o image: the image.
2640 % o exception: return any errors or warnings in this structure.
2644 static MagickBooleanType DirectToColormapImage(Image *image,
2645 ExceptionInfo *exception)
2663 number_colors=(size_t) (image->columns*image->rows);
2664 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2665 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2667 if (image->colors != number_colors)
2668 return(MagickFalse);
2670 image_view=AcquireAuthenticCacheView(image,exception);
2671 for (y=0; y < (ssize_t) image->rows; y++)
2682 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2683 if (q == (Quantum *) NULL)
2685 for (x=0; x < (ssize_t) image->columns; x++)
2687 image->colormap[i].red=(double) GetPixelRed(image,q);
2688 image->colormap[i].green=(double) GetPixelGreen(image,q);
2689 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2690 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2691 SetPixelIndex(image,(Quantum) i,q);
2693 q+=GetPixelChannels(image);
2695 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2697 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2699 if (proceed == MagickFalse)
2702 image_view=DestroyCacheView(image_view);
2706 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2707 Image *image,ExceptionInfo *exception)
2719 assert(quantize_info != (const QuantizeInfo *) NULL);
2720 assert(quantize_info->signature == MagickCoreSignature);
2721 assert(image != (Image *) NULL);
2722 assert(image->signature == MagickCoreSignature);
2723 if (image->debug != MagickFalse)
2724 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2725 assert(exception != (ExceptionInfo *) NULL);
2726 assert(exception->signature == MagickCoreSignature);
2727 maximum_colors=quantize_info->number_colors;
2728 if (maximum_colors == 0)
2729 maximum_colors=MaxColormapSize;
2730 if (maximum_colors > MaxColormapSize)
2731 maximum_colors=MaxColormapSize;
2732 if (image->alpha_trait != BlendPixelTrait)
2734 if ((image->columns*image->rows) <= maximum_colors)
2735 (void) DirectToColormapImage(image,exception);
2736 if (SetImageGray(image,exception) != MagickFalse)
2737 (void) SetGrayscaleImage(image,exception);
2739 if ((image->storage_class == PseudoClass) &&
2740 (image->colors <= maximum_colors))
2742 if ((quantize_info->colorspace != UndefinedColorspace) &&
2743 (quantize_info->colorspace != CMYKColorspace))
2744 (void) TransformImageColorspace(image,quantize_info->colorspace,
2748 depth=quantize_info->tree_depth;
2755 Depth of color tree is: Log4(colormap size)+2.
2757 colors=maximum_colors;
2758 for (depth=1; colors != 0; depth++)
2760 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2762 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2764 if (SetImageGray(image,exception) != MagickFalse)
2768 Initialize color cube.
2770 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2771 if (cube_info == (CubeInfo *) NULL)
2772 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2774 status=ClassifyImageColors(cube_info,image,exception);
2775 if (status != MagickFalse)
2778 Reduce the number of colors in the image if it contains more than the
2779 maximum, otherwise we can disable dithering to improve the performance.
2781 if (cube_info->colors > cube_info->maximum_colors)
2782 ReduceImageColors(image,cube_info);
2784 cube_info->quantize_info->dither_method=NoDitherMethod;
2785 status=AssignImageColors(image,cube_info,exception);
2787 DestroyCubeInfo(cube_info);
2792 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2796 % Q u a n t i z e I m a g e s %
2800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2802 % QuantizeImages() analyzes the colors within a set of reference images and
2803 % chooses a fixed number of colors to represent the set. The goal of the
2804 % algorithm is to minimize the color difference between the input and output
2805 % images while minimizing the processing time.
2807 % The format of the QuantizeImages method is:
2809 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2810 % Image *images,ExceptionInfo *exception)
2812 % A description of each parameter follows:
2814 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2816 % o images: Specifies a pointer to a list of Image structures.
2818 % o exception: return any errors or warnings in this structure.
2821 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2822 Image *images,ExceptionInfo *exception)
2834 MagickProgressMonitor
2845 assert(quantize_info != (const QuantizeInfo *) NULL);
2846 assert(quantize_info->signature == MagickCoreSignature);
2847 assert(images != (Image *) NULL);
2848 assert(images->signature == MagickCoreSignature);
2849 if (images->debug != MagickFalse)
2850 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2851 assert(exception != (ExceptionInfo *) NULL);
2852 assert(exception->signature == MagickCoreSignature);
2853 if (GetNextImageInList(images) == (Image *) NULL)
2856 Handle a single image with QuantizeImage.
2858 status=QuantizeImage(quantize_info,images,exception);
2862 maximum_colors=quantize_info->number_colors;
2863 if (maximum_colors == 0)
2864 maximum_colors=MaxColormapSize;
2865 if (maximum_colors > MaxColormapSize)
2866 maximum_colors=MaxColormapSize;
2867 depth=quantize_info->tree_depth;
2874 Depth of color tree is: Log4(colormap size)+2.
2876 colors=maximum_colors;
2877 for (depth=1; colors != 0; depth++)
2879 if (quantize_info->dither_method != NoDitherMethod)
2883 Initialize color cube.
2885 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2886 if (cube_info == (CubeInfo *) NULL)
2888 (void) ThrowMagickException(exception,GetMagickModule(),
2889 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2890 return(MagickFalse);
2892 number_images=GetImageListLength(images);
2894 for (i=0; image != (Image *) NULL; i++)
2896 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2897 image->client_data);
2898 status=ClassifyImageColors(cube_info,image,exception);
2899 if (status == MagickFalse)
2901 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2902 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2904 if (proceed == MagickFalse)
2906 image=GetNextImageInList(image);
2908 if (status != MagickFalse)
2911 Reduce the number of colors in an image sequence.
2913 ReduceImageColors(images,cube_info);
2915 for (i=0; image != (Image *) NULL; i++)
2917 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2918 NULL,image->client_data);
2919 status=AssignImageColors(image,cube_info,exception);
2920 if (status == MagickFalse)
2922 (void) SetImageProgressMonitor(image,progress_monitor,
2923 image->client_data);
2924 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2926 if (proceed == MagickFalse)
2928 image=GetNextImageInList(image);
2931 DestroyCubeInfo(cube_info);
2936 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2940 + Q u a n t i z e E r r o r F l a t t e n %
2944 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2946 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2947 % error into a sorted 1D array. This accelerates the color reduction process.
2949 % Contributed by Yoya.
2951 % The format of the QuantizeErrorFlatten method is:
2953 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2954 % const NodeInfo *node_info,const ssize_t offset,
2955 % double *quantize_error)
2957 % A description of each parameter follows.
2959 % o image: the image.
2961 % o cube_info: A pointer to the Cube structure.
2963 % o node_info: pointer to node in color cube tree that is current pointer.
2965 % o offset: quantize error offset.
2967 % o quantize_error: the quantization error vector.
2970 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2971 const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
2980 if (offset >= (ssize_t) cube_info->nodes)
2982 quantize_error[offset]=node_info->quantize_error;
2984 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2985 for (i=0; i < (ssize_t) number_children ; i++)
2986 if (node_info->child[i] != (NodeInfo *) NULL)
2987 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
2993 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3001 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3003 % Reduce() traverses the color cube tree and prunes any node whose
3004 % quantization error falls below a particular threshold.
3006 % The format of the Reduce method is:
3008 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3010 % A description of each parameter follows.
3012 % o image: the image.
3014 % o cube_info: A pointer to the Cube structure.
3016 % o node_info: pointer to node in color cube tree that is to be pruned.
3019 static void Reduce(const Image *image,CubeInfo *cube_info,
3020 const NodeInfo *node_info)
3029 Traverse any children.
3031 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3032 for (i=0; i < (ssize_t) number_children; i++)
3033 if (node_info->child[i] != (NodeInfo *) NULL)
3034 Reduce(image,cube_info,node_info->child[i]);
3035 if (node_info->quantize_error <= cube_info->pruning_threshold)
3036 PruneChild(image,cube_info,node_info);
3040 Find minimum pruning threshold.
3042 if (node_info->number_unique > 0)
3043 cube_info->colors++;
3044 if (node_info->quantize_error < cube_info->next_threshold)
3045 cube_info->next_threshold=node_info->quantize_error;
3050 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3054 + R e d u c e I m a g e C o l o r s %
3058 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3060 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3061 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3062 % in the output image. On any given iteration over the tree, it selects
3063 % those nodes whose E value is minimal for pruning and merges their
3064 % color statistics upward. It uses a pruning threshold, Ep, to govern
3065 % node selection as follows:
3068 % while number of nodes with (n2 > 0) > required maximum number of colors
3069 % prune all nodes such that E <= Ep
3070 % Set Ep to minimum E in remaining nodes
3072 % This has the effect of minimizing any quantization error when merging
3073 % two nodes together.
3075 % When a node to be pruned has offspring, the pruning procedure invokes
3076 % itself recursively in order to prune the tree from the leaves upward.
3077 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3078 % corresponding data in that node's parent. This retains the pruned
3079 % node's color characteristics for later averaging.
3081 % For each node, n2 pixels exist for which that node represents the
3082 % smallest volume in RGB space containing those pixel's colors. When n2
3083 % > 0 the node will uniquely define a color in the output image. At the
3084 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3085 % the tree which represent colors present in the input image.
3087 % The other pixel count, n1, indicates the total number of colors
3088 % within the cubic volume which the node represents. This includes n1 -
3089 % n2 pixels whose colors should be defined by nodes at a lower level in
3092 % The format of the ReduceImageColors method is:
3094 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3096 % A description of each parameter follows.
3098 % o image: the image.
3100 % o cube_info: A pointer to the Cube structure.
3104 static int QuantizeErrorCompare(const void *error_p,const void *error_q)
3110 p=(double *) error_p;
3111 q=(double *) error_q;
3114 if (fabs(*q-*p) <= MagickEpsilon)
3119 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3121 #define ReduceImageTag "Reduce/Image"
3132 cube_info->next_threshold=0.0;
3133 if (cube_info->colors > cube_info->maximum_colors)
3139 Enable rapid reduction of the number of unique colors.
3141 quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
3142 sizeof(*quantize_error));
3143 if (quantize_error != (double *) NULL)
3145 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3147 qsort(quantize_error,cube_info->nodes,sizeof(double),
3148 QuantizeErrorCompare);
3149 if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
3150 cube_info->next_threshold=quantize_error[cube_info->nodes-110*
3151 (cube_info->maximum_colors+1)/100];
3152 quantize_error=(double *) RelinquishMagickMemory(quantize_error);
3155 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3157 cube_info->pruning_threshold=cube_info->next_threshold;
3158 cube_info->next_threshold=cube_info->root->quantize_error-1;
3159 cube_info->colors=0;
3160 Reduce(image,cube_info,cube_info->root);
3161 offset=(MagickOffsetType) span-cube_info->colors;
3162 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3163 cube_info->maximum_colors+1);
3164 if (proceed == MagickFalse)
3170 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3174 % R e m a p I m a g e %
3178 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3180 % RemapImage() replaces the colors of an image with the closest of the colors
3181 % from the reference image.
3183 % The format of the RemapImage method is:
3185 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3186 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3188 % A description of each parameter follows:
3190 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3192 % o image: the image.
3194 % o remap_image: the reference image.
3196 % o exception: return any errors or warnings in this structure.
3199 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3200 Image *image,const Image *remap_image,ExceptionInfo *exception)
3209 Initialize color cube.
3211 assert(image != (Image *) NULL);
3212 assert(image->signature == MagickCoreSignature);
3213 if (image->debug != MagickFalse)
3214 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3215 assert(remap_image != (Image *) NULL);
3216 assert(remap_image->signature == MagickCoreSignature);
3217 assert(exception != (ExceptionInfo *) NULL);
3218 assert(exception->signature == MagickCoreSignature);
3219 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3220 quantize_info->number_colors);
3221 if (cube_info == (CubeInfo *) NULL)
3222 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3224 status=ClassifyImageColors(cube_info,remap_image,exception);
3225 if (status != MagickFalse)
3228 Classify image colors from the reference image.
3230 cube_info->quantize_info->number_colors=cube_info->colors;
3231 status=AssignImageColors(image,cube_info,exception);
3233 DestroyCubeInfo(cube_info);
3238 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3242 % R e m a p I m a g e s %
3246 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3248 % RemapImages() replaces the colors of a sequence of images with the
3249 % closest color from a reference image.
3251 % The format of the RemapImage method is:
3253 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3254 % Image *images,Image *remap_image,ExceptionInfo *exception)
3256 % A description of each parameter follows:
3258 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3260 % o images: the image sequence.
3262 % o remap_image: the reference image.
3264 % o exception: return any errors or warnings in this structure.
3267 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3268 Image *images,const Image *remap_image,ExceptionInfo *exception)
3279 assert(images != (Image *) NULL);
3280 assert(images->signature == MagickCoreSignature);
3281 if (images->debug != MagickFalse)
3282 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3283 assert(exception != (ExceptionInfo *) NULL);
3284 assert(exception->signature == MagickCoreSignature);
3286 if (remap_image == (Image *) NULL)
3289 Create a global colormap for an image sequence.
3291 status=QuantizeImages(quantize_info,images,exception);
3295 Classify image colors from the reference image.
3297 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3298 quantize_info->number_colors);
3299 if (cube_info == (CubeInfo *) NULL)
3300 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3302 status=ClassifyImageColors(cube_info,remap_image,exception);
3303 if (status != MagickFalse)
3306 Classify image colors from the reference image.
3308 cube_info->quantize_info->number_colors=cube_info->colors;
3310 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3312 status=AssignImageColors(image,cube_info,exception);
3313 if (status == MagickFalse)
3317 DestroyCubeInfo(cube_info);
3322 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3326 % S e t G r a y s c a l e I m a g e %
3330 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3332 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3334 % The format of the SetGrayscaleImage method is:
3336 % MagickBooleanType SetGrayscaleImage(Image *image,
3337 % ExceptionInfo *exception)
3339 % A description of each parameter follows:
3341 % o image: The image.
3343 % o exception: return any errors or warnings in this structure.
3347 #if defined(__cplusplus) || defined(c_plusplus)
3351 static int IntensityCompare(const void *x,const void *y)
3360 color_1=(PixelInfo *) x;
3361 color_2=(PixelInfo *) y;
3362 intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
3363 GetPixelInfoIntensity((const Image *) NULL,color_2);
3364 return((int) intensity);
3367 #if defined(__cplusplus) || defined(c_plusplus)
3371 static MagickBooleanType SetGrayscaleImage(Image *image,
3372 ExceptionInfo *exception)
3391 assert(image != (Image *) NULL);
3392 assert(image->signature == MagickCoreSignature);
3393 if (image->type != GrayscaleType)
3394 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3395 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
3396 sizeof(*colormap_index));
3397 if (colormap_index == (ssize_t *) NULL)
3398 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3400 if (image->storage_class != PseudoClass)
3402 (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
3403 sizeof(*colormap_index));
3404 if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
3405 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3409 image_view=AcquireAuthenticCacheView(image,exception);
3410 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3411 #pragma omp parallel for schedule(static,4) shared(status) \
3412 magick_threads(image,image,image->rows,1)
3414 for (y=0; y < (ssize_t) image->rows; y++)
3422 if (status == MagickFalse)
3424 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3426 if (q == (Quantum *) NULL)
3431 for (x=0; x < (ssize_t) image->columns; x++)
3436 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3437 if (colormap_index[intensity] < 0)
3439 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3440 #pragma omp critical (MagickCore_SetGrayscaleImage)
3442 if (colormap_index[intensity] < 0)
3444 colormap_index[intensity]=(ssize_t) image->colors;
3445 image->colormap[image->colors].red=(double)
3446 GetPixelRed(image,q);
3447 image->colormap[image->colors].green=(double)
3448 GetPixelGreen(image,q);
3449 image->colormap[image->colors].blue=(double)
3450 GetPixelBlue(image,q);
3454 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3455 q+=GetPixelChannels(image);
3457 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3460 image_view=DestroyCacheView(image_view);
3462 for (i=0; i < (ssize_t) image->colors; i++)
3463 image->colormap[i].alpha=(double) i;
3464 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3466 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3467 if (colormap == (PixelInfo *) NULL)
3468 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3471 colormap[j]=image->colormap[0];
3472 for (i=0; i < (ssize_t) image->colors; i++)
3474 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3477 colormap[j]=image->colormap[i];
3479 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3481 image->colors=(size_t) (j+1);
3482 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3483 image->colormap=colormap;
3485 image_view=AcquireAuthenticCacheView(image,exception);
3486 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3487 #pragma omp parallel for schedule(static,4) shared(status) \
3488 magick_threads(image,image,image->rows,1)
3490 for (y=0; y < (ssize_t) image->rows; y++)
3498 if (status == MagickFalse)
3500 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3501 if (q == (Quantum *) NULL)
3506 for (x=0; x < (ssize_t) image->columns; x++)
3508 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3509 GetPixelIndex(image,q))],q);
3510 q+=GetPixelChannels(image);
3512 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3515 image_view=DestroyCacheView(image_view);
3516 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3517 image->type=GrayscaleType;
3518 if (SetImageMonochrome(image,exception) != MagickFalse)
3519 image->type=BilevelType;