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(dynamic,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,image->colormap[index].red,q);
624 SetPixelGreen(image,image->colormap[index].green,q);
625 SetPixelBlue(image,image->colormap[index].blue,q);
626 if (cube.associate_alpha != MagickFalse)
627 SetPixelAlpha(image,image->colormap[index].alpha,q);
629 q+=GetPixelChannels(image);
632 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
634 if (image->progress_monitor != (MagickProgressMonitor) NULL)
639 #if defined(MAGICKCORE_OPENMP_SUPPORT)
640 #pragma omp critical (MagickCore_AssignImageColors)
642 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
644 if (proceed == MagickFalse)
648 image_view=DestroyCacheView(image_view);
650 if (cube_info->quantize_info->measure_error != MagickFalse)
651 (void) GetImageQuantizeError(image,exception);
652 if ((cube_info->quantize_info->number_colors == 2) &&
653 (cube_info->quantize_info->colorspace == GRAYColorspace))
668 for (i=0; i < (ssize_t) image->colors; i++)
670 intensity=(Quantum) ((MagickRealType) GetPixelInfoIntensity(q) <
671 ((MagickRealType) QuantumRange/2.0) ? 0 : QuantumRange);
678 (void) SyncImage(image,exception);
679 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
680 (cube_info->quantize_info->colorspace != CMYKColorspace))
681 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
686 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
690 + C l a s s i f y I m a g e C o l o r s %
694 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
696 % ClassifyImageColors() begins by initializing a color description tree
697 % of sufficient depth to represent each possible input color in a leaf.
698 % However, it is impractical to generate a fully-formed color
699 % description tree in the storage_class phase for realistic values of
700 % Cmax. If colors components in the input image are quantized to k-bit
701 % precision, so that Cmax= 2k-1, the tree would need k levels below the
702 % root node to allow representing each possible input color in a leaf.
703 % This becomes prohibitive because the tree's total number of nodes is
706 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
707 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
708 % Initializes data structures for nodes only as they are needed; (2)
709 % Chooses a maximum depth for the tree as a function of the desired
710 % number of colors in the output image (currently log2(colormap size)).
712 % For each pixel in the input image, storage_class scans downward from
713 % the root of the color description tree. At each level of the tree it
714 % identifies the single node which represents a cube in RGB space
715 % containing It updates the following data for each such node:
717 % n1 : Number of pixels whose color is contained in the RGB cube
718 % which this node represents;
720 % n2 : Number of pixels whose color is not represented in a node at
721 % lower depth in the tree; initially, n2 = 0 for all nodes except
722 % leaves of the tree.
724 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
725 % all pixels not classified at a lower depth. The combination of
726 % these sums and n2 will ultimately characterize the mean color of a
727 % set of pixels represented by this node.
729 % E: the distance squared in RGB space between each pixel contained
730 % within a node and the nodes' center. This represents the quantization
733 % The format of the ClassifyImageColors() method is:
735 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
736 % const Image *image,ExceptionInfo *exception)
738 % A description of each parameter follows.
740 % o cube_info: A pointer to the Cube structure.
742 % o image: the image.
746 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
751 associate_alpha=image->matte;
752 if (cube_info->quantize_info->colorspace == TransparentColorspace)
753 associate_alpha=MagickFalse;
754 if ((cube_info->quantize_info->number_colors == 2) &&
755 (cube_info->quantize_info->colorspace == GRAYColorspace))
756 associate_alpha=MagickFalse;
757 cube_info->associate_alpha=associate_alpha;
760 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
761 const Image *image,ExceptionInfo *exception)
763 #define ClassifyImageTag "Classify/Image"
793 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
795 SetAssociatedAlpha(image,cube_info);
796 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
797 (cube_info->quantize_info->colorspace != CMYKColorspace))
798 (void) TransformImageColorspace((Image *) image,
799 cube_info->quantize_info->colorspace,exception);
801 if ((image->colorspace != GRAYColorspace) &&
802 (image->colorspace != CMYColorspace) &&
803 (IsRGBColorspace(image->colorspace) == MagickFalse))
804 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
805 midpoint.red=(MagickRealType) QuantumRange/2.0;
806 midpoint.green=(MagickRealType) QuantumRange/2.0;
807 midpoint.blue=(MagickRealType) QuantumRange/2.0;
808 midpoint.alpha=(MagickRealType) QuantumRange/2.0;
810 image_view=AcquireCacheView(image);
811 for (y=0; y < (ssize_t) image->rows; y++)
813 register const Quantum
819 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
820 if (p == (const Quantum *) NULL)
822 if (cube_info->nodes > MaxNodes)
825 Prune one level if the color tree is too large.
827 PruneLevel(image,cube_info,cube_info->root);
830 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
833 Start at the root and descend the color cube tree.
835 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
840 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
841 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
844 AssociateAlphaPixel(image,cube_info,p,&pixel);
845 index=MaxTreeDepth-1;
846 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
848 node_info=cube_info->root;
849 for (level=1; level <= MaxTreeDepth; level++)
852 id=ColorToNodeId(cube_info,&pixel,index);
853 mid.red+=(id & 1) != 0 ? bisect : -bisect;
854 mid.green+=(id & 2) != 0 ? bisect : -bisect;
855 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
856 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
857 if (node_info->child[id] == (NodeInfo *) NULL)
860 Set colors of new node to contain pixel.
862 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
863 if (node_info->child[id] == (NodeInfo *) NULL)
864 (void) ThrowMagickException(exception,GetMagickModule(),
865 ResourceLimitError,"MemoryAllocationFailed","`%s'",
867 if (level == MaxTreeDepth)
871 Approximate the quantization error represented by this node.
873 node_info=node_info->child[id];
874 error.red=QuantumScale*(pixel.red-mid.red);
875 error.green=QuantumScale*(pixel.green-mid.green);
876 error.blue=QuantumScale*(pixel.blue-mid.blue);
877 if (cube_info->associate_alpha != MagickFalse)
878 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
879 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
880 count*error.green*error.green+count*error.blue*error.blue+
881 count*error.alpha*error.alpha));
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*pixel.red;
890 node_info->total_color.green+=count*QuantumScale*pixel.green;
891 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
892 if (cube_info->associate_alpha != MagickFalse)
893 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
894 p+=count*GetPixelChannels(image);
896 if (cube_info->colors > cube_info->maximum_colors)
898 PruneToCubeDepth(image,cube_info,cube_info->root);
901 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
903 if (proceed == MagickFalse)
906 for (y++; y < (ssize_t) image->rows; y++)
908 register const Quantum
914 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
915 if (p == (const Quantum *) NULL)
917 if (cube_info->nodes > MaxNodes)
920 Prune one level if the color tree is too large.
922 PruneLevel(image,cube_info,cube_info->root);
925 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
928 Start at the root and descend the color cube tree.
930 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
935 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
936 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
939 AssociateAlphaPixel(image,cube_info,p,&pixel);
940 index=MaxTreeDepth-1;
941 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
943 node_info=cube_info->root;
944 for (level=1; level <= cube_info->depth; level++)
947 id=ColorToNodeId(cube_info,&pixel,index);
948 mid.red+=(id & 1) != 0 ? bisect : -bisect;
949 mid.green+=(id & 2) != 0 ? bisect : -bisect;
950 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
951 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
952 if (node_info->child[id] == (NodeInfo *) NULL)
955 Set colors of new node to contain pixel.
957 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
958 if (node_info->child[id] == (NodeInfo *) NULL)
959 (void) ThrowMagickException(exception,GetMagickModule(),
960 ResourceLimitError,"MemoryAllocationFailed","%s",
962 if (level == cube_info->depth)
966 Approximate the quantization error represented by this node.
968 node_info=node_info->child[id];
969 error.red=QuantumScale*(pixel.red-mid.red);
970 error.green=QuantumScale*(pixel.green-mid.green);
971 error.blue=QuantumScale*(pixel.blue-mid.blue);
972 if (cube_info->associate_alpha != MagickFalse)
973 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
974 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
975 count*error.green*error.green+count*error.blue*error.blue+
976 count*error.alpha*error.alpha));
977 cube_info->root->quantize_error+=node_info->quantize_error;
981 Sum RGB for this leaf for later derivation of the mean cube color.
983 node_info->number_unique+=count;
984 node_info->total_color.red+=count*QuantumScale*pixel.red;
985 node_info->total_color.green+=count*QuantumScale*pixel.green;
986 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
987 if (cube_info->associate_alpha != MagickFalse)
988 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
989 p+=count*GetPixelChannels(image);
991 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
993 if (proceed == MagickFalse)
996 image_view=DestroyCacheView(image_view);
997 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
998 (cube_info->quantize_info->colorspace != CMYKColorspace))
999 (void) TransformImageColorspace((Image *) image,RGBColorspace,exception);
1004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1008 % C l o n e Q u a n t i z e I n f o %
1012 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1014 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1015 % or if quantize info is NULL, a new one.
1017 % The format of the CloneQuantizeInfo method is:
1019 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1021 % A description of each parameter follows:
1023 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1024 % quantize info, or if image info is NULL a new one.
1026 % o quantize_info: a structure of type info.
1029 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1034 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1035 if (clone_info == (QuantizeInfo *) NULL)
1036 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1037 GetQuantizeInfo(clone_info);
1038 if (quantize_info == (QuantizeInfo *) NULL)
1040 clone_info->number_colors=quantize_info->number_colors;
1041 clone_info->tree_depth=quantize_info->tree_depth;
1042 clone_info->dither=quantize_info->dither;
1043 clone_info->dither_method=quantize_info->dither_method;
1044 clone_info->colorspace=quantize_info->colorspace;
1045 clone_info->measure_error=quantize_info->measure_error;
1050 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1054 + C l o s e s t C o l o r %
1058 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1060 % ClosestColor() traverses the color cube tree at a particular node and
1061 % determines which colormap entry best represents the input color.
1063 % The format of the ClosestColor method is:
1065 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1066 % const NodeInfo *node_info)
1068 % A description of each parameter follows.
1070 % o image: the image.
1072 % o cube_info: A pointer to the Cube structure.
1074 % o node_info: the address of a structure of type NodeInfo which points to a
1075 % node in the color cube tree that is to be pruned.
1078 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1079 const NodeInfo *node_info)
1088 Traverse any children.
1090 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1091 for (i=0; i < (ssize_t) number_children; i++)
1092 if (node_info->child[i] != (NodeInfo *) NULL)
1093 ClosestColor(image,cube_info,node_info->child[i]);
1094 if (node_info->number_unique != 0)
1099 register MagickRealType
1107 register RealPixelInfo
1111 Determine if this color is "closest".
1113 p=image->colormap+node_info->color_number;
1114 q=(&cube_info->target);
1117 if (cube_info->associate_alpha != MagickFalse)
1119 alpha=(MagickRealType) (QuantumScale*p->alpha);
1120 beta=(MagickRealType) (QuantumScale*q->alpha);
1122 pixel=alpha*p->red-beta*q->red;
1123 distance=pixel*pixel;
1124 if (distance <= cube_info->distance)
1126 pixel=alpha*p->green-beta*q->green;
1127 distance+=pixel*pixel;
1128 if (distance <= cube_info->distance)
1130 pixel=alpha*p->blue-beta*q->blue;
1131 distance+=pixel*pixel;
1132 if (distance <= cube_info->distance)
1135 distance+=pixel*pixel;
1136 if (distance <= cube_info->distance)
1138 cube_info->distance=distance;
1139 cube_info->color_number=node_info->color_number;
1148 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1152 % C o m p r e s s I m a g e C o l o r m a p %
1156 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1158 % CompressImageColormap() compresses an image colormap by removing any
1159 % duplicate or unused color entries.
1161 % The format of the CompressImageColormap method is:
1163 % MagickBooleanType CompressImageColormap(Image *image,
1164 % ExceptionInfo *exception)
1166 % A description of each parameter follows:
1168 % o image: the image.
1170 % o exception: return any errors or warnings in this structure.
1173 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1174 ExceptionInfo *exception)
1179 assert(image != (Image *) NULL);
1180 assert(image->signature == MagickSignature);
1181 if (image->debug != MagickFalse)
1182 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1183 if (IsPaletteImage(image,exception) == MagickFalse)
1184 return(MagickFalse);
1185 GetQuantizeInfo(&quantize_info);
1186 quantize_info.number_colors=image->colors;
1187 quantize_info.tree_depth=MaxTreeDepth;
1188 return(QuantizeImage(&quantize_info,image,exception));
1192 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1196 + D e f i n e I m a g e C o l o r m a p %
1200 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1202 % DefineImageColormap() traverses the color cube tree and notes each colormap
1203 % entry. A colormap entry is any node in the color cube tree where the
1204 % of unique colors is not zero. DefineImageColormap() returns the number of
1205 % colors in the image colormap.
1207 % The format of the DefineImageColormap method is:
1209 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1210 % NodeInfo *node_info)
1212 % A description of each parameter follows.
1214 % o image: the image.
1216 % o cube_info: A pointer to the Cube structure.
1218 % o node_info: the address of a structure of type NodeInfo which points to a
1219 % node in the color cube tree that is to be pruned.
1222 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1223 NodeInfo *node_info)
1232 Traverse any children.
1234 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1235 for (i=0; i < (ssize_t) number_children; i++)
1236 if (node_info->child[i] != (NodeInfo *) NULL)
1237 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1238 if (node_info->number_unique != 0)
1240 register MagickRealType
1247 Colormap entry is defined by the mean color in this cube.
1249 q=image->colormap+image->colors;
1250 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1251 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1252 if (cube_info->associate_alpha == MagickFalse)
1254 q->red=ClampToQuantum((MagickRealType)
1255 (alpha*QuantumRange*node_info->total_color.red));
1256 q->green=ClampToQuantum((MagickRealType)
1257 (alpha*QuantumRange*node_info->total_color.green));
1258 q->blue=ClampToQuantum((MagickRealType)
1259 (alpha*QuantumRange*node_info->total_color.blue));
1260 q->alpha=OpaqueAlpha;
1267 opacity=(MagickRealType) (alpha*QuantumRange*
1268 node_info->total_color.alpha);
1269 q->alpha=ClampToQuantum(opacity);
1270 if (q->alpha == OpaqueAlpha)
1272 q->red=ClampToQuantum((MagickRealType)
1273 (alpha*QuantumRange*node_info->total_color.red));
1274 q->green=ClampToQuantum((MagickRealType)
1275 (alpha*QuantumRange*node_info->total_color.green));
1276 q->blue=ClampToQuantum((MagickRealType)
1277 (alpha*QuantumRange*node_info->total_color.blue));
1284 gamma=(MagickRealType) (QuantumScale*q->alpha);
1285 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1286 q->red=ClampToQuantum((MagickRealType)
1287 (alpha*gamma*QuantumRange*node_info->total_color.red));
1288 q->green=ClampToQuantum((MagickRealType)
1289 (alpha*gamma*QuantumRange*node_info->total_color.green));
1290 q->blue=ClampToQuantum((MagickRealType)
1291 (alpha*gamma*QuantumRange*node_info->total_color.blue));
1292 if (node_info->number_unique > cube_info->transparent_pixels)
1294 cube_info->transparent_pixels=node_info->number_unique;
1295 cube_info->transparent_index=(ssize_t) image->colors;
1299 node_info->color_number=image->colors++;
1301 return(image->colors);
1305 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1309 + D e s t r o y C u b e I n f o %
1313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1315 % DestroyCubeInfo() deallocates memory associated with an image.
1317 % The format of the DestroyCubeInfo method is:
1319 % DestroyCubeInfo(CubeInfo *cube_info)
1321 % A description of each parameter follows:
1323 % o cube_info: the address of a structure of type CubeInfo.
1326 static void DestroyCubeInfo(CubeInfo *cube_info)
1332 Release color cube tree storage.
1336 nodes=cube_info->node_queue->next;
1337 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1338 cube_info->node_queue->nodes);
1339 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1340 cube_info->node_queue);
1341 cube_info->node_queue=nodes;
1342 } while (cube_info->node_queue != (Nodes *) NULL);
1343 if (cube_info->cache != (ssize_t *) NULL)
1344 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1345 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1346 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1350 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1354 % D e s t r o y Q u a n t i z e I n f o %
1358 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1360 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1363 % The format of the DestroyQuantizeInfo method is:
1365 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1367 % A description of each parameter follows:
1369 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1372 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1374 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1375 assert(quantize_info != (QuantizeInfo *) NULL);
1376 assert(quantize_info->signature == MagickSignature);
1377 quantize_info->signature=(~MagickSignature);
1378 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1379 return(quantize_info);
1383 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1387 + D i t h e r I m a g e %
1391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1393 % DitherImage() distributes the difference between an original image and
1394 % the corresponding color reduced algorithm to neighboring pixels using
1395 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1396 % MagickTrue if the image is dithered otherwise MagickFalse.
1398 % The format of the DitherImage method is:
1400 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1401 % ExceptionInfo *exception)
1403 % A description of each parameter follows.
1405 % o image: the image.
1407 % o cube_info: A pointer to the Cube structure.
1409 % o exception: return any errors or warnings in this structure.
1413 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1418 assert(pixels != (RealPixelInfo **) NULL);
1419 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1420 if (pixels[i] != (RealPixelInfo *) NULL)
1421 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1422 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1426 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1437 number_threads=GetOpenMPMaximumThreads();
1438 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1440 if (pixels == (RealPixelInfo **) NULL)
1441 return((RealPixelInfo **) NULL);
1442 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1443 for (i=0; i < (ssize_t) number_threads; i++)
1445 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,
1446 2*sizeof(**pixels));
1447 if (pixels[i] == (RealPixelInfo *) NULL)
1448 return(DestroyPixelThreadSet(pixels));
1453 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1454 const RealPixelInfo *pixel)
1456 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1457 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1458 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1459 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1465 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1466 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1467 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1468 if (cube_info->associate_alpha != MagickFalse)
1469 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1474 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1475 ExceptionInfo *exception)
1477 #define DitherImageTag "Dither/Image"
1492 Distribute quantization error using Floyd-Steinberg.
1494 pixels=AcquirePixelThreadSet(image->columns);
1495 if (pixels == (RealPixelInfo **) NULL)
1496 return(MagickFalse);
1498 image_view=AcquireCacheView(image);
1499 for (y=0; y < (ssize_t) image->rows; y++)
1502 id = GetOpenMPThreadId();
1523 if (status == MagickFalse)
1525 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1526 if (q == (Quantum *) NULL)
1531 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
1533 current=pixels[id]+(y & 0x01)*image->columns;
1534 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1535 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1536 for (x=0; x < (ssize_t) image->columns; x++)
1548 q-=(y & 0x01)*GetPixelChannels(image);
1549 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1550 AssociateAlphaPixel(image,&cube,q,&pixel);
1553 pixel.red+=7*current[u-v].red/16;
1554 pixel.green+=7*current[u-v].green/16;
1555 pixel.blue+=7*current[u-v].blue/16;
1556 if (cube.associate_alpha != MagickFalse)
1557 pixel.alpha+=7*current[u-v].alpha/16;
1561 if (x < (ssize_t) (image->columns-1))
1563 pixel.red+=previous[u+v].red/16;
1564 pixel.green+=previous[u+v].green/16;
1565 pixel.blue+=previous[u+v].blue/16;
1566 if (cube.associate_alpha != MagickFalse)
1567 pixel.alpha+=previous[u+v].alpha/16;
1569 pixel.red+=5*previous[u].red/16;
1570 pixel.green+=5*previous[u].green/16;
1571 pixel.blue+=5*previous[u].blue/16;
1572 if (cube.associate_alpha != MagickFalse)
1573 pixel.alpha+=5*previous[u].alpha/16;
1576 pixel.red+=3*previous[u-v].red/16;
1577 pixel.green+=3*previous[u-v].green/16;
1578 pixel.blue+=3*previous[u-v].blue/16;
1579 if (cube.associate_alpha != MagickFalse)
1580 pixel.alpha+=3*previous[u-v].alpha/16;
1583 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1584 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1585 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1586 if (cube.associate_alpha != MagickFalse)
1587 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
1588 i=CacheOffset(&cube,&pixel);
1589 if (cube.cache[i] < 0)
1598 Identify the deepest node containing the pixel's color.
1600 node_info=cube.root;
1601 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1603 id=ColorToNodeId(&cube,&pixel,index);
1604 if (node_info->child[id] == (NodeInfo *) NULL)
1606 node_info=node_info->child[id];
1609 Find closest color among siblings and their children.
1612 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1614 ClosestColor(image,&cube,node_info->parent);
1615 cube.cache[i]=(ssize_t) cube.color_number;
1618 Assign pixel to closest colormap entry.
1620 index=(size_t) cube.cache[i];
1621 if (image->storage_class == PseudoClass)
1622 SetPixelIndex(image,(Quantum) index,q);
1623 if (cube.quantize_info->measure_error == MagickFalse)
1625 SetPixelRed(image,image->colormap[index].red,q);
1626 SetPixelGreen(image,image->colormap[index].green,q);
1627 SetPixelBlue(image,image->colormap[index].blue,q);
1628 if (cube.associate_alpha != MagickFalse)
1629 SetPixelAlpha(image,image->colormap[index].alpha,q);
1631 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1636 AssociateAlphaPixelInfo(image,&cube,image->colormap+index,&color);
1637 current[u].red=pixel.red-color.red;
1638 current[u].green=pixel.green-color.green;
1639 current[u].blue=pixel.blue-color.blue;
1640 if (cube.associate_alpha != MagickFalse)
1641 current[u].alpha=pixel.alpha-color.alpha;
1642 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1647 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1648 #pragma omp critical (MagickCore_FloydSteinbergDither)
1650 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1652 if (proceed == MagickFalse)
1655 q+=((y+1) & 0x01)*GetPixelChannels(image);
1658 image_view=DestroyCacheView(image_view);
1659 pixels=DestroyPixelThreadSet(pixels);
1663 static MagickBooleanType
1664 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1665 ExceptionInfo *exception);
1667 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1668 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1675 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1677 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1679 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1685 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1687 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1689 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1695 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1697 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1699 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1705 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1707 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1709 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1721 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1723 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1725 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1727 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1729 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1731 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1733 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1739 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1741 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1743 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1745 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1747 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1749 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1751 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1757 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1759 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1761 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1763 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1765 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1767 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1769 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1775 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1777 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1779 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1781 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1783 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1785 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1787 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1796 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1797 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1799 #define DitherImageTag "Dither/Image"
1815 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1816 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1827 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1828 if (q == (Quantum *) NULL)
1829 return(MagickFalse);
1830 AssociateAlphaPixel(image,cube_info,q,&pixel);
1831 for (i=0; i < ErrorQueueLength; i++)
1833 pixel.red+=p->weights[i]*p->error[i].red;
1834 pixel.green+=p->weights[i]*p->error[i].green;
1835 pixel.blue+=p->weights[i]*p->error[i].blue;
1836 if (cube_info->associate_alpha != MagickFalse)
1837 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1839 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1840 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1841 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1842 if (cube_info->associate_alpha != MagickFalse)
1843 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
1844 i=CacheOffset(cube_info,&pixel);
1845 if (p->cache[i] < 0)
1854 Identify the deepest node containing the pixel's color.
1857 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1859 id=ColorToNodeId(cube_info,&pixel,index);
1860 if (node_info->child[id] == (NodeInfo *) NULL)
1862 node_info=node_info->child[id];
1864 node_info=node_info->parent;
1866 Find closest color among siblings and their children.
1869 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1870 QuantumRange+1.0)+1.0);
1871 ClosestColor(image,p,node_info->parent);
1872 p->cache[i]=(ssize_t) p->color_number;
1875 Assign pixel to closest colormap entry.
1877 index=(size_t) p->cache[i];
1878 if (image->storage_class == PseudoClass)
1879 SetPixelIndex(image,(Quantum) index,q);
1880 if (cube_info->quantize_info->measure_error == MagickFalse)
1882 SetPixelRed(image,image->colormap[index].red,q);
1883 SetPixelGreen(image,image->colormap[index].green,q);
1884 SetPixelBlue(image,image->colormap[index].blue,q);
1885 if (cube_info->associate_alpha != MagickFalse)
1886 SetPixelAlpha(image,image->colormap[index].alpha,q);
1888 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1889 return(MagickFalse);
1891 Propagate the error as the last entry of the error queue.
1893 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1894 sizeof(p->error[0]));
1895 AssociateAlphaPixelInfo(image,cube_info,image->colormap+index,&color);
1896 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1897 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1898 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1899 if (cube_info->associate_alpha != MagickFalse)
1900 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1901 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1902 if (proceed == MagickFalse)
1903 return(MagickFalse);
1908 case WestGravity: p->x--; break;
1909 case EastGravity: p->x++; break;
1910 case NorthGravity: p->y--; break;
1911 case SouthGravity: p->y++; break;
1916 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1923 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1930 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1931 ExceptionInfo *exception)
1945 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1946 return(FloydSteinbergDither(image,cube_info,exception));
1948 Distribute quantization error along a Hilbert curve.
1950 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1951 sizeof(*cube_info->error));
1954 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1955 for (depth=1; i != 0; depth++)
1957 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1959 cube_info->offset=0;
1960 cube_info->span=(MagickSizeType) image->columns*image->rows;
1961 image_view=AcquireCacheView(image);
1963 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1964 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1965 image_view=DestroyCacheView(image_view);
1970 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1974 + G e t C u b e I n f o %
1978 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1980 % GetCubeInfo() initialize the Cube data structure.
1982 % The format of the GetCubeInfo method is:
1984 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1985 % const size_t depth,const size_t maximum_colors)
1987 % A description of each parameter follows.
1989 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1991 % o depth: Normally, this integer value is zero or one. A zero or
1992 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1993 % A tree of this depth generally allows the best representation of the
1994 % reference image with the least amount of memory and the fastest
1995 % computational speed. In some cases, such as an image with low color
1996 % dispersion (a few number of colors), a value other than
1997 % Log4(number_colors) is required. To expand the color tree completely,
2000 % o maximum_colors: maximum colors.
2003 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2004 const size_t depth,const size_t maximum_colors)
2020 Initialize tree to describe color cube_info.
2022 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2023 if (cube_info == (CubeInfo *) NULL)
2024 return((CubeInfo *) NULL);
2025 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2026 cube_info->depth=depth;
2027 if (cube_info->depth > MaxTreeDepth)
2028 cube_info->depth=MaxTreeDepth;
2029 if (cube_info->depth < 2)
2031 cube_info->maximum_colors=maximum_colors;
2033 Initialize root node.
2035 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2036 if (cube_info->root == (NodeInfo *) NULL)
2037 return((CubeInfo *) NULL);
2038 cube_info->root->parent=cube_info->root;
2039 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2040 if (cube_info->quantize_info->dither == MagickFalse)
2043 Initialize dither resources.
2045 length=(size_t) (1UL << (4*(8-CacheShift)));
2046 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
2047 sizeof(*cube_info->cache));
2048 if (cube_info->cache == (ssize_t *) NULL)
2049 return((CubeInfo *) NULL);
2051 Initialize color cache.
2053 for (i=0; i < (ssize_t) length; i++)
2054 cube_info->cache[i]=(-1);
2056 Distribute weights along a curve of exponential decay.
2059 for (i=0; i < ErrorQueueLength; i++)
2061 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2062 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2065 Normalize the weighting factors.
2068 for (i=0; i < ErrorQueueLength; i++)
2069 weight+=cube_info->weights[i];
2071 for (i=0; i < ErrorQueueLength; i++)
2073 cube_info->weights[i]/=weight;
2074 sum+=cube_info->weights[i];
2076 cube_info->weights[0]+=1.0-sum;
2081 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2085 + G e t N o d e I n f o %
2089 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2091 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2092 % presets all fields to zero.
2094 % The format of the GetNodeInfo method is:
2096 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2097 % const size_t level,NodeInfo *parent)
2099 % A description of each parameter follows.
2101 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2103 % o id: Specifies the child number of the node.
2105 % o level: Specifies the level in the storage_class the node resides.
2108 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2109 const size_t level,NodeInfo *parent)
2114 if (cube_info->free_nodes == 0)
2120 Allocate a new queue of nodes.
2122 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2123 if (nodes == (Nodes *) NULL)
2124 return((NodeInfo *) NULL);
2125 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2126 sizeof(*nodes->nodes));
2127 if (nodes->nodes == (NodeInfo *) NULL)
2128 return((NodeInfo *) NULL);
2129 nodes->next=cube_info->node_queue;
2130 cube_info->node_queue=nodes;
2131 cube_info->next_node=nodes->nodes;
2132 cube_info->free_nodes=NodesInAList;
2135 cube_info->free_nodes--;
2136 node_info=cube_info->next_node++;
2137 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2138 node_info->parent=parent;
2140 node_info->level=level;
2145 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2149 % G e t I m a g e Q u a n t i z e E r r o r %
2153 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2155 % GetImageQuantizeError() measures the difference between the original
2156 % and quantized images. This difference is the total quantization error.
2157 % The error is computed by summing over all pixels in an image the distance
2158 % squared in RGB space between each reference pixel value and its quantized
2159 % value. These values are computed:
2161 % o mean_error_per_pixel: This value is the mean error for any single
2162 % pixel in the image.
2164 % o normalized_mean_square_error: This value is the normalized mean
2165 % quantization error for any single pixel in the image. This distance
2166 % measure is normalized to a range between 0 and 1. It is independent
2167 % of the range of red, green, and blue values in the image.
2169 % o normalized_maximum_square_error: Thsi value is the normalized
2170 % maximum quantization error for any single pixel in the image. This
2171 % distance measure is normalized to a range between 0 and 1. It is
2172 % independent of the range of red, green, and blue values in your image.
2174 % The format of the GetImageQuantizeError method is:
2176 % MagickBooleanType GetImageQuantizeError(Image *image,
2177 % ExceptionInfo *exception)
2179 % A description of each parameter follows.
2181 % o image: the image.
2183 % o exception: return any errors or warnings in this structure.
2186 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2187 ExceptionInfo *exception)
2199 mean_error_per_pixel;
2207 assert(image != (Image *) NULL);
2208 assert(image->signature == MagickSignature);
2209 if (image->debug != MagickFalse)
2210 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2211 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2212 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2213 if (image->storage_class == DirectClass)
2217 area=3.0*image->columns*image->rows;
2219 mean_error_per_pixel=0.0;
2221 image_view=AcquireCacheView(image);
2222 for (y=0; y < (ssize_t) image->rows; y++)
2224 register const Quantum
2230 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2231 if (p == (const Quantum *) NULL)
2233 for (x=0; x < (ssize_t) image->columns; x++)
2235 index=1UL*GetPixelIndex(image,p);
2236 if (image->matte != MagickFalse)
2238 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,p));
2239 beta=(MagickRealType) (QuantumScale*image->colormap[index].alpha);
2241 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2242 image->colormap[index].red);
2243 mean_error_per_pixel+=distance;
2244 mean_error+=distance*distance;
2245 if (distance > maximum_error)
2246 maximum_error=distance;
2247 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2248 image->colormap[index].green);
2249 mean_error_per_pixel+=distance;
2250 mean_error+=distance*distance;
2251 if (distance > maximum_error)
2252 maximum_error=distance;
2253 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2254 image->colormap[index].blue);
2255 mean_error_per_pixel+=distance;
2256 mean_error+=distance*distance;
2257 if (distance > maximum_error)
2258 maximum_error=distance;
2259 p+=GetPixelChannels(image);
2262 image_view=DestroyCacheView(image_view);
2263 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2264 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2266 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2271 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2275 % G e t Q u a n t i z e I n f o %
2279 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2281 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2283 % The format of the GetQuantizeInfo method is:
2285 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2287 % A description of each parameter follows:
2289 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2292 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2294 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2295 assert(quantize_info != (QuantizeInfo *) NULL);
2296 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2297 quantize_info->number_colors=256;
2298 quantize_info->dither=MagickTrue;
2299 quantize_info->dither_method=RiemersmaDitherMethod;
2300 quantize_info->colorspace=UndefinedColorspace;
2301 quantize_info->measure_error=MagickFalse;
2302 quantize_info->signature=MagickSignature;
2306 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2310 % P o s t e r i z e I m a g e %
2314 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2316 % PosterizeImage() reduces the image to a limited number of colors for a
2319 % The format of the PosterizeImage method is:
2321 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2322 % const MagickBooleanType dither,ExceptionInfo *exception)
2324 % A description of each parameter follows:
2326 % o image: Specifies a pointer to an Image structure.
2328 % o levels: Number of color levels allowed in each channel. Very low values
2329 % (2, 3, or 4) have the most visible effect.
2331 % o dither: Set this integer value to something other than zero to dither
2334 % o exception: return any errors or warnings in this structure.
2338 static inline ssize_t MagickRound(MagickRealType x)
2341 Round the fraction to nearest integer.
2344 return((ssize_t) (x+0.5));
2345 return((ssize_t) (x-0.5));
2348 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2349 const MagickBooleanType dither,ExceptionInfo *exception)
2351 #define PosterizeImageTag "Posterize/Image"
2352 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2353 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2373 assert(image != (Image *) NULL);
2374 assert(image->signature == MagickSignature);
2375 if (image->debug != MagickFalse)
2376 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2377 if (image->storage_class == PseudoClass)
2378 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2379 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2381 for (i=0; i < (ssize_t) image->colors; i++)
2386 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2387 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2388 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2389 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2390 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2391 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2392 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2393 image->colormap[i].alpha=PosterizePixel(image->colormap[i].alpha);
2400 image_view=AcquireCacheView(image);
2401 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2402 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2404 for (y=0; y < (ssize_t) image->rows; y++)
2412 if (status == MagickFalse)
2414 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2415 if (q == (Quantum *) NULL)
2420 for (x=0; x < (ssize_t) image->columns; x++)
2422 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2423 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2424 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2425 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2426 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2427 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2428 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2429 (image->colorspace == CMYKColorspace))
2430 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2431 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2432 (image->matte == MagickTrue))
2433 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2434 q+=GetPixelChannels(image);
2436 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2438 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2443 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2444 #pragma omp critical (MagickCore_PosterizeImage)
2446 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2448 if (proceed == MagickFalse)
2452 image_view=DestroyCacheView(image_view);
2453 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2454 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2455 levels,MaxColormapSize+1);
2456 quantize_info->dither=dither;
2457 quantize_info->tree_depth=MaxTreeDepth;
2458 status=QuantizeImage(quantize_info,image,exception);
2459 quantize_info=DestroyQuantizeInfo(quantize_info);
2464 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2468 + P r u n e C h i l d %
2472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2474 % PruneChild() deletes the given node and merges its statistics into its
2477 % The format of the PruneSubtree method is:
2479 % PruneChild(const Image *image,CubeInfo *cube_info,
2480 % const NodeInfo *node_info)
2482 % A description of each parameter follows.
2484 % o image: the image.
2486 % o cube_info: A pointer to the Cube structure.
2488 % o node_info: pointer to node in color cube tree that is to be pruned.
2491 static void PruneChild(const Image *image,CubeInfo *cube_info,
2492 const NodeInfo *node_info)
2504 Traverse any children.
2506 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2507 for (i=0; i < (ssize_t) number_children; i++)
2508 if (node_info->child[i] != (NodeInfo *) NULL)
2509 PruneChild(image,cube_info,node_info->child[i]);
2511 Merge color statistics into parent.
2513 parent=node_info->parent;
2514 parent->number_unique+=node_info->number_unique;
2515 parent->total_color.red+=node_info->total_color.red;
2516 parent->total_color.green+=node_info->total_color.green;
2517 parent->total_color.blue+=node_info->total_color.blue;
2518 parent->total_color.alpha+=node_info->total_color.alpha;
2519 parent->child[node_info->id]=(NodeInfo *) NULL;
2524 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2528 + P r u n e L e v e l %
2532 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2534 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2535 % their color statistics into their parent node.
2537 % The format of the PruneLevel method is:
2539 % PruneLevel(const Image *image,CubeInfo *cube_info,
2540 % const NodeInfo *node_info)
2542 % A description of each parameter follows.
2544 % o image: the image.
2546 % o cube_info: A pointer to the Cube structure.
2548 % o node_info: pointer to node in color cube tree that is to be pruned.
2551 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2552 const NodeInfo *node_info)
2561 Traverse any children.
2563 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2564 for (i=0; i < (ssize_t) number_children; i++)
2565 if (node_info->child[i] != (NodeInfo *) NULL)
2566 PruneLevel(image,cube_info,node_info->child[i]);
2567 if (node_info->level == cube_info->depth)
2568 PruneChild(image,cube_info,node_info);
2572 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2576 + P r u n e T o C u b e D e p t h %
2580 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2582 % PruneToCubeDepth() deletes any nodes at a depth greater than
2583 % cube_info->depth while merging their color statistics into their parent
2586 % The format of the PruneToCubeDepth method is:
2588 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2589 % const NodeInfo *node_info)
2591 % A description of each parameter follows.
2593 % o cube_info: A pointer to the Cube structure.
2595 % o node_info: pointer to node in color cube tree that is to be pruned.
2598 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2599 const NodeInfo *node_info)
2608 Traverse any children.
2610 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2611 for (i=0; i < (ssize_t) number_children; i++)
2612 if (node_info->child[i] != (NodeInfo *) NULL)
2613 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2614 if (node_info->level > cube_info->depth)
2615 PruneChild(image,cube_info,node_info);
2619 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2623 % Q u a n t i z e I m a g e %
2627 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2629 % QuantizeImage() analyzes the colors within a reference image and chooses a
2630 % fixed number of colors to represent the image. The goal of the algorithm
2631 % is to minimize the color difference between the input and output image while
2632 % minimizing the processing time.
2634 % The format of the QuantizeImage method is:
2636 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2637 % Image *image,ExceptionInfo *exception)
2639 % A description of each parameter follows:
2641 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2643 % o image: the image.
2645 % o exception: return any errors or warnings in this structure.
2649 static MagickBooleanType DirectToColormapImage(Image *image,
2650 ExceptionInfo *exception)
2668 number_colors=(size_t) (image->columns*image->rows);
2669 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2670 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2672 if (image->colors != number_colors)
2673 return(MagickFalse);
2675 image_view=AcquireCacheView(image);
2676 for (y=0; y < (ssize_t) image->rows; y++)
2687 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2688 if (q == (Quantum *) NULL)
2690 for (x=0; x < (ssize_t) image->columns; x++)
2692 image->colormap[i].red=GetPixelRed(image,q);
2693 image->colormap[i].green=GetPixelGreen(image,q);
2694 image->colormap[i].blue=GetPixelBlue(image,q);
2695 image->colormap[i].alpha=GetPixelAlpha(image,q);
2696 SetPixelIndex(image,(Quantum) i,q);
2698 q+=GetPixelChannels(image);
2700 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2702 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2704 if (proceed == MagickFalse)
2707 image_view=DestroyCacheView(image_view);
2711 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2712 Image *image,ExceptionInfo *exception)
2724 assert(quantize_info != (const QuantizeInfo *) NULL);
2725 assert(quantize_info->signature == MagickSignature);
2726 assert(image != (Image *) NULL);
2727 assert(image->signature == MagickSignature);
2728 if (image->debug != MagickFalse)
2729 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2730 maximum_colors=quantize_info->number_colors;
2731 if (maximum_colors == 0)
2732 maximum_colors=MaxColormapSize;
2733 if (maximum_colors > MaxColormapSize)
2734 maximum_colors=MaxColormapSize;
2735 if ((image->columns*image->rows) <= maximum_colors)
2736 (void) DirectToColormapImage(image,exception);
2737 if ((IsImageGray(image,exception) != MagickFalse) &&
2738 (image->matte == MagickFalse))
2739 (void) SetGrayscaleImage(image,exception);
2740 if ((image->storage_class == PseudoClass) &&
2741 (image->colors <= maximum_colors))
2743 depth=quantize_info->tree_depth;
2750 Depth of color tree is: Log4(colormap size)+2.
2752 colors=maximum_colors;
2753 for (depth=1; colors != 0; depth++)
2755 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2757 if ((image->matte != MagickFalse) && (depth > 5))
2761 Initialize color cube.
2763 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2764 if (cube_info == (CubeInfo *) NULL)
2765 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2767 status=ClassifyImageColors(cube_info,image,exception);
2768 if (status != MagickFalse)
2771 Reduce the number of colors in the image.
2773 ReduceImageColors(image,cube_info);
2774 status=AssignImageColors(image,cube_info,exception);
2776 DestroyCubeInfo(cube_info);
2781 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2785 % Q u a n t i z e I m a g e s %
2789 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2791 % QuantizeImages() analyzes the colors within a set of reference images and
2792 % chooses a fixed number of colors to represent the set. The goal of the
2793 % algorithm is to minimize the color difference between the input and output
2794 % images while minimizing the processing time.
2796 % The format of the QuantizeImages method is:
2798 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2799 % Image *images,ExceptionInfo *exception)
2801 % A description of each parameter follows:
2803 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2805 % o images: Specifies a pointer to a list of Image structures.
2807 % o exception: return any errors or warnings in this structure.
2810 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2811 Image *images,ExceptionInfo *exception)
2823 MagickProgressMonitor
2834 assert(quantize_info != (const QuantizeInfo *) NULL);
2835 assert(quantize_info->signature == MagickSignature);
2836 assert(images != (Image *) NULL);
2837 assert(images->signature == MagickSignature);
2838 if (images->debug != MagickFalse)
2839 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2840 if (GetNextImageInList(images) == (Image *) NULL)
2843 Handle a single image with QuantizeImage.
2845 status=QuantizeImage(quantize_info,images,exception);
2849 maximum_colors=quantize_info->number_colors;
2850 if (maximum_colors == 0)
2851 maximum_colors=MaxColormapSize;
2852 if (maximum_colors > MaxColormapSize)
2853 maximum_colors=MaxColormapSize;
2854 depth=quantize_info->tree_depth;
2861 Depth of color tree is: Log4(colormap size)+2.
2863 colors=maximum_colors;
2864 for (depth=1; colors != 0; depth++)
2866 if (quantize_info->dither != MagickFalse)
2870 Initialize color cube.
2872 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2873 if (cube_info == (CubeInfo *) NULL)
2875 (void) ThrowMagickException(exception,GetMagickModule(),
2876 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2877 return(MagickFalse);
2879 number_images=GetImageListLength(images);
2881 for (i=0; image != (Image *) NULL; i++)
2883 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2884 image->client_data);
2885 status=ClassifyImageColors(cube_info,image,exception);
2886 if (status == MagickFalse)
2888 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2889 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2891 if (proceed == MagickFalse)
2893 image=GetNextImageInList(image);
2895 if (status != MagickFalse)
2898 Reduce the number of colors in an image sequence.
2900 ReduceImageColors(images,cube_info);
2902 for (i=0; image != (Image *) NULL; i++)
2904 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2905 NULL,image->client_data);
2906 status=AssignImageColors(image,cube_info,exception);
2907 if (status == MagickFalse)
2909 (void) SetImageProgressMonitor(image,progress_monitor,
2910 image->client_data);
2911 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2913 if (proceed == MagickFalse)
2915 image=GetNextImageInList(image);
2918 DestroyCubeInfo(cube_info);
2923 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2933 % Reduce() traverses the color cube tree and prunes any node whose
2934 % quantization error falls below a particular threshold.
2936 % The format of the Reduce method is:
2938 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2940 % A description of each parameter follows.
2942 % o image: the image.
2944 % o cube_info: A pointer to the Cube structure.
2946 % o node_info: pointer to node in color cube tree that is to be pruned.
2949 static void Reduce(const Image *image,CubeInfo *cube_info,
2950 const NodeInfo *node_info)
2959 Traverse any children.
2961 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2962 for (i=0; i < (ssize_t) number_children; i++)
2963 if (node_info->child[i] != (NodeInfo *) NULL)
2964 Reduce(image,cube_info,node_info->child[i]);
2965 if (node_info->quantize_error <= cube_info->pruning_threshold)
2966 PruneChild(image,cube_info,node_info);
2970 Find minimum pruning threshold.
2972 if (node_info->number_unique > 0)
2973 cube_info->colors++;
2974 if (node_info->quantize_error < cube_info->next_threshold)
2975 cube_info->next_threshold=node_info->quantize_error;
2980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2984 + R e d u c e I m a g e C o l o r s %
2988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2990 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2991 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2992 % in the output image. On any given iteration over the tree, it selects
2993 % those nodes whose E value is minimal for pruning and merges their
2994 % color statistics upward. It uses a pruning threshold, Ep, to govern
2995 % node selection as follows:
2998 % while number of nodes with (n2 > 0) > required maximum number of colors
2999 % prune all nodes such that E <= Ep
3000 % Set Ep to minimum E in remaining nodes
3002 % This has the effect of minimizing any quantization error when merging
3003 % two nodes together.
3005 % When a node to be pruned has offspring, the pruning procedure invokes
3006 % itself recursively in order to prune the tree from the leaves upward.
3007 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3008 % corresponding data in that node's parent. This retains the pruned
3009 % node's color characteristics for later averaging.
3011 % For each node, n2 pixels exist for which that node represents the
3012 % smallest volume in RGB space containing those pixel's colors. When n2
3013 % > 0 the node will uniquely define a color in the output image. At the
3014 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3015 % the tree which represent colors present in the input image.
3017 % The other pixel count, n1, indicates the total number of colors
3018 % within the cubic volume which the node represents. This includes n1 -
3019 % n2 pixels whose colors should be defined by nodes at a lower level in
3022 % The format of the ReduceImageColors method is:
3024 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3026 % A description of each parameter follows.
3028 % o image: the image.
3030 % o cube_info: A pointer to the Cube structure.
3033 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3035 #define ReduceImageTag "Reduce/Image"
3046 cube_info->next_threshold=0.0;
3047 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3049 cube_info->pruning_threshold=cube_info->next_threshold;
3050 cube_info->next_threshold=cube_info->root->quantize_error-1;
3051 cube_info->colors=0;
3052 Reduce(image,cube_info,cube_info->root);
3053 offset=(MagickOffsetType) span-cube_info->colors;
3054 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3055 cube_info->maximum_colors+1);
3056 if (proceed == MagickFalse)
3062 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3066 % R e m a p I m a g e %
3070 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3072 % RemapImage() replaces the colors of an image with the closest color from
3073 % a reference image.
3075 % The format of the RemapImage method is:
3077 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3078 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3080 % A description of each parameter follows:
3082 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3084 % o image: the image.
3086 % o remap_image: the reference image.
3088 % o exception: return any errors or warnings in this structure.
3091 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3092 Image *image,const Image *remap_image,ExceptionInfo *exception)
3101 Initialize color cube.
3103 assert(image != (Image *) NULL);
3104 assert(image->signature == MagickSignature);
3105 if (image->debug != MagickFalse)
3106 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3107 assert(remap_image != (Image *) NULL);
3108 assert(remap_image->signature == MagickSignature);
3109 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3110 quantize_info->number_colors);
3111 if (cube_info == (CubeInfo *) NULL)
3112 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3114 status=ClassifyImageColors(cube_info,remap_image,exception);
3115 if (status != MagickFalse)
3118 Classify image colors from the reference image.
3120 cube_info->quantize_info->number_colors=cube_info->colors;
3121 status=AssignImageColors(image,cube_info,exception);
3123 DestroyCubeInfo(cube_info);
3128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3132 % R e m a p I m a g e s %
3136 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3138 % RemapImages() replaces the colors of a sequence of images with the
3139 % closest color from a reference image.
3141 % The format of the RemapImage method is:
3143 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3144 % Image *images,Image *remap_image,ExceptionInfo *exception)
3146 % A description of each parameter follows:
3148 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3150 % o images: the image sequence.
3152 % o remap_image: the reference image.
3154 % o exception: return any errors or warnings in this structure.
3157 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3158 Image *images,const Image *remap_image,ExceptionInfo *exception)
3169 assert(images != (Image *) NULL);
3170 assert(images->signature == MagickSignature);
3171 if (images->debug != MagickFalse)
3172 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3174 if (remap_image == (Image *) NULL)
3177 Create a global colormap for an image sequence.
3179 status=QuantizeImages(quantize_info,images,exception);
3183 Classify image colors from the reference image.
3185 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3186 quantize_info->number_colors);
3187 if (cube_info == (CubeInfo *) NULL)
3188 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3190 status=ClassifyImageColors(cube_info,remap_image,exception);
3191 if (status != MagickFalse)
3194 Classify image colors from the reference image.
3196 cube_info->quantize_info->number_colors=cube_info->colors;
3198 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3200 status=AssignImageColors(image,cube_info,exception);
3201 if (status == MagickFalse)
3205 DestroyCubeInfo(cube_info);
3210 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3214 % S e t G r a y s c a l e I m a g e %
3218 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3220 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3222 % The format of the SetGrayscaleImage method is:
3224 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3226 % A description of each parameter follows:
3228 % o image: The image.
3230 % o exception: return any errors or warnings in this structure.
3234 #if defined(__cplusplus) || defined(c_plusplus)
3238 static int IntensityCompare(const void *x,const void *y)
3247 color_1=(PixelInfo *) x;
3248 color_2=(PixelInfo *) y;
3249 intensity=GetPixelInfoIntensity(color_1)-(ssize_t)
3250 GetPixelInfoIntensity(color_2);
3251 return((int) intensity);
3254 #if defined(__cplusplus) || defined(c_plusplus)
3258 static MagickBooleanType SetGrayscaleImage(Image *image,
3259 ExceptionInfo *exception)
3278 assert(image != (Image *) NULL);
3279 assert(image->signature == MagickSignature);
3280 if (image->type != GrayscaleType)
3281 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3282 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3283 sizeof(*colormap_index));
3284 if (colormap_index == (ssize_t *) NULL)
3285 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3287 if (image->storage_class != PseudoClass)
3289 for (i=0; i <= (ssize_t) MaxMap; i++)
3290 colormap_index[i]=(-1);
3291 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3292 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3296 image_view=AcquireCacheView(image);
3297 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3298 #pragma omp parallel for schedule(dynamic,4) shared(status)
3300 for (y=0; y < (ssize_t) image->rows; y++)
3308 if (status == MagickFalse)
3310 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3312 if (q == (Quantum *) NULL)
3317 for (x=0; x < (ssize_t) image->columns; x++)
3322 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3323 if (colormap_index[intensity] < 0)
3325 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3326 #pragma omp critical (MagickCore_SetGrayscaleImage)
3328 if (colormap_index[intensity] < 0)
3330 colormap_index[intensity]=(ssize_t) image->colors;
3331 image->colormap[image->colors].red=GetPixelRed(image,q);
3332 image->colormap[image->colors].green=GetPixelGreen(image,q);
3333 image->colormap[image->colors].blue=GetPixelBlue(image,q);
3337 SetPixelIndex(image,(Quantum)
3338 colormap_index[intensity],q);
3339 q+=GetPixelChannels(image);
3341 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3344 image_view=DestroyCacheView(image_view);
3346 for (i=0; i < (ssize_t) image->colors; i++)
3347 image->colormap[i].alpha=(unsigned short) i;
3348 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3350 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,
3352 if (colormap == (PixelInfo *) NULL)
3353 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3356 colormap[j]=image->colormap[0];
3357 for (i=0; i < (ssize_t) image->colors; i++)
3359 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3362 colormap[j]=image->colormap[i];
3364 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3366 image->colors=(size_t) (j+1);
3367 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3368 image->colormap=colormap;
3370 image_view=AcquireCacheView(image);
3371 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3372 #pragma omp parallel for schedule(dynamic,4) shared(status)
3374 for (y=0; y < (ssize_t) image->rows; y++)
3382 if (status == MagickFalse)
3384 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3385 if (q == (Quantum *) NULL)
3390 for (x=0; x < (ssize_t) image->columns; x++)
3392 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3393 GetPixelIndex(image,q))],q);
3394 q+=GetPixelChannels(image);
3396 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3399 image_view=DestroyCacheView(image_view);
3400 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3401 image->type=GrayscaleType;
3402 if (IsImageMonochrome(image,exception) != MagickFalse)
3403 image->type=BilevelType;