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-2012 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
28 % Unless required by applicable law or agreed to in writing, software %
29 % distributed under the License is distributed on an "AS IS" BASIS, %
30 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31 % See the License for the specific language governing permissions and %
32 % limitations under the License. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Realism in computer graphics typically requires using 24 bits/pixel to
37 % generate an image. Yet many graphic display devices do not contain the
38 % amount of memory necessary to match the spatial and color resolution of
39 % the human eye. The Quantize methods takes a 24 bit image and reduces
40 % the number of colors so it can be displayed on raster device with less
41 % bits per pixel. In most instances, the quantized image closely
42 % resembles the original reference image.
44 % A reduction of colors in an image is also desirable for image
45 % transmission and real-time animation.
47 % QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 % them down to some fixed number of colors.
50 % For purposes of color allocation, an image is a set of n pixels, where
51 % each pixel is a point in RGB space. RGB space is a 3-dimensional
52 % vector space, and each pixel, Pi, is defined by an ordered triple of
53 % red, green, and blue coordinates, (Ri, Gi, Bi).
55 % Each primary color component (red, green, or blue) represents an
56 % intensity which varies linearly from 0 to a maximum value, Cmax, which
57 % corresponds to full saturation of that color. Color allocation is
58 % defined over a domain consisting of the cube in RGB space with opposite
59 % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
62 % The algorithm maps this domain onto a tree in which each node
63 % represents a cube within that domain. In the following discussion
64 % these cubes are defined by the coordinate of two opposite vertices:
65 % The vertex nearest the origin in RGB space and the vertex farthest from
68 % The tree's root node represents the entire domain, (0,0,0) through
69 % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70 % subdividing one node's cube into eight smaller cubes of equal size.
71 % This corresponds to bisecting the parent cube with planes passing
72 % through the midpoints of each edge.
74 % The basic algorithm operates in three phases: Classification,
75 % Reduction, and Assignment. Classification builds a color description
76 % tree for the image. Reduction collapses the tree until the number it
77 % represents, at most, the number of colors desired in the output image.
78 % Assignment defines the output image's color map and sets each pixel's
79 % color by restorage_class in the reduced tree. Our goal is to minimize
80 % the numerical discrepancies between the original colors and quantized
81 % colors (quantization error).
83 % Classification begins by initializing a color description tree of
84 % sufficient depth to represent each possible input color in a leaf.
85 % However, it is impractical to generate a fully-formed color description
86 % tree in the storage_class phase for realistic values of Cmax. If
87 % colors components in the input image are quantized to k-bit precision,
88 % so that Cmax= 2k-1, the tree would need k levels below the root node to
89 % allow representing each possible input color in a leaf. This becomes
90 % prohibitive because the tree's total number of nodes is 1 +
93 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95 % Initializes data structures for nodes only as they are needed; (2)
96 % Chooses a maximum depth for the tree as a function of the desired
97 % number of colors in the output image (currently log2(colormap size)).
99 % For each pixel in the input image, storage_class scans downward from
100 % the root of the color description tree. At each level of the tree it
101 % identifies the single node which represents a cube in RGB space
102 % containing the pixel's color. It updates the following data for each
105 % n1: Number of pixels whose color is contained in the RGB cube which
106 % this node represents;
108 % n2: Number of pixels whose color is not represented in a node at
109 % lower depth in the tree; initially, n2 = 0 for all nodes except
110 % leaves of the tree.
112 % Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113 % pixels not classified at a lower depth. The combination of these sums
114 % and n2 will ultimately characterize the mean color of a set of
115 % pixels represented by this node.
117 % E: the distance squared in RGB space between each pixel contained
118 % within a node and the nodes' center. This represents the
119 % quantization error for a node.
121 % Reduction repeatedly prunes the tree until the number of nodes with n2
122 % > 0 is less than or equal to the maximum number of colors allowed in
123 % the output image. On any given iteration over the tree, it selects
124 % those nodes whose E count is minimal for pruning and merges their color
125 % statistics upward. It uses a pruning threshold, Ep, to govern node
126 % selection as follows:
129 % while number of nodes with (n2 > 0) > required maximum number of colors
130 % prune all nodes such that E <= Ep
131 % Set Ep to minimum E in remaining nodes
133 % This has the effect of minimizing any quantization error when merging
134 % two nodes together.
136 % When a node to be pruned has offspring, the pruning procedure invokes
137 % itself recursively in order to prune the tree from the leaves upward.
138 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
139 % corresponding data in that node's parent. This retains the pruned
140 % node's color characteristics for later averaging.
142 % For each node, n2 pixels exist for which that node represents the
143 % smallest volume in RGB space containing those pixel's colors. When n2
144 % > 0 the node will uniquely define a color in the output image. At the
145 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
146 % the tree which represent colors present in the input image.
148 % The other pixel count, n1, indicates the total number of colors within
149 % the cubic volume which the node represents. This includes n1 - n2
150 % pixels whose colors should be defined by nodes at a lower level in the
153 % Assignment generates the output image from the pruned tree. The output
154 % image consists of two parts: (1) A color map, which is an array of
155 % color descriptions (RGB triples) for each color present in the output
156 % image; (2) A pixel array, which represents each pixel as an index
157 % into the color map array.
159 % First, the assignment phase makes one pass over the pruned color
160 % description tree to establish the image's color map. For each node
161 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162 % color of all pixels that classify no lower than this node. Each of
163 % these colors becomes an entry in the color map.
165 % Finally, the assignment phase reclassifies each pixel in the pruned
166 % tree to identify the deepest node containing the pixel's color. The
167 % pixel's value in the pixel array becomes the index of this node's mean
168 % color in the color map.
170 % This method is based on a similar algorithm written by Paul Raveling.
175 Include declarations.
177 #include "MagickCore/studio.h"
178 #include "MagickCore/attribute.h"
179 #include "MagickCore/cache-view.h"
180 #include "MagickCore/color.h"
181 #include "MagickCore/color-private.h"
182 #include "MagickCore/colormap.h"
183 #include "MagickCore/colorspace.h"
184 #include "MagickCore/colorspace-private.h"
185 #include "MagickCore/enhance.h"
186 #include "MagickCore/exception.h"
187 #include "MagickCore/exception-private.h"
188 #include "MagickCore/histogram.h"
189 #include "MagickCore/image.h"
190 #include "MagickCore/image-private.h"
191 #include "MagickCore/list.h"
192 #include "MagickCore/memory_.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/quantize.h"
198 #include "MagickCore/quantum.h"
199 #include "MagickCore/quantum-private.h"
200 #include "MagickCore/string_.h"
201 #include "MagickCore/thread-private.h"
206 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
211 #define ErrorQueueLength 16
212 #define MaxNodes 266817
213 #define MaxTreeDepth 8
214 #define NodesInAList 1920
219 typedef struct _RealPixelInfo
228 typedef struct _NodeInfo
249 typedef struct _Nodes
258 typedef struct _CubeInfo
296 error[ErrorQueueLength];
299 weights[ErrorQueueLength];
325 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
328 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
330 static MagickBooleanType
331 AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
332 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
333 DitherImage(Image *,CubeInfo *,ExceptionInfo *),
334 SetGrayscaleImage(Image *,ExceptionInfo *);
337 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
340 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
341 DestroyCubeInfo(CubeInfo *),
342 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
343 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
344 ReduceImageColors(const Image *,CubeInfo *);
347 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
351 % A c q u i r e Q u a n t i z e I n f o %
355 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
357 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
359 % The format of the AcquireQuantizeInfo method is:
361 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
363 % A description of each parameter follows:
365 % o image_info: the image info.
368 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
373 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
374 if (quantize_info == (QuantizeInfo *) NULL)
375 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
376 GetQuantizeInfo(quantize_info);
377 if (image_info != (ImageInfo *) NULL)
382 quantize_info->dither=image_info->dither;
383 option=GetImageOption(image_info,"dither");
384 if (option != (const char *) NULL)
385 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
386 MagickDitherOptions,MagickFalse,option);
387 quantize_info->measure_error=image_info->verbose;
389 return(quantize_info);
393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
397 + A s s i g n I m a g e C o l o r s %
401 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
403 % AssignImageColors() generates the output image from the pruned tree. The
404 % output image consists of two parts: (1) A color map, which is an array
405 % of color descriptions (RGB triples) for each color present in the
406 % output image; (2) A pixel array, which represents each pixel as an
407 % index into the color map array.
409 % First, the assignment phase makes one pass over the pruned color
410 % description tree to establish the image's color map. For each node
411 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
412 % color of all pixels that classify no lower than this node. Each of
413 % these colors becomes an entry in the color map.
415 % Finally, the assignment phase reclassifies each pixel in the pruned
416 % tree to identify the deepest node containing the pixel's color. The
417 % pixel's value in the pixel array becomes the index of this node's mean
418 % color in the color map.
420 % The format of the AssignImageColors() method is:
422 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
424 % A description of each parameter follows.
426 % o image: the image.
428 % o cube_info: A pointer to the Cube structure.
432 static inline void AssociateAlphaPixel(const Image *image,
433 const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
438 if ((cube_info->associate_alpha == MagickFalse) ||
439 (GetPixelAlpha(image,pixel)== OpaqueAlpha))
441 alpha_pixel->red=(MagickRealType) GetPixelRed(image,pixel);
442 alpha_pixel->green=(MagickRealType) GetPixelGreen(image,pixel);
443 alpha_pixel->blue=(MagickRealType) GetPixelBlue(image,pixel);
444 alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
447 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,pixel));
448 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
449 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
450 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
451 alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
454 static inline void AssociateAlphaPixelInfo(const Image *image,
455 const CubeInfo *cube_info,const PixelInfo *pixel,
456 RealPixelInfo *alpha_pixel)
461 if ((cube_info->associate_alpha == MagickFalse) ||
462 (pixel->alpha == OpaqueAlpha))
464 alpha_pixel->red=(MagickRealType) pixel->red;
465 alpha_pixel->green=(MagickRealType) pixel->green;
466 alpha_pixel->blue=(MagickRealType) pixel->blue;
467 alpha_pixel->alpha=(MagickRealType) pixel->alpha;
470 alpha=(MagickRealType) (QuantumScale*pixel->alpha);
471 alpha_pixel->red=alpha*pixel->red;
472 alpha_pixel->green=alpha*pixel->green;
473 alpha_pixel->blue=alpha*pixel->blue;
474 alpha_pixel->alpha=(MagickRealType) pixel->alpha;
477 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
481 if (value >= QuantumRange)
482 return((Quantum) QuantumRange);
483 return((Quantum) (value+0.5));
486 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
487 const RealPixelInfo *pixel,size_t index)
492 id=(size_t) (((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x01) |
493 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x01) << 1 |
494 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x01) << 2);
495 if (cube_info->associate_alpha != MagickFalse)
496 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->alpha)) >> index) & 0x1) << 3;
500 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
501 ExceptionInfo *exception)
503 #define AssignImageTag "Assign/Image"
509 Allocate image colormap.
511 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
512 (cube_info->quantize_info->colorspace != CMYKColorspace))
513 (void) TransformImageColorspace((Image *) image,
514 cube_info->quantize_info->colorspace,exception);
516 if ((image->colorspace != GRAYColorspace) &&
517 (IsRGBColorspace(image->colorspace) == MagickFalse) &&
518 (image->colorspace != CMYColorspace))
519 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
520 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
521 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
524 cube_info->transparent_pixels=0;
525 cube_info->transparent_index=(-1);
526 (void) DefineImageColormap(image,cube_info,cube_info->root);
528 Create a reduced color image.
530 if ((cube_info->quantize_info->dither != MagickFalse) &&
531 (cube_info->quantize_info->dither_method != NoDitherMethod))
532 (void) DitherImage(image,cube_info,exception);
545 image_view=AcquireCacheView(image);
546 #if defined(MAGICKCORE_OPENMP_SUPPORT)
547 #pragma omp parallel for schedule(static,4) shared(status)
549 for (y=0; y < (ssize_t) image->rows; y++)
563 if (status == MagickFalse)
565 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
567 if (q == (Quantum *) NULL)
573 for (x=0; x < (ssize_t) image->columns; x+=count)
578 register const NodeInfo
589 Identify the deepest node containing the pixel's color.
591 for (count=1; (x+count) < (ssize_t) image->columns; count++)
596 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
597 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
600 AssociateAlphaPixel(image,&cube,q,&pixel);
602 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
604 id=ColorToNodeId(&cube,&pixel,index);
605 if (node_info->child[id] == (NodeInfo *) NULL)
607 node_info=node_info->child[id];
610 Find closest color among siblings and their children.
613 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
614 (QuantumRange+1.0)+1.0);
615 ClosestColor(image,&cube,node_info->parent);
616 index=cube.color_number;
617 for (i=0; i < (ssize_t) count; i++)
619 if (image->storage_class == PseudoClass)
620 SetPixelIndex(image,(Quantum) index,q);
621 if (cube.quantize_info->measure_error == MagickFalse)
623 SetPixelRed(image,ClampToQuantum(
624 image->colormap[index].red),q);
625 SetPixelGreen(image,ClampToQuantum(
626 image->colormap[index].green),q);
627 SetPixelBlue(image,ClampToQuantum(
628 image->colormap[index].blue),q);
629 if (cube.associate_alpha != MagickFalse)
630 SetPixelAlpha(image,ClampToQuantum(
631 image->colormap[index].alpha),q);
633 q+=GetPixelChannels(image);
636 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
638 if (image->progress_monitor != (MagickProgressMonitor) NULL)
643 #if defined(MAGICKCORE_OPENMP_SUPPORT)
644 #pragma omp critical (MagickCore_AssignImageColors)
646 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
648 if (proceed == MagickFalse)
652 image_view=DestroyCacheView(image_view);
654 if (cube_info->quantize_info->measure_error != MagickFalse)
655 (void) GetImageQuantizeError(image,exception);
656 if ((cube_info->quantize_info->number_colors == 2) &&
657 (cube_info->quantize_info->colorspace == GRAYColorspace))
672 for (i=0; i < (ssize_t) image->colors; i++)
674 intensity=(double) ((MagickRealType) GetPixelInfoIntensity(q) <
675 ((MagickRealType) QuantumRange/2.0) ? 0 : QuantumRange);
682 (void) SyncImage(image,exception);
683 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
684 (cube_info->quantize_info->colorspace != CMYKColorspace))
685 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
690 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
694 + C l a s s i f y I m a g e C o l o r s %
698 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
700 % ClassifyImageColors() begins by initializing a color description tree
701 % of sufficient depth to represent each possible input color in a leaf.
702 % However, it is impractical to generate a fully-formed color
703 % description tree in the storage_class phase for realistic values of
704 % Cmax. If colors components in the input image are quantized to k-bit
705 % precision, so that Cmax= 2k-1, the tree would need k levels below the
706 % root node to allow representing each possible input color in a leaf.
707 % This becomes prohibitive because the tree's total number of nodes is
710 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
711 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
712 % Initializes data structures for nodes only as they are needed; (2)
713 % Chooses a maximum depth for the tree as a function of the desired
714 % number of colors in the output image (currently log2(colormap size)).
716 % For each pixel in the input image, storage_class scans downward from
717 % the root of the color description tree. At each level of the tree it
718 % identifies the single node which represents a cube in RGB space
719 % containing It updates the following data for each such node:
721 % n1 : Number of pixels whose color is contained in the RGB cube
722 % which this node represents;
724 % n2 : Number of pixels whose color is not represented in a node at
725 % lower depth in the tree; initially, n2 = 0 for all nodes except
726 % leaves of the tree.
728 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
729 % all pixels not classified at a lower depth. The combination of
730 % these sums and n2 will ultimately characterize the mean color of a
731 % set of pixels represented by this node.
733 % E: the distance squared in RGB space between each pixel contained
734 % within a node and the nodes' center. This represents the quantization
737 % The format of the ClassifyImageColors() method is:
739 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
740 % const Image *image,ExceptionInfo *exception)
742 % A description of each parameter follows.
744 % o cube_info: A pointer to the Cube structure.
746 % o image: the image.
750 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
755 associate_alpha=image->matte;
756 if (cube_info->quantize_info->colorspace == TransparentColorspace)
757 associate_alpha=MagickFalse;
758 if ((cube_info->quantize_info->number_colors == 2) &&
759 (cube_info->quantize_info->colorspace == GRAYColorspace))
760 associate_alpha=MagickFalse;
761 cube_info->associate_alpha=associate_alpha;
764 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
765 const Image *image,ExceptionInfo *exception)
767 #define ClassifyImageTag "Classify/Image"
797 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
799 SetAssociatedAlpha(image,cube_info);
800 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
801 (cube_info->quantize_info->colorspace != CMYKColorspace))
802 (void) TransformImageColorspace((Image *) image,
803 cube_info->quantize_info->colorspace,exception);
805 if ((image->colorspace != GRAYColorspace) &&
806 (image->colorspace != CMYColorspace) &&
807 (IsRGBColorspace(image->colorspace) == MagickFalse))
808 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
809 midpoint.red=(MagickRealType) QuantumRange/2.0;
810 midpoint.green=(MagickRealType) QuantumRange/2.0;
811 midpoint.blue=(MagickRealType) QuantumRange/2.0;
812 midpoint.alpha=(MagickRealType) QuantumRange/2.0;
814 image_view=AcquireCacheView(image);
815 for (y=0; y < (ssize_t) image->rows; y++)
817 register const Quantum
823 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
824 if (p == (const Quantum *) NULL)
826 if (cube_info->nodes > MaxNodes)
829 Prune one level if the color tree is too large.
831 PruneLevel(image,cube_info,cube_info->root);
834 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
837 Start at the root and descend the color cube tree.
839 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
844 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
845 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
848 AssociateAlphaPixel(image,cube_info,p,&pixel);
849 index=MaxTreeDepth-1;
850 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
852 node_info=cube_info->root;
853 for (level=1; level <= MaxTreeDepth; level++)
856 id=ColorToNodeId(cube_info,&pixel,index);
857 mid.red+=(id & 1) != 0 ? bisect : -bisect;
858 mid.green+=(id & 2) != 0 ? bisect : -bisect;
859 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
860 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
861 if (node_info->child[id] == (NodeInfo *) NULL)
864 Set colors of new node to contain pixel.
866 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
867 if (node_info->child[id] == (NodeInfo *) NULL)
868 (void) ThrowMagickException(exception,GetMagickModule(),
869 ResourceLimitError,"MemoryAllocationFailed","`%s'",
871 if (level == MaxTreeDepth)
875 Approximate the quantization error represented by this node.
877 node_info=node_info->child[id];
878 error.red=QuantumScale*(pixel.red-mid.red);
879 error.green=QuantumScale*(pixel.green-mid.green);
880 error.blue=QuantumScale*(pixel.blue-mid.blue);
881 if (cube_info->associate_alpha != MagickFalse)
882 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
883 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
884 count*error.green*error.green+count*error.blue*error.blue+
885 count*error.alpha*error.alpha));
886 cube_info->root->quantize_error+=node_info->quantize_error;
890 Sum RGB for this leaf for later derivation of the mean cube color.
892 node_info->number_unique+=count;
893 node_info->total_color.red+=count*QuantumScale*pixel.red;
894 node_info->total_color.green+=count*QuantumScale*pixel.green;
895 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
896 if (cube_info->associate_alpha != MagickFalse)
897 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
898 p+=count*GetPixelChannels(image);
900 if (cube_info->colors > cube_info->maximum_colors)
902 PruneToCubeDepth(image,cube_info,cube_info->root);
905 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
907 if (proceed == MagickFalse)
910 for (y++; y < (ssize_t) image->rows; y++)
912 register const Quantum
918 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
919 if (p == (const Quantum *) NULL)
921 if (cube_info->nodes > MaxNodes)
924 Prune one level if the color tree is too large.
926 PruneLevel(image,cube_info,cube_info->root);
929 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
932 Start at the root and descend the color cube tree.
934 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
939 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
940 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
943 AssociateAlphaPixel(image,cube_info,p,&pixel);
944 index=MaxTreeDepth-1;
945 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
947 node_info=cube_info->root;
948 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)
963 (void) ThrowMagickException(exception,GetMagickModule(),
964 ResourceLimitError,"MemoryAllocationFailed","%s",
966 if (level == cube_info->depth)
970 Approximate the quantization error represented by this node.
972 node_info=node_info->child[id];
973 error.red=QuantumScale*(pixel.red-mid.red);
974 error.green=QuantumScale*(pixel.green-mid.green);
975 error.blue=QuantumScale*(pixel.blue-mid.blue);
976 if (cube_info->associate_alpha != MagickFalse)
977 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
978 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
979 count*error.green*error.green+count*error.blue*error.blue+
980 count*error.alpha*error.alpha));
981 cube_info->root->quantize_error+=node_info->quantize_error;
985 Sum RGB for this leaf for later derivation of the mean cube color.
987 node_info->number_unique+=count;
988 node_info->total_color.red+=count*QuantumScale*pixel.red;
989 node_info->total_color.green+=count*QuantumScale*pixel.green;
990 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
991 if (cube_info->associate_alpha != MagickFalse)
992 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
993 p+=count*GetPixelChannels(image);
995 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
997 if (proceed == MagickFalse)
1000 image_view=DestroyCacheView(image_view);
1001 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1002 (cube_info->quantize_info->colorspace != CMYKColorspace))
1003 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
1008 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1012 % C l o n e Q u a n t i z e I n f o %
1016 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1018 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1019 % or if quantize info is NULL, a new one.
1021 % The format of the CloneQuantizeInfo method is:
1023 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1025 % A description of each parameter follows:
1027 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1028 % quantize info, or if image info is NULL a new one.
1030 % o quantize_info: a structure of type info.
1033 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1038 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1039 if (clone_info == (QuantizeInfo *) NULL)
1040 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1041 GetQuantizeInfo(clone_info);
1042 if (quantize_info == (QuantizeInfo *) NULL)
1044 clone_info->number_colors=quantize_info->number_colors;
1045 clone_info->tree_depth=quantize_info->tree_depth;
1046 clone_info->dither=quantize_info->dither;
1047 clone_info->dither_method=quantize_info->dither_method;
1048 clone_info->colorspace=quantize_info->colorspace;
1049 clone_info->measure_error=quantize_info->measure_error;
1054 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1058 + C l o s e s t C o l o r %
1062 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1064 % ClosestColor() traverses the color cube tree at a particular node and
1065 % determines which colormap entry best represents the input color.
1067 % The format of the ClosestColor method is:
1069 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1070 % const NodeInfo *node_info)
1072 % A description of each parameter follows.
1074 % o image: the image.
1076 % o cube_info: A pointer to the Cube structure.
1078 % o node_info: the address of a structure of type NodeInfo which points to a
1079 % node in the color cube tree that is to be pruned.
1082 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1083 const NodeInfo *node_info)
1092 Traverse any children.
1094 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1095 for (i=0; i < (ssize_t) number_children; i++)
1096 if (node_info->child[i] != (NodeInfo *) NULL)
1097 ClosestColor(image,cube_info,node_info->child[i]);
1098 if (node_info->number_unique != 0)
1103 register MagickRealType
1111 register RealPixelInfo
1115 Determine if this color is "closest".
1117 p=image->colormap+node_info->color_number;
1118 q=(&cube_info->target);
1121 if (cube_info->associate_alpha != MagickFalse)
1123 alpha=(MagickRealType) (QuantumScale*p->alpha);
1124 beta=(MagickRealType) (QuantumScale*q->alpha);
1126 pixel=alpha*p->red-beta*q->red;
1127 distance=pixel*pixel;
1128 if (distance <= cube_info->distance)
1130 pixel=alpha*p->green-beta*q->green;
1131 distance+=pixel*pixel;
1132 if (distance <= cube_info->distance)
1134 pixel=alpha*p->blue-beta*q->blue;
1135 distance+=pixel*pixel;
1136 if (distance <= cube_info->distance)
1139 distance+=pixel*pixel;
1140 if (distance <= cube_info->distance)
1142 cube_info->distance=distance;
1143 cube_info->color_number=node_info->color_number;
1152 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1156 % C o m p r e s s I m a g e C o l o r m a p %
1160 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1162 % CompressImageColormap() compresses an image colormap by removing any
1163 % duplicate or unused color entries.
1165 % The format of the CompressImageColormap method is:
1167 % MagickBooleanType CompressImageColormap(Image *image,
1168 % ExceptionInfo *exception)
1170 % A description of each parameter follows:
1172 % o image: the image.
1174 % o exception: return any errors or warnings in this structure.
1177 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1178 ExceptionInfo *exception)
1183 assert(image != (Image *) NULL);
1184 assert(image->signature == MagickSignature);
1185 if (image->debug != MagickFalse)
1186 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1187 if (IsPaletteImage(image,exception) == MagickFalse)
1188 return(MagickFalse);
1189 GetQuantizeInfo(&quantize_info);
1190 quantize_info.number_colors=image->colors;
1191 quantize_info.tree_depth=MaxTreeDepth;
1192 return(QuantizeImage(&quantize_info,image,exception));
1196 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1200 + D e f i n e I m a g e C o l o r m a p %
1204 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1206 % DefineImageColormap() traverses the color cube tree and notes each colormap
1207 % entry. A colormap entry is any node in the color cube tree where the
1208 % of unique colors is not zero. DefineImageColormap() returns the number of
1209 % colors in the image colormap.
1211 % The format of the DefineImageColormap method is:
1213 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1214 % NodeInfo *node_info)
1216 % A description of each parameter follows.
1218 % o image: the image.
1220 % o cube_info: A pointer to the Cube structure.
1222 % o node_info: the address of a structure of type NodeInfo which points to a
1223 % node in the color cube tree that is to be pruned.
1226 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1227 NodeInfo *node_info)
1236 Traverse any children.
1238 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1239 for (i=0; i < (ssize_t) number_children; i++)
1240 if (node_info->child[i] != (NodeInfo *) NULL)
1241 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1242 if (node_info->number_unique != 0)
1244 register MagickRealType
1251 Colormap entry is defined by the mean color in this cube.
1253 q=image->colormap+image->colors;
1254 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1255 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1256 if (cube_info->associate_alpha == MagickFalse)
1258 q->red=(double) ClampToQuantum((MagickRealType)
1259 (alpha*QuantumRange*node_info->total_color.red));
1260 q->green=(double) ClampToQuantum((MagickRealType)
1261 (alpha*QuantumRange*node_info->total_color.green));
1262 q->blue=(double) ClampToQuantum((MagickRealType)
1263 (alpha*(double) QuantumRange*node_info->total_color.blue));
1264 q->alpha=OpaqueAlpha;
1271 opacity=(MagickRealType) (alpha*QuantumRange*
1272 node_info->total_color.alpha);
1273 q->alpha=(double) ClampToQuantum(opacity);
1274 if (q->alpha == OpaqueAlpha)
1276 q->red=(double) ClampToQuantum((MagickRealType)
1277 (alpha*QuantumRange*node_info->total_color.red));
1278 q->green=(double) ClampToQuantum((MagickRealType)
1279 (alpha*QuantumRange*node_info->total_color.green));
1280 q->blue=(double) ClampToQuantum((MagickRealType)
1281 (alpha*QuantumRange*node_info->total_color.blue));
1288 gamma=(MagickRealType) (QuantumScale*q->alpha);
1289 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1290 q->red=(double) ClampToQuantum((MagickRealType)
1291 (alpha*gamma*QuantumRange*node_info->total_color.red));
1292 q->green=(double) ClampToQuantum((MagickRealType)
1293 (alpha*gamma*QuantumRange*node_info->total_color.green));
1294 q->blue=(double) ClampToQuantum((MagickRealType)
1295 (alpha*gamma*QuantumRange*node_info->total_color.blue));
1296 if (node_info->number_unique > cube_info->transparent_pixels)
1298 cube_info->transparent_pixels=node_info->number_unique;
1299 cube_info->transparent_index=(ssize_t) image->colors;
1303 node_info->color_number=image->colors++;
1305 return(image->colors);
1309 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1313 + D e s t r o y C u b e I n f o %
1317 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1319 % DestroyCubeInfo() deallocates memory associated with an image.
1321 % The format of the DestroyCubeInfo method is:
1323 % DestroyCubeInfo(CubeInfo *cube_info)
1325 % A description of each parameter follows:
1327 % o cube_info: the address of a structure of type CubeInfo.
1330 static void DestroyCubeInfo(CubeInfo *cube_info)
1336 Release color cube tree storage.
1340 nodes=cube_info->node_queue->next;
1341 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1342 cube_info->node_queue->nodes);
1343 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1344 cube_info->node_queue);
1345 cube_info->node_queue=nodes;
1346 } while (cube_info->node_queue != (Nodes *) NULL);
1347 if (cube_info->cache != (ssize_t *) NULL)
1348 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1349 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1350 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1354 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1358 % D e s t r o y Q u a n t i z e I n f o %
1362 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1364 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1367 % The format of the DestroyQuantizeInfo method is:
1369 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1371 % A description of each parameter follows:
1373 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1376 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1378 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1379 assert(quantize_info != (QuantizeInfo *) NULL);
1380 assert(quantize_info->signature == MagickSignature);
1381 quantize_info->signature=(~MagickSignature);
1382 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1383 return(quantize_info);
1387 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1391 + D i t h e r I m a g e %
1395 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1397 % DitherImage() distributes the difference between an original image and
1398 % the corresponding color reduced algorithm to neighboring pixels using
1399 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1400 % MagickTrue if the image is dithered otherwise MagickFalse.
1402 % The format of the DitherImage method is:
1404 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1405 % ExceptionInfo *exception)
1407 % A description of each parameter follows.
1409 % o image: the image.
1411 % o cube_info: A pointer to the Cube structure.
1413 % o exception: return any errors or warnings in this structure.
1417 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1422 assert(pixels != (RealPixelInfo **) NULL);
1423 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1424 if (pixels[i] != (RealPixelInfo *) NULL)
1425 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1426 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1430 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1441 number_threads=GetOpenMPMaximumThreads();
1442 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1444 if (pixels == (RealPixelInfo **) NULL)
1445 return((RealPixelInfo **) NULL);
1446 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1447 for (i=0; i < (ssize_t) number_threads; i++)
1449 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,
1450 2*sizeof(**pixels));
1451 if (pixels[i] == (RealPixelInfo *) NULL)
1452 return(DestroyPixelThreadSet(pixels));
1457 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1458 const RealPixelInfo *pixel)
1460 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1461 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1462 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1463 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1469 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1470 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1471 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1472 if (cube_info->associate_alpha != MagickFalse)
1473 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1478 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1479 ExceptionInfo *exception)
1481 #define DitherImageTag "Dither/Image"
1496 Distribute quantization error using Floyd-Steinberg.
1498 pixels=AcquirePixelThreadSet(image->columns);
1499 if (pixels == (RealPixelInfo **) NULL)
1500 return(MagickFalse);
1502 image_view=AcquireCacheView(image);
1503 for (y=0; y < (ssize_t) image->rows; y++)
1506 id = GetOpenMPThreadId();
1527 if (status == MagickFalse)
1529 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1530 if (q == (Quantum *) NULL)
1535 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
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 q-=(y & 0x01)*GetPixelChannels(image);
1553 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1554 AssociateAlphaPixel(image,&cube,q,&pixel);
1557 pixel.red+=7*current[u-v].red/16;
1558 pixel.green+=7*current[u-v].green/16;
1559 pixel.blue+=7*current[u-v].blue/16;
1560 if (cube.associate_alpha != MagickFalse)
1561 pixel.alpha+=7*current[u-v].alpha/16;
1565 if (x < (ssize_t) (image->columns-1))
1567 pixel.red+=previous[u+v].red/16;
1568 pixel.green+=previous[u+v].green/16;
1569 pixel.blue+=previous[u+v].blue/16;
1570 if (cube.associate_alpha != MagickFalse)
1571 pixel.alpha+=previous[u+v].alpha/16;
1573 pixel.red+=5*previous[u].red/16;
1574 pixel.green+=5*previous[u].green/16;
1575 pixel.blue+=5*previous[u].blue/16;
1576 if (cube.associate_alpha != MagickFalse)
1577 pixel.alpha+=5*previous[u].alpha/16;
1580 pixel.red+=3*previous[u-v].red/16;
1581 pixel.green+=3*previous[u-v].green/16;
1582 pixel.blue+=3*previous[u-v].blue/16;
1583 if (cube.associate_alpha != MagickFalse)
1584 pixel.alpha+=3*previous[u-v].alpha/16;
1587 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1588 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1589 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1590 if (cube.associate_alpha != MagickFalse)
1591 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
1592 i=CacheOffset(&cube,&pixel);
1593 if (cube.cache[i] < 0)
1602 Identify the deepest node containing the pixel's color.
1604 node_info=cube.root;
1605 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1607 id=ColorToNodeId(&cube,&pixel,index);
1608 if (node_info->child[id] == (NodeInfo *) NULL)
1610 node_info=node_info->child[id];
1613 Find closest color among siblings and their children.
1616 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1618 ClosestColor(image,&cube,node_info->parent);
1619 cube.cache[i]=(ssize_t) cube.color_number;
1622 Assign pixel to closest colormap entry.
1624 index=(size_t) cube.cache[i];
1625 if (image->storage_class == PseudoClass)
1626 SetPixelIndex(image,(Quantum) index,q);
1627 if (cube.quantize_info->measure_error == MagickFalse)
1629 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1630 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1631 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1632 if (cube.associate_alpha != MagickFalse)
1633 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1635 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1640 AssociateAlphaPixelInfo(image,&cube,image->colormap+index,&color);
1641 current[u].red=pixel.red-color.red;
1642 current[u].green=pixel.green-color.green;
1643 current[u].blue=pixel.blue-color.blue;
1644 if (cube.associate_alpha != MagickFalse)
1645 current[u].alpha=pixel.alpha-color.alpha;
1646 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1651 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1652 #pragma omp critical (MagickCore_FloydSteinbergDither)
1654 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1656 if (proceed == MagickFalse)
1659 q+=((y+1) & 0x01)*GetPixelChannels(image);
1662 image_view=DestroyCacheView(image_view);
1663 pixels=DestroyPixelThreadSet(pixels);
1667 static MagickBooleanType
1668 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1669 ExceptionInfo *exception);
1671 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1672 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1679 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1681 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1683 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1689 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1691 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1693 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1699 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1701 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1703 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1709 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1711 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1713 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1725 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1727 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1729 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1731 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1733 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1735 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1737 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1743 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1745 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1747 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1749 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1751 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1753 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1755 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1761 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1763 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1765 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1767 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1769 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1771 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1773 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1779 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1781 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1783 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1785 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1787 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1789 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1791 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1800 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1801 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1803 #define DitherImageTag "Dither/Image"
1819 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1820 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1831 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1832 if (q == (Quantum *) NULL)
1833 return(MagickFalse);
1834 AssociateAlphaPixel(image,cube_info,q,&pixel);
1835 for (i=0; i < ErrorQueueLength; i++)
1837 pixel.red+=p->weights[i]*p->error[i].red;
1838 pixel.green+=p->weights[i]*p->error[i].green;
1839 pixel.blue+=p->weights[i]*p->error[i].blue;
1840 if (cube_info->associate_alpha != MagickFalse)
1841 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1843 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1844 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1845 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1846 if (cube_info->associate_alpha != MagickFalse)
1847 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
1848 i=CacheOffset(cube_info,&pixel);
1849 if (p->cache[i] < 0)
1858 Identify the deepest node containing the pixel's color.
1861 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1863 id=ColorToNodeId(cube_info,&pixel,index);
1864 if (node_info->child[id] == (NodeInfo *) NULL)
1866 node_info=node_info->child[id];
1868 node_info=node_info->parent;
1870 Find closest color among siblings and their children.
1873 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1874 QuantumRange+1.0)+1.0);
1875 ClosestColor(image,p,node_info->parent);
1876 p->cache[i]=(ssize_t) p->color_number;
1879 Assign pixel to closest colormap entry.
1881 index=(size_t) p->cache[i];
1882 if (image->storage_class == PseudoClass)
1883 SetPixelIndex(image,(Quantum) index,q);
1884 if (cube_info->quantize_info->measure_error == MagickFalse)
1886 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1887 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1888 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1889 if (cube_info->associate_alpha != MagickFalse)
1890 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1892 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1893 return(MagickFalse);
1895 Propagate the error as the last entry of the error queue.
1897 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1898 sizeof(p->error[0]));
1899 AssociateAlphaPixelInfo(image,cube_info,image->colormap+index,&color);
1900 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1901 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1902 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1903 if (cube_info->associate_alpha != MagickFalse)
1904 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1905 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1906 if (proceed == MagickFalse)
1907 return(MagickFalse);
1912 case WestGravity: p->x--; break;
1913 case EastGravity: p->x++; break;
1914 case NorthGravity: p->y--; break;
1915 case SouthGravity: p->y++; break;
1920 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1927 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1934 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1935 ExceptionInfo *exception)
1949 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1950 return(FloydSteinbergDither(image,cube_info,exception));
1952 Distribute quantization error along a Hilbert curve.
1954 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1955 sizeof(*cube_info->error));
1958 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1959 for (depth=1; i != 0; depth++)
1961 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1963 cube_info->offset=0;
1964 cube_info->span=(MagickSizeType) image->columns*image->rows;
1965 image_view=AcquireCacheView(image);
1967 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1968 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1969 image_view=DestroyCacheView(image_view);
1974 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1978 + G e t C u b e I n f o %
1982 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1984 % GetCubeInfo() initialize the Cube data structure.
1986 % The format of the GetCubeInfo method is:
1988 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1989 % const size_t depth,const size_t maximum_colors)
1991 % A description of each parameter follows.
1993 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1995 % o depth: Normally, this integer value is zero or one. A zero or
1996 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1997 % A tree of this depth generally allows the best representation of the
1998 % reference image with the least amount of memory and the fastest
1999 % computational speed. In some cases, such as an image with low color
2000 % dispersion (a few number of colors), a value other than
2001 % Log4(number_colors) is required. To expand the color tree completely,
2004 % o maximum_colors: maximum colors.
2007 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2008 const size_t depth,const size_t maximum_colors)
2024 Initialize tree to describe color cube_info.
2026 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2027 if (cube_info == (CubeInfo *) NULL)
2028 return((CubeInfo *) NULL);
2029 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2030 cube_info->depth=depth;
2031 if (cube_info->depth > MaxTreeDepth)
2032 cube_info->depth=MaxTreeDepth;
2033 if (cube_info->depth < 2)
2035 cube_info->maximum_colors=maximum_colors;
2037 Initialize root node.
2039 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2040 if (cube_info->root == (NodeInfo *) NULL)
2041 return((CubeInfo *) NULL);
2042 cube_info->root->parent=cube_info->root;
2043 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2044 if (cube_info->quantize_info->dither == MagickFalse)
2047 Initialize dither resources.
2049 length=(size_t) (1UL << (4*(8-CacheShift)));
2050 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
2051 sizeof(*cube_info->cache));
2052 if (cube_info->cache == (ssize_t *) NULL)
2053 return((CubeInfo *) NULL);
2055 Initialize color cache.
2057 for (i=0; i < (ssize_t) length; i++)
2058 cube_info->cache[i]=(-1);
2060 Distribute weights along a curve of exponential decay.
2063 for (i=0; i < ErrorQueueLength; i++)
2065 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2066 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2069 Normalize the weighting factors.
2072 for (i=0; i < ErrorQueueLength; i++)
2073 weight+=cube_info->weights[i];
2075 for (i=0; i < ErrorQueueLength; i++)
2077 cube_info->weights[i]/=weight;
2078 sum+=cube_info->weights[i];
2080 cube_info->weights[0]+=1.0-sum;
2085 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2089 + G e t N o d e I n f o %
2093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2095 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2096 % presets all fields to zero.
2098 % The format of the GetNodeInfo method is:
2100 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2101 % const size_t level,NodeInfo *parent)
2103 % A description of each parameter follows.
2105 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2107 % o id: Specifies the child number of the node.
2109 % o level: Specifies the level in the storage_class the node resides.
2112 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2113 const size_t level,NodeInfo *parent)
2118 if (cube_info->free_nodes == 0)
2124 Allocate a new queue of nodes.
2126 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2127 if (nodes == (Nodes *) NULL)
2128 return((NodeInfo *) NULL);
2129 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2130 sizeof(*nodes->nodes));
2131 if (nodes->nodes == (NodeInfo *) NULL)
2132 return((NodeInfo *) NULL);
2133 nodes->next=cube_info->node_queue;
2134 cube_info->node_queue=nodes;
2135 cube_info->next_node=nodes->nodes;
2136 cube_info->free_nodes=NodesInAList;
2139 cube_info->free_nodes--;
2140 node_info=cube_info->next_node++;
2141 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2142 node_info->parent=parent;
2144 node_info->level=level;
2149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2153 % G e t I m a g e Q u a n t i z e E r r o r %
2157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2159 % GetImageQuantizeError() measures the difference between the original
2160 % and quantized images. This difference is the total quantization error.
2161 % The error is computed by summing over all pixels in an image the distance
2162 % squared in RGB space between each reference pixel value and its quantized
2163 % value. These values are computed:
2165 % o mean_error_per_pixel: This value is the mean error for any single
2166 % pixel in the image.
2168 % o normalized_mean_square_error: This value is the normalized mean
2169 % quantization error for any single pixel in the image. This distance
2170 % measure is normalized to a range between 0 and 1. It is independent
2171 % of the range of red, green, and blue values in the image.
2173 % o normalized_maximum_square_error: Thsi value is the normalized
2174 % maximum quantization error for any single pixel in the image. This
2175 % distance measure is normalized to a range between 0 and 1. It is
2176 % independent of the range of red, green, and blue values in your image.
2178 % The format of the GetImageQuantizeError method is:
2180 % MagickBooleanType GetImageQuantizeError(Image *image,
2181 % ExceptionInfo *exception)
2183 % A description of each parameter follows.
2185 % o image: the image.
2187 % o exception: return any errors or warnings in this structure.
2190 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2191 ExceptionInfo *exception)
2203 mean_error_per_pixel;
2211 assert(image != (Image *) NULL);
2212 assert(image->signature == MagickSignature);
2213 if (image->debug != MagickFalse)
2214 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2215 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2216 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2217 if (image->storage_class == DirectClass)
2221 area=3.0*image->columns*image->rows;
2223 mean_error_per_pixel=0.0;
2225 image_view=AcquireCacheView(image);
2226 for (y=0; y < (ssize_t) image->rows; y++)
2228 register const Quantum
2234 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2235 if (p == (const Quantum *) NULL)
2237 for (x=0; x < (ssize_t) image->columns; x++)
2239 index=1UL*GetPixelIndex(image,p);
2240 if (image->matte != MagickFalse)
2242 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,p));
2243 beta=(MagickRealType) (QuantumScale*image->colormap[index].alpha);
2245 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2246 image->colormap[index].red);
2247 mean_error_per_pixel+=distance;
2248 mean_error+=distance*distance;
2249 if (distance > maximum_error)
2250 maximum_error=distance;
2251 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2252 image->colormap[index].green);
2253 mean_error_per_pixel+=distance;
2254 mean_error+=distance*distance;
2255 if (distance > maximum_error)
2256 maximum_error=distance;
2257 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2258 image->colormap[index].blue);
2259 mean_error_per_pixel+=distance;
2260 mean_error+=distance*distance;
2261 if (distance > maximum_error)
2262 maximum_error=distance;
2263 p+=GetPixelChannels(image);
2266 image_view=DestroyCacheView(image_view);
2267 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2268 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2270 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2275 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2279 % G e t Q u a n t i z e I n f o %
2283 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2285 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2287 % The format of the GetQuantizeInfo method is:
2289 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2291 % A description of each parameter follows:
2293 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2296 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2298 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2299 assert(quantize_info != (QuantizeInfo *) NULL);
2300 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2301 quantize_info->number_colors=256;
2302 quantize_info->dither=MagickTrue;
2303 quantize_info->dither_method=RiemersmaDitherMethod;
2304 quantize_info->colorspace=UndefinedColorspace;
2305 quantize_info->measure_error=MagickFalse;
2306 quantize_info->signature=MagickSignature;
2310 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2314 % P o s t e r i z e I m a g e %
2318 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2320 % PosterizeImage() reduces the image to a limited number of colors for a
2323 % The format of the PosterizeImage method is:
2325 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2326 % const MagickBooleanType dither,ExceptionInfo *exception)
2328 % A description of each parameter follows:
2330 % o image: Specifies a pointer to an Image structure.
2332 % o levels: Number of color levels allowed in each channel. Very low values
2333 % (2, 3, or 4) have the most visible effect.
2335 % o dither: Set this integer value to something other than zero to dither
2338 % o exception: return any errors or warnings in this structure.
2342 static inline ssize_t MagickRound(MagickRealType x)
2345 Round the fraction to nearest integer.
2348 return((ssize_t) (x+0.5));
2349 return((ssize_t) (x-0.5));
2352 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2353 const MagickBooleanType dither,ExceptionInfo *exception)
2355 #define PosterizeImageTag "Posterize/Image"
2356 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2357 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2377 assert(image != (Image *) NULL);
2378 assert(image->signature == MagickSignature);
2379 if (image->debug != MagickFalse)
2380 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2381 if (image->storage_class == PseudoClass)
2382 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2383 #pragma omp parallel for schedule(static,4) shared(progress,status)
2385 for (i=0; i < (ssize_t) image->colors; i++)
2390 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2391 image->colormap[i].red=(double)
2392 PosterizePixel(image->colormap[i].red);
2393 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2394 image->colormap[i].green=(double)
2395 PosterizePixel(image->colormap[i].green);
2396 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2397 image->colormap[i].blue=(double)
2398 PosterizePixel(image->colormap[i].blue);
2399 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2400 image->colormap[i].alpha=(double)
2401 PosterizePixel(image->colormap[i].alpha);
2408 image_view=AcquireCacheView(image);
2409 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2410 #pragma omp parallel for schedule(static,4) shared(progress,status)
2412 for (y=0; y < (ssize_t) image->rows; y++)
2420 if (status == MagickFalse)
2422 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2423 if (q == (Quantum *) NULL)
2428 for (x=0; x < (ssize_t) image->columns; x++)
2430 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2431 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2432 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2433 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2434 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2435 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2436 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2437 (image->colorspace == CMYKColorspace))
2438 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2439 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2440 (image->matte == MagickTrue))
2441 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2442 q+=GetPixelChannels(image);
2444 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2446 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2451 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2452 #pragma omp critical (MagickCore_PosterizeImage)
2454 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2456 if (proceed == MagickFalse)
2460 image_view=DestroyCacheView(image_view);
2461 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2462 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2463 levels,MaxColormapSize+1);
2464 quantize_info->dither=dither;
2465 quantize_info->tree_depth=MaxTreeDepth;
2466 status=QuantizeImage(quantize_info,image,exception);
2467 quantize_info=DestroyQuantizeInfo(quantize_info);
2472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2476 + P r u n e C h i l d %
2480 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2482 % PruneChild() deletes the given node and merges its statistics into its
2485 % The format of the PruneSubtree method is:
2487 % PruneChild(const Image *image,CubeInfo *cube_info,
2488 % const NodeInfo *node_info)
2490 % A description of each parameter follows.
2492 % o image: the image.
2494 % o cube_info: A pointer to the Cube structure.
2496 % o node_info: pointer to node in color cube tree that is to be pruned.
2499 static void PruneChild(const Image *image,CubeInfo *cube_info,
2500 const NodeInfo *node_info)
2512 Traverse any children.
2514 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2515 for (i=0; i < (ssize_t) number_children; i++)
2516 if (node_info->child[i] != (NodeInfo *) NULL)
2517 PruneChild(image,cube_info,node_info->child[i]);
2519 Merge color statistics into parent.
2521 parent=node_info->parent;
2522 parent->number_unique+=node_info->number_unique;
2523 parent->total_color.red+=node_info->total_color.red;
2524 parent->total_color.green+=node_info->total_color.green;
2525 parent->total_color.blue+=node_info->total_color.blue;
2526 parent->total_color.alpha+=node_info->total_color.alpha;
2527 parent->child[node_info->id]=(NodeInfo *) NULL;
2532 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2536 + P r u n e L e v e l %
2540 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2542 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2543 % their color statistics into their parent node.
2545 % The format of the PruneLevel method is:
2547 % PruneLevel(const Image *image,CubeInfo *cube_info,
2548 % const NodeInfo *node_info)
2550 % A description of each parameter follows.
2552 % o image: the image.
2554 % o cube_info: A pointer to the Cube structure.
2556 % o node_info: pointer to node in color cube tree that is to be pruned.
2559 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2560 const NodeInfo *node_info)
2569 Traverse any children.
2571 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2572 for (i=0; i < (ssize_t) number_children; i++)
2573 if (node_info->child[i] != (NodeInfo *) NULL)
2574 PruneLevel(image,cube_info,node_info->child[i]);
2575 if (node_info->level == cube_info->depth)
2576 PruneChild(image,cube_info,node_info);
2580 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2584 + P r u n e T o C u b e D e p t h %
2588 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2590 % PruneToCubeDepth() deletes any nodes at a depth greater than
2591 % cube_info->depth while merging their color statistics into their parent
2594 % The format of the PruneToCubeDepth method is:
2596 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2597 % const NodeInfo *node_info)
2599 % A description of each parameter follows.
2601 % o cube_info: A pointer to the Cube structure.
2603 % o node_info: pointer to node in color cube tree that is to be pruned.
2606 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2607 const NodeInfo *node_info)
2616 Traverse any children.
2618 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2619 for (i=0; i < (ssize_t) number_children; i++)
2620 if (node_info->child[i] != (NodeInfo *) NULL)
2621 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2622 if (node_info->level > cube_info->depth)
2623 PruneChild(image,cube_info,node_info);
2627 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2631 % Q u a n t i z e I m a g e %
2635 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2637 % QuantizeImage() analyzes the colors within a reference image and chooses a
2638 % fixed number of colors to represent the image. The goal of the algorithm
2639 % is to minimize the color difference between the input and output image while
2640 % minimizing the processing time.
2642 % The format of the QuantizeImage method is:
2644 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2645 % Image *image,ExceptionInfo *exception)
2647 % A description of each parameter follows:
2649 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2651 % o image: the image.
2653 % o exception: return any errors or warnings in this structure.
2657 static MagickBooleanType DirectToColormapImage(Image *image,
2658 ExceptionInfo *exception)
2676 number_colors=(size_t) (image->columns*image->rows);
2677 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2678 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2680 if (image->colors != number_colors)
2681 return(MagickFalse);
2683 image_view=AcquireCacheView(image);
2684 for (y=0; y < (ssize_t) image->rows; y++)
2695 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2696 if (q == (Quantum *) NULL)
2698 for (x=0; x < (ssize_t) image->columns; x++)
2700 image->colormap[i].red=(double) GetPixelRed(image,q);
2701 image->colormap[i].green=(double) GetPixelGreen(image,q);
2702 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2703 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2704 SetPixelIndex(image,(Quantum) i,q);
2706 q+=GetPixelChannels(image);
2708 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2710 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2712 if (proceed == MagickFalse)
2715 image_view=DestroyCacheView(image_view);
2719 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2720 Image *image,ExceptionInfo *exception)
2732 assert(quantize_info != (const QuantizeInfo *) NULL);
2733 assert(quantize_info->signature == MagickSignature);
2734 assert(image != (Image *) NULL);
2735 assert(image->signature == MagickSignature);
2736 if (image->debug != MagickFalse)
2737 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2738 maximum_colors=quantize_info->number_colors;
2739 if (maximum_colors == 0)
2740 maximum_colors=MaxColormapSize;
2741 if (maximum_colors > MaxColormapSize)
2742 maximum_colors=MaxColormapSize;
2743 if ((image->columns*image->rows) <= maximum_colors)
2744 (void) DirectToColormapImage(image,exception);
2745 if ((IsImageGray(image,exception) != MagickFalse) &&
2746 (image->matte == MagickFalse))
2747 (void) SetGrayscaleImage(image,exception);
2748 if ((image->storage_class == PseudoClass) &&
2749 (image->colors <= maximum_colors))
2751 depth=quantize_info->tree_depth;
2758 Depth of color tree is: Log4(colormap size)+2.
2760 colors=maximum_colors;
2761 for (depth=1; colors != 0; depth++)
2763 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2765 if ((image->matte != MagickFalse) && (depth > 5))
2769 Initialize color cube.
2771 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2772 if (cube_info == (CubeInfo *) NULL)
2773 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2775 status=ClassifyImageColors(cube_info,image,exception);
2776 if (status != MagickFalse)
2779 Reduce the number of colors in the image.
2781 ReduceImageColors(image,cube_info);
2782 status=AssignImageColors(image,cube_info,exception);
2784 DestroyCubeInfo(cube_info);
2789 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2793 % Q u a n t i z e I m a g e s %
2797 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2799 % QuantizeImages() analyzes the colors within a set of reference images and
2800 % chooses a fixed number of colors to represent the set. The goal of the
2801 % algorithm is to minimize the color difference between the input and output
2802 % images while minimizing the processing time.
2804 % The format of the QuantizeImages method is:
2806 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2807 % Image *images,ExceptionInfo *exception)
2809 % A description of each parameter follows:
2811 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2813 % o images: Specifies a pointer to a list of Image structures.
2815 % o exception: return any errors or warnings in this structure.
2818 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2819 Image *images,ExceptionInfo *exception)
2831 MagickProgressMonitor
2842 assert(quantize_info != (const QuantizeInfo *) NULL);
2843 assert(quantize_info->signature == MagickSignature);
2844 assert(images != (Image *) NULL);
2845 assert(images->signature == MagickSignature);
2846 if (images->debug != MagickFalse)
2847 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2848 if (GetNextImageInList(images) == (Image *) NULL)
2851 Handle a single image with QuantizeImage.
2853 status=QuantizeImage(quantize_info,images,exception);
2857 maximum_colors=quantize_info->number_colors;
2858 if (maximum_colors == 0)
2859 maximum_colors=MaxColormapSize;
2860 if (maximum_colors > MaxColormapSize)
2861 maximum_colors=MaxColormapSize;
2862 depth=quantize_info->tree_depth;
2869 Depth of color tree is: Log4(colormap size)+2.
2871 colors=maximum_colors;
2872 for (depth=1; colors != 0; depth++)
2874 if (quantize_info->dither != MagickFalse)
2878 Initialize color cube.
2880 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2881 if (cube_info == (CubeInfo *) NULL)
2883 (void) ThrowMagickException(exception,GetMagickModule(),
2884 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2885 return(MagickFalse);
2887 number_images=GetImageListLength(images);
2889 for (i=0; image != (Image *) NULL; i++)
2891 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2892 image->client_data);
2893 status=ClassifyImageColors(cube_info,image,exception);
2894 if (status == MagickFalse)
2896 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2897 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2899 if (proceed == MagickFalse)
2901 image=GetNextImageInList(image);
2903 if (status != MagickFalse)
2906 Reduce the number of colors in an image sequence.
2908 ReduceImageColors(images,cube_info);
2910 for (i=0; image != (Image *) NULL; i++)
2912 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2913 NULL,image->client_data);
2914 status=AssignImageColors(image,cube_info,exception);
2915 if (status == MagickFalse)
2917 (void) SetImageProgressMonitor(image,progress_monitor,
2918 image->client_data);
2919 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2921 if (proceed == MagickFalse)
2923 image=GetNextImageInList(image);
2926 DestroyCubeInfo(cube_info);
2931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2939 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2941 % Reduce() traverses the color cube tree and prunes any node whose
2942 % quantization error falls below a particular threshold.
2944 % The format of the Reduce method is:
2946 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2948 % A description of each parameter follows.
2950 % o image: the image.
2952 % o cube_info: A pointer to the Cube structure.
2954 % o node_info: pointer to node in color cube tree that is to be pruned.
2957 static void Reduce(const Image *image,CubeInfo *cube_info,
2958 const NodeInfo *node_info)
2967 Traverse any children.
2969 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2970 for (i=0; i < (ssize_t) number_children; i++)
2971 if (node_info->child[i] != (NodeInfo *) NULL)
2972 Reduce(image,cube_info,node_info->child[i]);
2973 if (node_info->quantize_error <= cube_info->pruning_threshold)
2974 PruneChild(image,cube_info,node_info);
2978 Find minimum pruning threshold.
2980 if (node_info->number_unique > 0)
2981 cube_info->colors++;
2982 if (node_info->quantize_error < cube_info->next_threshold)
2983 cube_info->next_threshold=node_info->quantize_error;
2988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2992 + R e d u c e I m a g e C o l o r s %
2996 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2998 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2999 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3000 % in the output image. On any given iteration over the tree, it selects
3001 % those nodes whose E value is minimal for pruning and merges their
3002 % color statistics upward. It uses a pruning threshold, Ep, to govern
3003 % node selection as follows:
3006 % while number of nodes with (n2 > 0) > required maximum number of colors
3007 % prune all nodes such that E <= Ep
3008 % Set Ep to minimum E in remaining nodes
3010 % This has the effect of minimizing any quantization error when merging
3011 % two nodes together.
3013 % When a node to be pruned has offspring, the pruning procedure invokes
3014 % itself recursively in order to prune the tree from the leaves upward.
3015 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3016 % corresponding data in that node's parent. This retains the pruned
3017 % node's color characteristics for later averaging.
3019 % For each node, n2 pixels exist for which that node represents the
3020 % smallest volume in RGB space containing those pixel's colors. When n2
3021 % > 0 the node will uniquely define a color in the output image. At the
3022 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3023 % the tree which represent colors present in the input image.
3025 % The other pixel count, n1, indicates the total number of colors
3026 % within the cubic volume which the node represents. This includes n1 -
3027 % n2 pixels whose colors should be defined by nodes at a lower level in
3030 % The format of the ReduceImageColors method is:
3032 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3034 % A description of each parameter follows.
3036 % o image: the image.
3038 % o cube_info: A pointer to the Cube structure.
3041 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3043 #define ReduceImageTag "Reduce/Image"
3054 cube_info->next_threshold=0.0;
3055 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3057 cube_info->pruning_threshold=cube_info->next_threshold;
3058 cube_info->next_threshold=cube_info->root->quantize_error-1;
3059 cube_info->colors=0;
3060 Reduce(image,cube_info,cube_info->root);
3061 offset=(MagickOffsetType) span-cube_info->colors;
3062 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3063 cube_info->maximum_colors+1);
3064 if (proceed == MagickFalse)
3070 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3074 % R e m a p I m a g e %
3078 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3080 % RemapImage() replaces the colors of an image with a dither of the colors
3083 % The format of the RemapImage method is:
3085 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3086 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3088 % A description of each parameter follows:
3090 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3092 % o image: the image.
3094 % o remap_image: the reference image.
3096 % o exception: return any errors or warnings in this structure.
3099 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3100 Image *image,const Image *remap_image,ExceptionInfo *exception)
3109 Initialize color cube.
3111 assert(image != (Image *) NULL);
3112 assert(image->signature == MagickSignature);
3113 if (image->debug != MagickFalse)
3114 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3115 assert(remap_image != (Image *) NULL);
3116 assert(remap_image->signature == MagickSignature);
3117 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3118 quantize_info->number_colors);
3119 if (cube_info == (CubeInfo *) NULL)
3120 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3122 status=ClassifyImageColors(cube_info,remap_image,exception);
3123 if (status != MagickFalse)
3126 Classify image colors from the reference image.
3128 cube_info->quantize_info->number_colors=cube_info->colors;
3129 status=AssignImageColors(image,cube_info,exception);
3131 DestroyCubeInfo(cube_info);
3136 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3140 % R e m a p I m a g e s %
3144 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3146 % RemapImages() replaces the colors of a sequence of images with the
3147 % closest color from a reference image.
3149 % The format of the RemapImage method is:
3151 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3152 % Image *images,Image *remap_image,ExceptionInfo *exception)
3154 % A description of each parameter follows:
3156 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3158 % o images: the image sequence.
3160 % o remap_image: the reference image.
3162 % o exception: return any errors or warnings in this structure.
3165 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3166 Image *images,const Image *remap_image,ExceptionInfo *exception)
3177 assert(images != (Image *) NULL);
3178 assert(images->signature == MagickSignature);
3179 if (images->debug != MagickFalse)
3180 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3182 if (remap_image == (Image *) NULL)
3185 Create a global colormap for an image sequence.
3187 status=QuantizeImages(quantize_info,images,exception);
3191 Classify image colors from the reference image.
3193 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3194 quantize_info->number_colors);
3195 if (cube_info == (CubeInfo *) NULL)
3196 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3198 status=ClassifyImageColors(cube_info,remap_image,exception);
3199 if (status != MagickFalse)
3202 Classify image colors from the reference image.
3204 cube_info->quantize_info->number_colors=cube_info->colors;
3206 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3208 status=AssignImageColors(image,cube_info,exception);
3209 if (status == MagickFalse)
3213 DestroyCubeInfo(cube_info);
3218 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3222 % S e t G r a y s c a l e I m a g e %
3226 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3228 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3230 % The format of the SetGrayscaleImage method is:
3232 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3234 % A description of each parameter follows:
3236 % o image: The image.
3238 % o exception: return any errors or warnings in this structure.
3242 #if defined(__cplusplus) || defined(c_plusplus)
3246 static int IntensityCompare(const void *x,const void *y)
3255 color_1=(PixelInfo *) x;
3256 color_2=(PixelInfo *) y;
3257 intensity=GetPixelInfoIntensity(color_1)-(ssize_t)
3258 GetPixelInfoIntensity(color_2);
3259 return((int) intensity);
3262 #if defined(__cplusplus) || defined(c_plusplus)
3266 static MagickBooleanType SetGrayscaleImage(Image *image,
3267 ExceptionInfo *exception)
3286 assert(image != (Image *) NULL);
3287 assert(image->signature == MagickSignature);
3288 if (image->type != GrayscaleType)
3289 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3290 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3291 sizeof(*colormap_index));
3292 if (colormap_index == (ssize_t *) NULL)
3293 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3295 if (image->storage_class != PseudoClass)
3297 for (i=0; i <= (ssize_t) MaxMap; i++)
3298 colormap_index[i]=(-1);
3299 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3300 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3304 image_view=AcquireCacheView(image);
3305 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3306 #pragma omp parallel for schedule(static,4) shared(status)
3308 for (y=0; y < (ssize_t) image->rows; y++)
3316 if (status == MagickFalse)
3318 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3320 if (q == (Quantum *) NULL)
3325 for (x=0; x < (ssize_t) image->columns; x++)
3330 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3331 if (colormap_index[intensity] < 0)
3333 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3334 #pragma omp critical (MagickCore_SetGrayscaleImage)
3336 if (colormap_index[intensity] < 0)
3338 colormap_index[intensity]=(ssize_t) image->colors;
3339 image->colormap[image->colors].red=(double)
3340 GetPixelRed(image,q);
3341 image->colormap[image->colors].green=(double)
3342 GetPixelGreen(image,q);
3343 image->colormap[image->colors].blue=(double)
3344 GetPixelBlue(image,q);
3348 SetPixelIndex(image,(Quantum)
3349 colormap_index[intensity],q);
3350 q+=GetPixelChannels(image);
3352 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3355 image_view=DestroyCacheView(image_view);
3357 for (i=0; i < (ssize_t) image->colors; i++)
3358 image->colormap[i].alpha=(double) i;
3359 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3361 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,
3363 if (colormap == (PixelInfo *) NULL)
3364 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3367 colormap[j]=image->colormap[0];
3368 for (i=0; i < (ssize_t) image->colors; i++)
3370 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3373 colormap[j]=image->colormap[i];
3375 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3377 image->colors=(size_t) (j+1);
3378 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3379 image->colormap=colormap;
3381 image_view=AcquireCacheView(image);
3382 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3383 #pragma omp parallel for schedule(static,4) shared(status)
3385 for (y=0; y < (ssize_t) image->rows; y++)
3393 if (status == MagickFalse)
3395 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3396 if (q == (Quantum *) NULL)
3401 for (x=0; x < (ssize_t) image->columns; x++)
3403 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3404 GetPixelIndex(image,q))],q);
3405 q+=GetPixelChannels(image);
3407 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3410 image_view=DestroyCacheView(image_view);
3411 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3412 image->type=GrayscaleType;
3413 if (IsImageMonochrome(image,exception) != MagickFalse)
3414 image->type=BilevelType;