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-2011 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
28 % Unless required by applicable law or agreed to in writing, software %
29 % distributed under the License is distributed on an "AS IS" BASIS, %
30 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31 % See the License for the specific language governing permissions and %
32 % limitations under the License. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Realism in computer graphics typically requires using 24 bits/pixel to
37 % generate an image. Yet many graphic display devices do not contain the
38 % amount of memory necessary to match the spatial and color resolution of
39 % the human eye. The Quantize methods takes a 24 bit image and reduces
40 % the number of colors so it can be displayed on raster device with less
41 % bits per pixel. In most instances, the quantized image closely
42 % resembles the original reference image.
44 % A reduction of colors in an image is also desirable for image
45 % transmission and real-time animation.
47 % QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 % them down to some fixed number of colors.
50 % For purposes of color allocation, an image is a set of n pixels, where
51 % each pixel is a point in RGB space. RGB space is a 3-dimensional
52 % vector space, and each pixel, Pi, is defined by an ordered triple of
53 % red, green, and blue coordinates, (Ri, Gi, Bi).
55 % Each primary color component (red, green, or blue) represents an
56 % intensity which varies linearly from 0 to a maximum value, Cmax, which
57 % corresponds to full saturation of that color. Color allocation is
58 % defined over a domain consisting of the cube in RGB space with opposite
59 % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
62 % The algorithm maps this domain onto a tree in which each node
63 % represents a cube within that domain. In the following discussion
64 % these cubes are defined by the coordinate of two opposite vertices:
65 % The vertex nearest the origin in RGB space and the vertex farthest from
68 % The tree's root node represents the entire domain, (0,0,0) through
69 % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70 % subdividing one node's cube into eight smaller cubes of equal size.
71 % This corresponds to bisecting the parent cube with planes passing
72 % through the midpoints of each edge.
74 % The basic algorithm operates in three phases: Classification,
75 % Reduction, and Assignment. Classification builds a color description
76 % tree for the image. Reduction collapses the tree until the number it
77 % represents, at most, the number of colors desired in the output image.
78 % Assignment defines the output image's color map and sets each pixel's
79 % color by restorage_class in the reduced tree. Our goal is to minimize
80 % the numerical discrepancies between the original colors and quantized
81 % colors (quantization error).
83 % Classification begins by initializing a color description tree of
84 % sufficient depth to represent each possible input color in a leaf.
85 % However, it is impractical to generate a fully-formed color description
86 % tree in the storage_class phase for realistic values of Cmax. If
87 % colors components in the input image are quantized to k-bit precision,
88 % so that Cmax= 2k-1, the tree would need k levels below the root node to
89 % allow representing each possible input color in a leaf. This becomes
90 % prohibitive because the tree's total number of nodes is 1 +
93 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95 % Initializes data structures for nodes only as they are needed; (2)
96 % Chooses a maximum depth for the tree as a function of the desired
97 % number of colors in the output image (currently log2(colormap size)).
99 % For each pixel in the input image, storage_class scans downward from
100 % the root of the color description tree. At each level of the tree it
101 % identifies the single node which represents a cube in RGB space
102 % containing the pixel's color. It updates the following data for each
105 % n1: Number of pixels whose color is contained in the RGB cube which
106 % this node represents;
108 % n2: Number of pixels whose color is not represented in a node at
109 % lower depth in the tree; initially, n2 = 0 for all nodes except
110 % leaves of the tree.
112 % Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113 % pixels not classified at a lower depth. The combination of these sums
114 % and n2 will ultimately characterize the mean color of a set of
115 % pixels represented by this node.
117 % E: the distance squared in RGB space between each pixel contained
118 % within a node and the nodes' center. This represents the
119 % quantization error for a node.
121 % Reduction repeatedly prunes the tree until the number of nodes with n2
122 % > 0 is less than or equal to the maximum number of colors allowed in
123 % the output image. On any given iteration over the tree, it selects
124 % those nodes whose E count is minimal for pruning and merges their color
125 % statistics upward. It uses a pruning threshold, Ep, to govern node
126 % selection as follows:
129 % while number of nodes with (n2 > 0) > required maximum number of colors
130 % prune all nodes such that E <= Ep
131 % Set Ep to minimum E in remaining nodes
133 % This has the effect of minimizing any quantization error when merging
134 % two nodes together.
136 % When a node to be pruned has offspring, the pruning procedure invokes
137 % itself recursively in order to prune the tree from the leaves upward.
138 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
139 % corresponding data in that node's parent. This retains the pruned
140 % node's color characteristics for later averaging.
142 % For each node, n2 pixels exist for which that node represents the
143 % smallest volume in RGB space containing those pixel's colors. When n2
144 % > 0 the node will uniquely define a color in the output image. At the
145 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
146 % the tree which represent colors present in the input image.
148 % The other pixel count, n1, indicates the total number of colors within
149 % the cubic volume which the node represents. This includes n1 - n2
150 % pixels whose colors should be defined by nodes at a lower level in the
153 % Assignment generates the output image from the pruned tree. The output
154 % image consists of two parts: (1) A color map, which is an array of
155 % color descriptions (RGB triples) for each color present in the output
156 % image; (2) A pixel array, which represents each pixel as an index
157 % into the color map array.
159 % First, the assignment phase makes one pass over the pruned color
160 % description tree to establish the image's color map. For each node
161 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162 % color of all pixels that classify no lower than this node. Each of
163 % these colors becomes an entry in the color map.
165 % Finally, the assignment phase reclassifies each pixel in the pruned
166 % tree to identify the deepest node containing the pixel's color. The
167 % pixel's value in the pixel array becomes the index of this node's mean
168 % color in the color map.
170 % This method is based on a similar algorithm written by Paul Raveling.
175 Include declarations.
177 #include "magick/studio.h"
178 #include "magick/cache-view.h"
179 #include "magick/color.h"
180 #include "magick/color-private.h"
181 #include "magick/colormap.h"
182 #include "magick/colorspace.h"
183 #include "magick/enhance.h"
184 #include "magick/exception.h"
185 #include "magick/exception-private.h"
186 #include "magick/histogram.h"
187 #include "magick/image.h"
188 #include "magick/image-private.h"
189 #include "magick/list.h"
190 #include "magick/memory_.h"
191 #include "magick/monitor.h"
192 #include "magick/monitor-private.h"
193 #include "magick/option.h"
194 #include "magick/pixel-private.h"
195 #include "magick/quantize.h"
196 #include "magick/quantum.h"
197 #include "magick/string_.h"
198 #include "magick/thread-private.h"
203 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
208 #define ErrorQueueLength 16
209 #define MaxNodes 266817
210 #define MaxTreeDepth 8
211 #define NodesInAList 1920
216 typedef struct _RealPixelPacket
225 typedef struct _NodeInfo
246 typedef struct _Nodes
255 typedef struct _CubeInfo
293 error[ErrorQueueLength];
296 weights[ErrorQueueLength];
322 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
325 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
327 static MagickBooleanType
328 AssignImageColors(Image *,CubeInfo *),
329 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
330 DitherImage(Image *,CubeInfo *),
331 SetGrayscaleImage(Image *);
334 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
337 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
338 DestroyCubeInfo(CubeInfo *),
339 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
340 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
341 ReduceImageColors(const Image *,CubeInfo *);
344 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
348 % A c q u i r e Q u a n t i z e I n f o %
352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
354 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
356 % The format of the AcquireQuantizeInfo method is:
358 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
360 % A description of each parameter follows:
362 % o image_info: the image info.
365 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
370 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
371 if (quantize_info == (QuantizeInfo *) NULL)
372 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
373 GetQuantizeInfo(quantize_info);
374 if (image_info != (ImageInfo *) NULL)
379 quantize_info->dither=image_info->dither;
380 option=GetImageOption(image_info,"dither");
381 if (option != (const char *) NULL)
382 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
383 MagickDitherOptions,MagickFalse,option);
384 quantize_info->measure_error=image_info->verbose;
386 return(quantize_info);
390 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
394 + A s s i g n I m a g e C o l o r s %
398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
400 % AssignImageColors() generates the output image from the pruned tree. The
401 % output image consists of two parts: (1) A color map, which is an array
402 % of color descriptions (RGB triples) for each color present in the
403 % output image; (2) A pixel array, which represents each pixel as an
404 % index into the color map array.
406 % First, the assignment phase makes one pass over the pruned color
407 % description tree to establish the image's color map. For each node
408 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
409 % color of all pixels that classify no lower than this node. Each of
410 % these colors becomes an entry in the color map.
412 % Finally, the assignment phase reclassifies each pixel in the pruned
413 % tree to identify the deepest node containing the pixel's color. The
414 % pixel's value in the pixel array becomes the index of this node's mean
415 % color in the color map.
417 % The format of the AssignImageColors() method is:
419 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
421 % A description of each parameter follows.
423 % o image: the image.
425 % o cube_info: A pointer to the Cube structure.
429 static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
430 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
435 if ((cube_info->associate_alpha == MagickFalse) ||
436 (pixel->opacity == OpaqueOpacity))
438 alpha_pixel->red=(MagickRealType) pixel->red;
439 alpha_pixel->green=(MagickRealType) pixel->green;
440 alpha_pixel->blue=(MagickRealType) pixel->blue;
441 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
444 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
445 alpha_pixel->red=alpha*pixel->red;
446 alpha_pixel->green=alpha*pixel->green;
447 alpha_pixel->blue=alpha*pixel->blue;
448 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
451 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
455 if (value >= QuantumRange)
456 return((Quantum) QuantumRange);
457 return((Quantum) (value+0.5));
460 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
461 const RealPixelPacket *pixel,size_t index)
467 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
468 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
469 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
470 if (cube_info->associate_alpha != MagickFalse)
471 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
476 static inline MagickBooleanType IsSameColor(const Image *image,
477 const PixelPacket *p,const PixelPacket *q)
479 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
481 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
486 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
488 #define AssignImageTag "Assign/Image"
494 Allocate image colormap.
496 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
497 (cube_info->quantize_info->colorspace != CMYKColorspace))
498 (void) TransformImageColorspace((Image *) image,
499 cube_info->quantize_info->colorspace);
501 if ((image->colorspace != GRAYColorspace) &&
502 (image->colorspace != RGBColorspace) &&
503 (image->colorspace != CMYColorspace))
504 (void) TransformImageColorspace((Image *) image,RGBColorspace);
505 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
506 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
509 cube_info->transparent_pixels=0;
510 cube_info->transparent_index=(-1);
511 (void) DefineImageColormap(image,cube_info,cube_info->root);
513 Create a reduced color image.
515 if ((cube_info->quantize_info->dither != MagickFalse) &&
516 (cube_info->quantize_info->dither_method != NoDitherMethod))
517 (void) DitherImage(image,cube_info);
530 exception=(&image->exception);
531 image_view=AcquireCacheView(image);
532 #if defined(MAGICKCORE_OPENMP_SUPPORT)
533 #pragma omp parallel for schedule(dynamic,4) shared(status)
535 for (y=0; y < (ssize_t) image->rows; y++)
552 if (status == MagickFalse)
554 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
556 if (q == (PixelPacket *) NULL)
561 indexes=GetCacheViewAuthenticIndexQueue(image_view);
563 for (x=0; x < (ssize_t) image->columns; x+=count)
568 register const NodeInfo
579 Identify the deepest node containing the pixel's color.
581 for (count=1; (x+count) < (ssize_t) image->columns; count++)
582 if (IsSameColor(image,q,q+count) == MagickFalse)
584 AssociateAlphaPixel(&cube,q,&pixel);
586 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
588 id=ColorToNodeId(&cube,&pixel,index);
589 if (node_info->child[id] == (NodeInfo *) NULL)
591 node_info=node_info->child[id];
594 Find closest color among siblings and their children.
597 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
598 (QuantumRange+1.0)+1.0);
599 ClosestColor(image,&cube,node_info->parent);
600 index=cube.color_number;
601 for (i=0; i < (ssize_t) count; i++)
603 if (image->storage_class == PseudoClass)
604 indexes[x+i]=(IndexPacket) index;
605 if (cube.quantize_info->measure_error == MagickFalse)
607 q->red=image->colormap[index].red;
608 q->green=image->colormap[index].green;
609 q->blue=image->colormap[index].blue;
610 if (cube.associate_alpha != MagickFalse)
611 q->opacity=image->colormap[index].opacity;
616 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
618 if (image->progress_monitor != (MagickProgressMonitor) NULL)
623 #if defined(MAGICKCORE_OPENMP_SUPPORT)
624 #pragma omp critical (MagickCore_AssignImageColors)
626 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
628 if (proceed == MagickFalse)
632 image_view=DestroyCacheView(image_view);
634 if (cube_info->quantize_info->measure_error != MagickFalse)
635 (void) GetImageQuantizeError(image);
636 if ((cube_info->quantize_info->number_colors == 2) &&
637 (cube_info->quantize_info->colorspace == GRAYColorspace))
652 for (i=0; i < (ssize_t) image->colors; i++)
654 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
655 QuantumRange/2.0) ? 0 : QuantumRange);
662 (void) SyncImage(image);
663 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
664 (cube_info->quantize_info->colorspace != CMYKColorspace))
665 (void) TransformImageColorspace((Image *) image,RGBColorspace);
670 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
674 + C l a s s i f y I m a g e C o l o r s %
678 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
680 % ClassifyImageColors() begins by initializing a color description tree
681 % of sufficient depth to represent each possible input color in a leaf.
682 % However, it is impractical to generate a fully-formed color
683 % description tree in the storage_class phase for realistic values of
684 % Cmax. If colors components in the input image are quantized to k-bit
685 % precision, so that Cmax= 2k-1, the tree would need k levels below the
686 % root node to allow representing each possible input color in a leaf.
687 % This becomes prohibitive because the tree's total number of nodes is
690 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
691 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
692 % Initializes data structures for nodes only as they are needed; (2)
693 % Chooses a maximum depth for the tree as a function of the desired
694 % number of colors in the output image (currently log2(colormap size)).
696 % For each pixel in the input image, storage_class scans downward from
697 % the root of the color description tree. At each level of the tree it
698 % identifies the single node which represents a cube in RGB space
699 % containing It updates the following data for each such node:
701 % n1 : Number of pixels whose color is contained in the RGB cube
702 % which this node represents;
704 % n2 : Number of pixels whose color is not represented in a node at
705 % lower depth in the tree; initially, n2 = 0 for all nodes except
706 % leaves of the tree.
708 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
709 % all pixels not classified at a lower depth. The combination of
710 % these sums and n2 will ultimately characterize the mean color of a
711 % set of pixels represented by this node.
713 % E: the distance squared in RGB space between each pixel contained
714 % within a node and the nodes' center. This represents the quantization
717 % The format of the ClassifyImageColors() method is:
719 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
720 % const Image *image,ExceptionInfo *exception)
722 % A description of each parameter follows.
724 % o cube_info: A pointer to the Cube structure.
726 % o image: the image.
730 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
735 associate_alpha=image->matte;
736 if (cube_info->quantize_info->colorspace == TransparentColorspace)
737 associate_alpha=MagickFalse;
738 if ((cube_info->quantize_info->number_colors == 2) &&
739 (cube_info->quantize_info->colorspace == GRAYColorspace))
740 associate_alpha=MagickFalse;
741 cube_info->associate_alpha=associate_alpha;
744 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
745 const Image *image,ExceptionInfo *exception)
747 #define ClassifyImageTag "Classify/Image"
777 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
779 SetAssociatedAlpha(image,cube_info);
780 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
781 (cube_info->quantize_info->colorspace != CMYKColorspace))
782 (void) TransformImageColorspace((Image *) image,
783 cube_info->quantize_info->colorspace);
785 if ((image->colorspace != GRAYColorspace) &&
786 (image->colorspace != CMYColorspace) &&
787 (image->colorspace != RGBColorspace))
788 (void) TransformImageColorspace((Image *) image,RGBColorspace);
789 midpoint.red=(MagickRealType) QuantumRange/2.0;
790 midpoint.green=(MagickRealType) QuantumRange/2.0;
791 midpoint.blue=(MagickRealType) QuantumRange/2.0;
792 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
794 image_view=AcquireCacheView(image);
795 for (y=0; y < (ssize_t) image->rows; y++)
797 register const PixelPacket
803 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
804 if (p == (const PixelPacket *) NULL)
806 if (cube_info->nodes > MaxNodes)
809 Prune one level if the color tree is too large.
811 PruneLevel(image,cube_info,cube_info->root);
814 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
817 Start at the root and descend the color cube tree.
819 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
820 if (IsSameColor(image,p,p+count) == MagickFalse)
822 AssociateAlphaPixel(cube_info,p,&pixel);
823 index=MaxTreeDepth-1;
824 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
826 node_info=cube_info->root;
827 for (level=1; level <= MaxTreeDepth; level++)
830 id=ColorToNodeId(cube_info,&pixel,index);
831 mid.red+=(id & 1) != 0 ? bisect : -bisect;
832 mid.green+=(id & 2) != 0 ? bisect : -bisect;
833 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
834 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
835 if (node_info->child[id] == (NodeInfo *) NULL)
838 Set colors of new node to contain pixel.
840 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
841 if (node_info->child[id] == (NodeInfo *) NULL)
842 (void) ThrowMagickException(exception,GetMagickModule(),
843 ResourceLimitError,"MemoryAllocationFailed","`%s'",
845 if (level == MaxTreeDepth)
849 Approximate the quantization error represented by this node.
851 node_info=node_info->child[id];
852 error.red=QuantumScale*(pixel.red-mid.red);
853 error.green=QuantumScale*(pixel.green-mid.green);
854 error.blue=QuantumScale*(pixel.blue-mid.blue);
855 if (cube_info->associate_alpha != MagickFalse)
856 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
857 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
858 count*error.green*error.green+count*error.blue*error.blue+
859 count*error.opacity*error.opacity));
860 cube_info->root->quantize_error+=node_info->quantize_error;
864 Sum RGB for this leaf for later derivation of the mean cube color.
866 node_info->number_unique+=count;
867 node_info->total_color.red+=count*QuantumScale*pixel.red;
868 node_info->total_color.green+=count*QuantumScale*pixel.green;
869 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
870 if (cube_info->associate_alpha != MagickFalse)
871 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
874 if (cube_info->colors > cube_info->maximum_colors)
876 PruneToCubeDepth(image,cube_info,cube_info->root);
879 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
881 if (proceed == MagickFalse)
884 for (y++; y < (ssize_t) image->rows; y++)
886 register const PixelPacket
892 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
893 if (p == (const PixelPacket *) NULL)
895 if (cube_info->nodes > MaxNodes)
898 Prune one level if the color tree is too large.
900 PruneLevel(image,cube_info,cube_info->root);
903 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
906 Start at the root and descend the color cube tree.
908 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
909 if (IsSameColor(image,p,p+count) == MagickFalse)
911 AssociateAlphaPixel(cube_info,p,&pixel);
912 index=MaxTreeDepth-1;
913 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
915 node_info=cube_info->root;
916 for (level=1; level <= cube_info->depth; level++)
919 id=ColorToNodeId(cube_info,&pixel,index);
920 mid.red+=(id & 1) != 0 ? bisect : -bisect;
921 mid.green+=(id & 2) != 0 ? bisect : -bisect;
922 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
923 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
924 if (node_info->child[id] == (NodeInfo *) NULL)
927 Set colors of new node to contain pixel.
929 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
930 if (node_info->child[id] == (NodeInfo *) NULL)
931 (void) ThrowMagickException(exception,GetMagickModule(),
932 ResourceLimitError,"MemoryAllocationFailed","%s",
934 if (level == cube_info->depth)
938 Approximate the quantization error represented by this node.
940 node_info=node_info->child[id];
941 error.red=QuantumScale*(pixel.red-mid.red);
942 error.green=QuantumScale*(pixel.green-mid.green);
943 error.blue=QuantumScale*(pixel.blue-mid.blue);
944 if (cube_info->associate_alpha != MagickFalse)
945 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
946 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
947 count*error.green*error.green+count*error.blue*error.blue+
948 count*error.opacity*error.opacity));
949 cube_info->root->quantize_error+=node_info->quantize_error;
953 Sum RGB for this leaf for later derivation of the mean cube color.
955 node_info->number_unique+=count;
956 node_info->total_color.red+=count*QuantumScale*pixel.red;
957 node_info->total_color.green+=count*QuantumScale*pixel.green;
958 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
959 if (cube_info->associate_alpha != MagickFalse)
960 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
963 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
965 if (proceed == MagickFalse)
968 image_view=DestroyCacheView(image_view);
969 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
970 (cube_info->quantize_info->colorspace != CMYKColorspace))
971 (void) TransformImageColorspace((Image *) image,RGBColorspace);
976 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
980 % C l o n e Q u a n t i z e I n f o %
984 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
986 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
987 % or if quantize info is NULL, a new one.
989 % The format of the CloneQuantizeInfo method is:
991 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
993 % A description of each parameter follows:
995 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
996 % quantize info, or if image info is NULL a new one.
998 % o quantize_info: a structure of type info.
1001 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1006 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1007 if (clone_info == (QuantizeInfo *) NULL)
1008 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1009 GetQuantizeInfo(clone_info);
1010 if (quantize_info == (QuantizeInfo *) NULL)
1012 clone_info->number_colors=quantize_info->number_colors;
1013 clone_info->tree_depth=quantize_info->tree_depth;
1014 clone_info->dither=quantize_info->dither;
1015 clone_info->dither_method=quantize_info->dither_method;
1016 clone_info->colorspace=quantize_info->colorspace;
1017 clone_info->measure_error=quantize_info->measure_error;
1022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1026 + C l o s e s t C o l o r %
1030 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032 % ClosestColor() traverses the color cube tree at a particular node and
1033 % determines which colormap entry best represents the input color.
1035 % The format of the ClosestColor method is:
1037 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1038 % const NodeInfo *node_info)
1040 % A description of each parameter follows.
1042 % o image: the image.
1044 % o cube_info: A pointer to the Cube structure.
1046 % o node_info: the address of a structure of type NodeInfo which points to a
1047 % node in the color cube tree that is to be pruned.
1050 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1051 const NodeInfo *node_info)
1060 Traverse any children.
1062 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1063 for (i=0; i < (ssize_t) number_children; i++)
1064 if (node_info->child[i] != (NodeInfo *) NULL)
1065 ClosestColor(image,cube_info,node_info->child[i]);
1066 if (node_info->number_unique != 0)
1071 register MagickRealType
1076 register PixelPacket
1079 register RealPixelPacket
1083 Determine if this color is "closest".
1085 p=image->colormap+node_info->color_number;
1086 q=(&cube_info->target);
1089 if (cube_info->associate_alpha != MagickFalse)
1091 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1092 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1094 pixel=alpha*p->red-beta*q->red;
1095 distance=pixel*pixel;
1096 if (distance <= cube_info->distance)
1098 pixel=alpha*p->green-beta*q->green;
1099 distance+=pixel*pixel;
1100 if (distance <= cube_info->distance)
1102 pixel=alpha*p->blue-beta*q->blue;
1103 distance+=pixel*pixel;
1104 if (distance <= cube_info->distance)
1107 distance+=pixel*pixel;
1108 if (distance <= cube_info->distance)
1110 cube_info->distance=distance;
1111 cube_info->color_number=node_info->color_number;
1120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1124 % C o m p r e s s I m a g e C o l o r m a p %
1128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1130 % CompressImageColormap() compresses an image colormap by removing any
1131 % duplicate or unused color entries.
1133 % The format of the CompressImageColormap method is:
1135 % MagickBooleanType CompressImageColormap(Image *image)
1137 % A description of each parameter follows:
1139 % o image: the image.
1142 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1147 assert(image != (Image *) NULL);
1148 assert(image->signature == MagickSignature);
1149 if (image->debug != MagickFalse)
1150 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1151 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1152 return(MagickFalse);
1153 GetQuantizeInfo(&quantize_info);
1154 quantize_info.number_colors=image->colors;
1155 quantize_info.tree_depth=MaxTreeDepth;
1156 return(QuantizeImage(&quantize_info,image));
1160 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1164 + D e f i n e I m a g e C o l o r m a p %
1168 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1170 % DefineImageColormap() traverses the color cube tree and notes each colormap
1171 % entry. A colormap entry is any node in the color cube tree where the
1172 % of unique colors is not zero. DefineImageColormap() returns the number of
1173 % colors in the image colormap.
1175 % The format of the DefineImageColormap method is:
1177 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1178 % NodeInfo *node_info)
1180 % A description of each parameter follows.
1182 % o image: the image.
1184 % o cube_info: A pointer to the Cube structure.
1186 % o node_info: the address of a structure of type NodeInfo which points to a
1187 % node in the color cube tree that is to be pruned.
1190 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1191 NodeInfo *node_info)
1200 Traverse any children.
1202 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1203 for (i=0; i < (ssize_t) number_children; i++)
1204 if (node_info->child[i] != (NodeInfo *) NULL)
1205 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1206 if (node_info->number_unique != 0)
1208 register MagickRealType
1211 register PixelPacket
1215 Colormap entry is defined by the mean color in this cube.
1217 q=image->colormap+image->colors;
1218 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1219 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1220 if (cube_info->associate_alpha == MagickFalse)
1222 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1223 node_info->total_color.red));
1224 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1225 node_info->total_color.green));
1226 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1227 node_info->total_color.blue));
1228 SetOpacityPixelComponent(q,OpaqueOpacity);
1235 opacity=(MagickRealType) (alpha*QuantumRange*
1236 node_info->total_color.opacity);
1237 q->opacity=ClampToQuantum(opacity);
1238 if (q->opacity == OpaqueOpacity)
1240 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1241 node_info->total_color.red));
1242 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1243 node_info->total_color.green));
1244 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1245 node_info->total_color.blue));
1252 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1253 (MagickRealType) q->opacity));
1254 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1255 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1256 node_info->total_color.red));
1257 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1258 QuantumRange*node_info->total_color.green));
1259 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1260 node_info->total_color.blue));
1261 if (node_info->number_unique > cube_info->transparent_pixels)
1263 cube_info->transparent_pixels=node_info->number_unique;
1264 cube_info->transparent_index=(ssize_t) image->colors;
1268 node_info->color_number=image->colors++;
1270 return(image->colors);
1274 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1278 + D e s t r o y C u b e I n f o %
1282 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1284 % DestroyCubeInfo() deallocates memory associated with an image.
1286 % The format of the DestroyCubeInfo method is:
1288 % DestroyCubeInfo(CubeInfo *cube_info)
1290 % A description of each parameter follows:
1292 % o cube_info: the address of a structure of type CubeInfo.
1295 static void DestroyCubeInfo(CubeInfo *cube_info)
1301 Release color cube tree storage.
1305 nodes=cube_info->node_queue->next;
1306 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1307 cube_info->node_queue->nodes);
1308 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1309 cube_info->node_queue);
1310 cube_info->node_queue=nodes;
1311 } while (cube_info->node_queue != (Nodes *) NULL);
1312 if (cube_info->cache != (ssize_t *) NULL)
1313 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1314 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1315 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1319 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1323 % D e s t r o y Q u a n t i z e I n f o %
1327 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1329 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1332 % The format of the DestroyQuantizeInfo method is:
1334 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1336 % A description of each parameter follows:
1338 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1341 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1343 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1344 assert(quantize_info != (QuantizeInfo *) NULL);
1345 assert(quantize_info->signature == MagickSignature);
1346 quantize_info->signature=(~MagickSignature);
1347 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1348 return(quantize_info);
1352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1356 + D i t h e r I m a g e %
1360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1362 % DitherImage() distributes the difference between an original image and
1363 % the corresponding color reduced algorithm to neighboring pixels using
1364 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1365 % MagickTrue if the image is dithered otherwise MagickFalse.
1367 % The format of the DitherImage method is:
1369 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1371 % A description of each parameter follows.
1373 % o image: the image.
1375 % o cube_info: A pointer to the Cube structure.
1379 static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1384 assert(pixels != (RealPixelPacket **) NULL);
1385 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1386 if (pixels[i] != (RealPixelPacket *) NULL)
1387 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1388 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1392 static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1403 number_threads=GetOpenMPMaximumThreads();
1404 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1406 if (pixels == (RealPixelPacket **) NULL)
1407 return((RealPixelPacket **) NULL);
1408 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1409 for (i=0; i < (ssize_t) number_threads; i++)
1411 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1412 2*sizeof(**pixels));
1413 if (pixels[i] == (RealPixelPacket *) NULL)
1414 return(DestroyPixelThreadSet(pixels));
1419 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1420 const RealPixelPacket *pixel)
1422 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1423 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1424 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1425 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1431 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1432 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1433 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1434 if (cube_info->associate_alpha != MagickFalse)
1435 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1440 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1442 #define DitherImageTag "Dither/Image"
1460 Distribute quantization error using Floyd-Steinberg.
1462 pixels=AcquirePixelThreadSet(image->columns);
1463 if (pixels == (RealPixelPacket **) NULL)
1464 return(MagickFalse);
1465 exception=(&image->exception);
1467 image_view=AcquireCacheView(image);
1468 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1469 #pragma omp parallel for schedule(dynamic,4) shared(status)
1471 for (y=0; y < (ssize_t) image->rows; y++)
1474 id = GetOpenMPThreadId();
1483 register IndexPacket
1486 register PixelPacket
1498 if (status == MagickFalse)
1500 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1501 if (q == (PixelPacket *) NULL)
1506 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1508 current=pixels[id]+(y & 0x01)*image->columns;
1509 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1510 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1511 for (x=0; x < (ssize_t) image->columns; x++)
1523 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1524 AssociateAlphaPixel(&cube,q+u,&pixel);
1527 pixel.red+=7*current[u-v].red/16;
1528 pixel.green+=7*current[u-v].green/16;
1529 pixel.blue+=7*current[u-v].blue/16;
1530 if (cube.associate_alpha != MagickFalse)
1531 pixel.opacity+=7*current[u-v].opacity/16;
1535 if (x < (ssize_t) (image->columns-1))
1537 pixel.red+=previous[u+v].red/16;
1538 pixel.green+=previous[u+v].green/16;
1539 pixel.blue+=previous[u+v].blue/16;
1540 if (cube.associate_alpha != MagickFalse)
1541 pixel.opacity+=previous[u+v].opacity/16;
1543 pixel.red+=5*previous[u].red/16;
1544 pixel.green+=5*previous[u].green/16;
1545 pixel.blue+=5*previous[u].blue/16;
1546 if (cube.associate_alpha != MagickFalse)
1547 pixel.opacity+=5*previous[u].opacity/16;
1550 pixel.red+=3*previous[u-v].red/16;
1551 pixel.green+=3*previous[u-v].green/16;
1552 pixel.blue+=3*previous[u-v].blue/16;
1553 if (cube.associate_alpha != MagickFalse)
1554 pixel.opacity+=3*previous[u-v].opacity/16;
1557 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1558 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1559 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1560 if (cube.associate_alpha != MagickFalse)
1561 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1562 i=CacheOffset(&cube,&pixel);
1563 if (cube.cache[i] < 0)
1572 Identify the deepest node containing the pixel's color.
1574 node_info=cube.root;
1575 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1577 id=ColorToNodeId(&cube,&pixel,index);
1578 if (node_info->child[id] == (NodeInfo *) NULL)
1580 node_info=node_info->child[id];
1583 Find closest color among siblings and their children.
1586 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1588 ClosestColor(image,&cube,node_info->parent);
1589 cube.cache[i]=(ssize_t) cube.color_number;
1592 Assign pixel to closest colormap entry.
1594 index=(size_t) cube.cache[i];
1595 if (image->storage_class == PseudoClass)
1596 indexes[u]=(IndexPacket) index;
1597 if (cube.quantize_info->measure_error == MagickFalse)
1599 (q+u)->red=image->colormap[index].red;
1600 (q+u)->green=image->colormap[index].green;
1601 (q+u)->blue=image->colormap[index].blue;
1602 if (cube.associate_alpha != MagickFalse)
1603 (q+u)->opacity=image->colormap[index].opacity;
1605 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1610 AssociateAlphaPixel(&cube,image->colormap+index,&color);
1611 current[u].red=pixel.red-color.red;
1612 current[u].green=pixel.green-color.green;
1613 current[u].blue=pixel.blue-color.blue;
1614 if (cube.associate_alpha != MagickFalse)
1615 current[u].opacity=pixel.opacity-color.opacity;
1616 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1621 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1622 #pragma omp critical (MagickCore_FloydSteinbergDither)
1624 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1626 if (proceed == MagickFalse)
1631 image_view=DestroyCacheView(image_view);
1632 pixels=DestroyPixelThreadSet(pixels);
1636 static MagickBooleanType
1637 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1639 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1640 const size_t level,const unsigned int direction)
1647 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1648 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1649 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1654 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1655 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1656 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1661 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1662 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1663 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1668 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1669 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1670 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1681 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1682 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1683 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1684 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1685 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1686 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1687 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1692 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1693 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1694 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1695 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1696 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1697 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1698 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1703 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1704 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1705 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1707 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1709 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1714 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1715 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1716 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1717 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1718 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1719 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1720 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1728 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1729 CubeInfo *cube_info,const unsigned int direction)
1731 #define DitherImageTag "Dither/Image"
1747 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1748 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1753 register IndexPacket
1756 register PixelPacket
1765 exception=(&image->exception);
1766 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1767 if (q == (PixelPacket *) NULL)
1768 return(MagickFalse);
1769 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1770 AssociateAlphaPixel(cube_info,q,&pixel);
1771 for (i=0; i < ErrorQueueLength; i++)
1773 pixel.red+=p->weights[i]*p->error[i].red;
1774 pixel.green+=p->weights[i]*p->error[i].green;
1775 pixel.blue+=p->weights[i]*p->error[i].blue;
1776 if (cube_info->associate_alpha != MagickFalse)
1777 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1779 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1780 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1781 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1782 if (cube_info->associate_alpha != MagickFalse)
1783 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1784 i=CacheOffset(cube_info,&pixel);
1785 if (p->cache[i] < 0)
1794 Identify the deepest node containing the pixel's color.
1797 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1799 id=ColorToNodeId(cube_info,&pixel,index);
1800 if (node_info->child[id] == (NodeInfo *) NULL)
1802 node_info=node_info->child[id];
1804 node_info=node_info->parent;
1806 Find closest color among siblings and their children.
1809 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1810 QuantumRange+1.0)+1.0);
1811 ClosestColor(image,p,node_info->parent);
1812 p->cache[i]=(ssize_t) p->color_number;
1815 Assign pixel to closest colormap entry.
1817 index=(size_t) (1*p->cache[i]);
1818 if (image->storage_class == PseudoClass)
1819 *indexes=(IndexPacket) index;
1820 if (cube_info->quantize_info->measure_error == MagickFalse)
1822 q->red=image->colormap[index].red;
1823 q->green=image->colormap[index].green;
1824 q->blue=image->colormap[index].blue;
1825 if (cube_info->associate_alpha != MagickFalse)
1826 q->opacity=image->colormap[index].opacity;
1828 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1829 return(MagickFalse);
1831 Propagate the error as the last entry of the error queue.
1833 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1834 sizeof(p->error[0]));
1835 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1836 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1837 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1838 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1839 if (cube_info->associate_alpha != MagickFalse)
1840 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1841 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1842 if (proceed == MagickFalse)
1843 return(MagickFalse);
1848 case WestGravity: p->x--; break;
1849 case EastGravity: p->x++; break;
1850 case NorthGravity: p->y--; break;
1851 case SouthGravity: p->y++; break;
1856 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1863 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1870 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1884 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1885 return(FloydSteinbergDither(image,cube_info));
1887 Distribute quantization error along a Hilbert curve.
1889 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1890 sizeof(*cube_info->error));
1893 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1894 for (depth=1; i != 0; depth++)
1896 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1898 cube_info->offset=0;
1899 cube_info->span=(MagickSizeType) image->columns*image->rows;
1900 image_view=AcquireCacheView(image);
1902 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1903 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1904 image_view=DestroyCacheView(image_view);
1909 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1913 + G e t C u b e I n f o %
1917 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1919 % GetCubeInfo() initialize the Cube data structure.
1921 % The format of the GetCubeInfo method is:
1923 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1924 % const size_t depth,const size_t maximum_colors)
1926 % A description of each parameter follows.
1928 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1930 % o depth: Normally, this integer value is zero or one. A zero or
1931 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1932 % A tree of this depth generally allows the best representation of the
1933 % reference image with the least amount of memory and the fastest
1934 % computational speed. In some cases, such as an image with low color
1935 % dispersion (a few number of colors), a value other than
1936 % Log4(number_colors) is required. To expand the color tree completely,
1939 % o maximum_colors: maximum colors.
1942 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1943 const size_t depth,const size_t maximum_colors)
1959 Initialize tree to describe color cube_info.
1961 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1962 if (cube_info == (CubeInfo *) NULL)
1963 return((CubeInfo *) NULL);
1964 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1965 cube_info->depth=depth;
1966 if (cube_info->depth > MaxTreeDepth)
1967 cube_info->depth=MaxTreeDepth;
1968 if (cube_info->depth < 2)
1970 cube_info->maximum_colors=maximum_colors;
1972 Initialize root node.
1974 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1975 if (cube_info->root == (NodeInfo *) NULL)
1976 return((CubeInfo *) NULL);
1977 cube_info->root->parent=cube_info->root;
1978 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1979 if (cube_info->quantize_info->dither == MagickFalse)
1982 Initialize dither resources.
1984 length=(size_t) (1UL << (4*(8-CacheShift)));
1985 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1986 sizeof(*cube_info->cache));
1987 if (cube_info->cache == (ssize_t *) NULL)
1988 return((CubeInfo *) NULL);
1990 Initialize color cache.
1992 for (i=0; i < (ssize_t) length; i++)
1993 cube_info->cache[i]=(-1);
1995 Distribute weights along a curve of exponential decay.
1998 for (i=0; i < ErrorQueueLength; i++)
2000 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2001 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2004 Normalize the weighting factors.
2007 for (i=0; i < ErrorQueueLength; i++)
2008 weight+=cube_info->weights[i];
2010 for (i=0; i < ErrorQueueLength; i++)
2012 cube_info->weights[i]/=weight;
2013 sum+=cube_info->weights[i];
2015 cube_info->weights[0]+=1.0-sum;
2020 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2024 + G e t N o d e I n f o %
2028 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2030 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2031 % presets all fields to zero.
2033 % The format of the GetNodeInfo method is:
2035 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2036 % const size_t level,NodeInfo *parent)
2038 % A description of each parameter follows.
2040 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2042 % o id: Specifies the child number of the node.
2044 % o level: Specifies the level in the storage_class the node resides.
2047 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2048 const size_t level,NodeInfo *parent)
2053 if (cube_info->free_nodes == 0)
2059 Allocate a new queue of nodes.
2061 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2062 if (nodes == (Nodes *) NULL)
2063 return((NodeInfo *) NULL);
2064 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2065 sizeof(*nodes->nodes));
2066 if (nodes->nodes == (NodeInfo *) NULL)
2067 return((NodeInfo *) NULL);
2068 nodes->next=cube_info->node_queue;
2069 cube_info->node_queue=nodes;
2070 cube_info->next_node=nodes->nodes;
2071 cube_info->free_nodes=NodesInAList;
2074 cube_info->free_nodes--;
2075 node_info=cube_info->next_node++;
2076 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2077 node_info->parent=parent;
2079 node_info->level=level;
2084 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2088 % G e t I m a g e Q u a n t i z e E r r o r %
2092 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2094 % GetImageQuantizeError() measures the difference between the original
2095 % and quantized images. This difference is the total quantization error.
2096 % The error is computed by summing over all pixels in an image the distance
2097 % squared in RGB space between each reference pixel value and its quantized
2098 % value. These values are computed:
2100 % o mean_error_per_pixel: This value is the mean error for any single
2101 % pixel in the image.
2103 % o normalized_mean_square_error: This value is the normalized mean
2104 % quantization error for any single pixel in the image. This distance
2105 % measure is normalized to a range between 0 and 1. It is independent
2106 % of the range of red, green, and blue values in the image.
2108 % o normalized_maximum_square_error: Thsi value is the normalized
2109 % maximum quantization error for any single pixel in the image. This
2110 % distance measure is normalized to a range between 0 and 1. It is
2111 % independent of the range of red, green, and blue values in your image.
2113 % The format of the GetImageQuantizeError method is:
2115 % MagickBooleanType GetImageQuantizeError(Image *image)
2117 % A description of each parameter follows.
2119 % o image: the image.
2122 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2140 mean_error_per_pixel;
2148 assert(image != (Image *) NULL);
2149 assert(image->signature == MagickSignature);
2150 if (image->debug != MagickFalse)
2151 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2152 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2153 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2154 if (image->storage_class == DirectClass)
2158 area=3.0*image->columns*image->rows;
2160 mean_error_per_pixel=0.0;
2162 exception=(&image->exception);
2163 image_view=AcquireCacheView(image);
2164 for (y=0; y < (ssize_t) image->rows; y++)
2166 register const PixelPacket
2172 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2173 if (p == (const PixelPacket *) NULL)
2175 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2176 for (x=0; x < (ssize_t) image->columns; x++)
2178 index=1UL*indexes[x];
2179 if (image->matte != MagickFalse)
2181 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2182 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2183 image->colormap[index].opacity));
2185 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2186 mean_error_per_pixel+=distance;
2187 mean_error+=distance*distance;
2188 if (distance > maximum_error)
2189 maximum_error=distance;
2190 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2191 mean_error_per_pixel+=distance;
2192 mean_error+=distance*distance;
2193 if (distance > maximum_error)
2194 maximum_error=distance;
2195 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2196 mean_error_per_pixel+=distance;
2197 mean_error+=distance*distance;
2198 if (distance > maximum_error)
2199 maximum_error=distance;
2203 image_view=DestroyCacheView(image_view);
2204 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2205 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2207 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2212 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2216 % G e t Q u a n t i z e I n f o %
2220 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2222 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2224 % The format of the GetQuantizeInfo method is:
2226 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2228 % A description of each parameter follows:
2230 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2233 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2235 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2236 assert(quantize_info != (QuantizeInfo *) NULL);
2237 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2238 quantize_info->number_colors=256;
2239 quantize_info->dither=MagickTrue;
2240 quantize_info->dither_method=RiemersmaDitherMethod;
2241 quantize_info->colorspace=UndefinedColorspace;
2242 quantize_info->measure_error=MagickFalse;
2243 quantize_info->signature=MagickSignature;
2247 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2251 % P o s t e r i z e I m a g e C h a n n e l %
2255 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2257 % PosterizeImage() reduces the image to a limited number of colors for a
2260 % The format of the PosterizeImage method is:
2262 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2263 % const MagickBooleanType dither)
2264 % MagickBooleanType PosterizeImageChannel(Image *image,
2265 % const ChannelType channel,const size_t levels,
2266 % const MagickBooleanType dither)
2268 % A description of each parameter follows:
2270 % o image: Specifies a pointer to an Image structure.
2272 % o levels: Number of color levels allowed in each channel. Very low values
2273 % (2, 3, or 4) have the most visible effect.
2275 % o dither: Set this integer value to something other than zero to dither
2280 static inline ssize_t MagickRound(MagickRealType x)
2283 Round the fraction to nearest integer.
2286 return((ssize_t) (x+0.5));
2287 return((ssize_t) (x-0.5));
2290 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2291 const MagickBooleanType dither)
2296 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2300 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2301 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2303 #define PosterizeImageTag "Posterize/Image"
2304 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2305 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2328 assert(image != (Image *) NULL);
2329 assert(image->signature == MagickSignature);
2330 if (image->debug != MagickFalse)
2331 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2332 if (image->storage_class == PseudoClass)
2333 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2334 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2336 for (i=0; i < (ssize_t) image->colors; i++)
2341 if ((channel & RedChannel) != 0)
2342 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2343 if ((channel & GreenChannel) != 0)
2344 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2345 if ((channel & BlueChannel) != 0)
2346 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2347 if ((channel & OpacityChannel) != 0)
2348 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2355 exception=(&image->exception);
2356 image_view=AcquireCacheView(image);
2357 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2358 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2360 for (y=0; y < (ssize_t) image->rows; y++)
2362 register IndexPacket
2365 register PixelPacket
2371 if (status == MagickFalse)
2373 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2374 if (q == (PixelPacket *) NULL)
2379 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2380 for (x=0; x < (ssize_t) image->columns; x++)
2382 if ((channel & RedChannel) != 0)
2383 q->red=PosterizePixel(q->red);
2384 if ((channel & GreenChannel) != 0)
2385 q->green=PosterizePixel(q->green);
2386 if ((channel & BlueChannel) != 0)
2387 q->blue=PosterizePixel(q->blue);
2388 if (((channel & OpacityChannel) != 0) &&
2389 (image->matte == MagickTrue))
2390 q->opacity=PosterizePixel(q->opacity);
2391 if (((channel & IndexChannel) != 0) &&
2392 (image->colorspace == CMYKColorspace))
2393 indexes[x]=PosterizePixel(indexes[x]);
2396 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2398 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2403 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2404 #pragma omp critical (MagickCore_PosterizeImageChannel)
2406 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2408 if (proceed == MagickFalse)
2412 image_view=DestroyCacheView(image_view);
2413 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2414 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2415 levels,MaxColormapSize+1);
2416 quantize_info->dither=dither;
2417 quantize_info->tree_depth=MaxTreeDepth;
2418 status=QuantizeImage(quantize_info,image);
2419 quantize_info=DestroyQuantizeInfo(quantize_info);
2424 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2428 + P r u n e C h i l d %
2432 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2434 % PruneChild() deletes the given node and merges its statistics into its
2437 % The format of the PruneSubtree method is:
2439 % PruneChild(const Image *image,CubeInfo *cube_info,
2440 % const NodeInfo *node_info)
2442 % A description of each parameter follows.
2444 % o image: the image.
2446 % o cube_info: A pointer to the Cube structure.
2448 % o node_info: pointer to node in color cube tree that is to be pruned.
2451 static void PruneChild(const Image *image,CubeInfo *cube_info,
2452 const NodeInfo *node_info)
2464 Traverse any children.
2466 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2467 for (i=0; i < (ssize_t) number_children; i++)
2468 if (node_info->child[i] != (NodeInfo *) NULL)
2469 PruneChild(image,cube_info,node_info->child[i]);
2471 Merge color statistics into parent.
2473 parent=node_info->parent;
2474 parent->number_unique+=node_info->number_unique;
2475 parent->total_color.red+=node_info->total_color.red;
2476 parent->total_color.green+=node_info->total_color.green;
2477 parent->total_color.blue+=node_info->total_color.blue;
2478 parent->total_color.opacity+=node_info->total_color.opacity;
2479 parent->child[node_info->id]=(NodeInfo *) NULL;
2484 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2488 + P r u n e L e v e l %
2492 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2494 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2495 % their color statistics into their parent node.
2497 % The format of the PruneLevel method is:
2499 % PruneLevel(const Image *image,CubeInfo *cube_info,
2500 % const NodeInfo *node_info)
2502 % A description of each parameter follows.
2504 % o image: the image.
2506 % o cube_info: A pointer to the Cube structure.
2508 % o node_info: pointer to node in color cube tree that is to be pruned.
2511 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2512 const NodeInfo *node_info)
2521 Traverse any children.
2523 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2524 for (i=0; i < (ssize_t) number_children; i++)
2525 if (node_info->child[i] != (NodeInfo *) NULL)
2526 PruneLevel(image,cube_info,node_info->child[i]);
2527 if (node_info->level == cube_info->depth)
2528 PruneChild(image,cube_info,node_info);
2532 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2536 + P r u n e T o C u b e D e p t h %
2540 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2542 % PruneToCubeDepth() deletes any nodes at a depth greater than
2543 % cube_info->depth while merging their color statistics into their parent
2546 % The format of the PruneToCubeDepth method is:
2548 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2549 % const NodeInfo *node_info)
2551 % A description of each parameter follows.
2553 % o cube_info: A pointer to the Cube structure.
2555 % o node_info: pointer to node in color cube tree that is to be pruned.
2558 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2559 const NodeInfo *node_info)
2568 Traverse any children.
2570 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2571 for (i=0; i < (ssize_t) number_children; i++)
2572 if (node_info->child[i] != (NodeInfo *) NULL)
2573 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2574 if (node_info->level > cube_info->depth)
2575 PruneChild(image,cube_info,node_info);
2579 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2583 % Q u a n t i z e I m a g e %
2587 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2589 % QuantizeImage() analyzes the colors within a reference image and chooses a
2590 % fixed number of colors to represent the image. The goal of the algorithm
2591 % is to minimize the color difference between the input and output image while
2592 % minimizing the processing time.
2594 % The format of the QuantizeImage method is:
2596 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2599 % A description of each parameter follows:
2601 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2603 % o image: the image.
2606 static MagickBooleanType DirectToColormapImage(Image *image,
2607 ExceptionInfo *exception)
2625 number_colors=(size_t) (image->columns*image->rows);
2626 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2627 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2630 image_view=AcquireCacheView(image);
2631 for (y=0; y < (ssize_t) image->rows; y++)
2636 register IndexPacket
2639 register PixelPacket
2645 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2646 if (q == (const PixelPacket *) NULL)
2648 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2649 for (x=0; x < (ssize_t) image->columns; x++)
2651 indexes[x]=(IndexPacket) i;
2652 image->colormap[i++]=(*q++);
2654 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2656 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2658 if (proceed == MagickFalse)
2661 image_view=DestroyCacheView(image_view);
2665 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2678 assert(quantize_info != (const QuantizeInfo *) NULL);
2679 assert(quantize_info->signature == MagickSignature);
2680 assert(image != (Image *) NULL);
2681 assert(image->signature == MagickSignature);
2682 if (image->debug != MagickFalse)
2683 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2684 maximum_colors=quantize_info->number_colors;
2685 if (maximum_colors == 0)
2686 maximum_colors=MaxColormapSize;
2687 if (maximum_colors > MaxColormapSize)
2688 maximum_colors=MaxColormapSize;
2689 if ((image->columns*image->rows) <= maximum_colors)
2690 return(DirectToColormapImage(image,&image->exception));
2691 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2692 (image->matte == MagickFalse))
2693 (void) SetGrayscaleImage(image);
2694 if ((image->storage_class == PseudoClass) &&
2695 (image->colors <= maximum_colors))
2697 depth=quantize_info->tree_depth;
2704 Depth of color tree is: Log4(colormap size)+2.
2706 colors=maximum_colors;
2707 for (depth=1; colors != 0; depth++)
2709 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2711 if ((image->matte != MagickFalse) && (depth > 5))
2715 Initialize color cube.
2717 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2718 if (cube_info == (CubeInfo *) NULL)
2719 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2721 status=ClassifyImageColors(cube_info,image,&image->exception);
2722 if (status != MagickFalse)
2725 Reduce the number of colors in the image.
2727 ReduceImageColors(image,cube_info);
2728 status=AssignImageColors(image,cube_info);
2730 DestroyCubeInfo(cube_info);
2735 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2739 % Q u a n t i z e I m a g e s %
2743 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2745 % QuantizeImages() analyzes the colors within a set of reference images and
2746 % chooses a fixed number of colors to represent the set. The goal of the
2747 % algorithm is to minimize the color difference between the input and output
2748 % images while minimizing the processing time.
2750 % The format of the QuantizeImages method is:
2752 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2755 % A description of each parameter follows:
2757 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2759 % o images: Specifies a pointer to a list of Image structures.
2762 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2775 MagickProgressMonitor
2786 assert(quantize_info != (const QuantizeInfo *) NULL);
2787 assert(quantize_info->signature == MagickSignature);
2788 assert(images != (Image *) NULL);
2789 assert(images->signature == MagickSignature);
2790 if (images->debug != MagickFalse)
2791 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2792 if (GetNextImageInList(images) == (Image *) NULL)
2795 Handle a single image with QuantizeImage.
2797 status=QuantizeImage(quantize_info,images);
2801 maximum_colors=quantize_info->number_colors;
2802 if (maximum_colors == 0)
2803 maximum_colors=MaxColormapSize;
2804 if (maximum_colors > MaxColormapSize)
2805 maximum_colors=MaxColormapSize;
2806 depth=quantize_info->tree_depth;
2813 Depth of color tree is: Log4(colormap size)+2.
2815 colors=maximum_colors;
2816 for (depth=1; colors != 0; depth++)
2818 if (quantize_info->dither != MagickFalse)
2822 Initialize color cube.
2824 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2825 if (cube_info == (CubeInfo *) NULL)
2827 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2828 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2829 return(MagickFalse);
2831 number_images=GetImageListLength(images);
2833 for (i=0; image != (Image *) NULL; i++)
2835 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2836 image->client_data);
2837 status=ClassifyImageColors(cube_info,image,&image->exception);
2838 if (status == MagickFalse)
2840 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2841 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2843 if (proceed == MagickFalse)
2845 image=GetNextImageInList(image);
2847 if (status != MagickFalse)
2850 Reduce the number of colors in an image sequence.
2852 ReduceImageColors(images,cube_info);
2854 for (i=0; image != (Image *) NULL; i++)
2856 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2857 NULL,image->client_data);
2858 status=AssignImageColors(image,cube_info);
2859 if (status == MagickFalse)
2861 (void) SetImageProgressMonitor(image,progress_monitor,
2862 image->client_data);
2863 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2865 if (proceed == MagickFalse)
2867 image=GetNextImageInList(image);
2870 DestroyCubeInfo(cube_info);
2875 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2883 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2885 % Reduce() traverses the color cube tree and prunes any node whose
2886 % quantization error falls below a particular threshold.
2888 % The format of the Reduce method is:
2890 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2892 % A description of each parameter follows.
2894 % o image: the image.
2896 % o cube_info: A pointer to the Cube structure.
2898 % o node_info: pointer to node in color cube tree that is to be pruned.
2901 static void Reduce(const Image *image,CubeInfo *cube_info,
2902 const NodeInfo *node_info)
2911 Traverse any children.
2913 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2914 for (i=0; i < (ssize_t) number_children; i++)
2915 if (node_info->child[i] != (NodeInfo *) NULL)
2916 Reduce(image,cube_info,node_info->child[i]);
2917 if (node_info->quantize_error <= cube_info->pruning_threshold)
2918 PruneChild(image,cube_info,node_info);
2922 Find minimum pruning threshold.
2924 if (node_info->number_unique > 0)
2925 cube_info->colors++;
2926 if (node_info->quantize_error < cube_info->next_threshold)
2927 cube_info->next_threshold=node_info->quantize_error;
2932 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2936 + R e d u c e I m a g e C o l o r s %
2940 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2942 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2943 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2944 % in the output image. On any given iteration over the tree, it selects
2945 % those nodes whose E value is minimal for pruning and merges their
2946 % color statistics upward. It uses a pruning threshold, Ep, to govern
2947 % node selection as follows:
2950 % while number of nodes with (n2 > 0) > required maximum number of colors
2951 % prune all nodes such that E <= Ep
2952 % Set Ep to minimum E in remaining nodes
2954 % This has the effect of minimizing any quantization error when merging
2955 % two nodes together.
2957 % When a node to be pruned has offspring, the pruning procedure invokes
2958 % itself recursively in order to prune the tree from the leaves upward.
2959 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2960 % corresponding data in that node's parent. This retains the pruned
2961 % node's color characteristics for later averaging.
2963 % For each node, n2 pixels exist for which that node represents the
2964 % smallest volume in RGB space containing those pixel's colors. When n2
2965 % > 0 the node will uniquely define a color in the output image. At the
2966 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2967 % the tree which represent colors present in the input image.
2969 % The other pixel count, n1, indicates the total number of colors
2970 % within the cubic volume which the node represents. This includes n1 -
2971 % n2 pixels whose colors should be defined by nodes at a lower level in
2974 % The format of the ReduceImageColors method is:
2976 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2978 % A description of each parameter follows.
2980 % o image: the image.
2982 % o cube_info: A pointer to the Cube structure.
2985 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2987 #define ReduceImageTag "Reduce/Image"
2998 cube_info->next_threshold=0.0;
2999 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3001 cube_info->pruning_threshold=cube_info->next_threshold;
3002 cube_info->next_threshold=cube_info->root->quantize_error-1;
3003 cube_info->colors=0;
3004 Reduce(image,cube_info,cube_info->root);
3005 offset=(MagickOffsetType) span-cube_info->colors;
3006 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3007 cube_info->maximum_colors+1);
3008 if (proceed == MagickFalse)
3014 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3018 % R e m a p I m a g e %
3022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3024 % RemapImage() replaces the colors of an image with the closest color from
3025 % a reference image.
3027 % The format of the RemapImage method is:
3029 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3030 % Image *image,const Image *remap_image)
3032 % A description of each parameter follows:
3034 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3036 % o image: the image.
3038 % o remap_image: the reference image.
3041 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3042 Image *image,const Image *remap_image)
3051 Initialize color cube.
3053 assert(image != (Image *) NULL);
3054 assert(image->signature == MagickSignature);
3055 if (image->debug != MagickFalse)
3056 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3057 assert(remap_image != (Image *) NULL);
3058 assert(remap_image->signature == MagickSignature);
3059 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3060 quantize_info->number_colors);
3061 if (cube_info == (CubeInfo *) NULL)
3062 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3064 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3065 if (status != MagickFalse)
3068 Classify image colors from the reference image.
3070 cube_info->quantize_info->number_colors=cube_info->colors;
3071 status=AssignImageColors(image,cube_info);
3073 DestroyCubeInfo(cube_info);
3078 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3082 % R e m a p I m a g e s %
3086 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3088 % RemapImages() replaces the colors of a sequence of images with the
3089 % closest color from a reference image.
3091 % The format of the RemapImage method is:
3093 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3094 % Image *images,Image *remap_image)
3096 % A description of each parameter follows:
3098 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3100 % o images: the image sequence.
3102 % o remap_image: the reference image.
3105 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3106 Image *images,const Image *remap_image)
3117 assert(images != (Image *) NULL);
3118 assert(images->signature == MagickSignature);
3119 if (images->debug != MagickFalse)
3120 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3122 if (remap_image == (Image *) NULL)
3125 Create a global colormap for an image sequence.
3127 status=QuantizeImages(quantize_info,images);
3131 Classify image colors from the reference image.
3133 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3134 quantize_info->number_colors);
3135 if (cube_info == (CubeInfo *) NULL)
3136 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3138 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3139 if (status != MagickFalse)
3142 Classify image colors from the reference image.
3144 cube_info->quantize_info->number_colors=cube_info->colors;
3146 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3148 status=AssignImageColors(image,cube_info);
3149 if (status == MagickFalse)
3153 DestroyCubeInfo(cube_info);
3158 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3162 % S e t G r a y s c a l e I m a g e %
3166 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3168 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3170 % The format of the SetGrayscaleImage method is:
3172 % MagickBooleanType SetGrayscaleImage(Image *image)
3174 % A description of each parameter follows:
3176 % o image: The image.
3180 #if defined(__cplusplus) || defined(c_plusplus)
3184 static int IntensityCompare(const void *x,const void *y)
3193 color_1=(PixelPacket *) x;
3194 color_2=(PixelPacket *) y;
3195 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3196 PixelIntensityToQuantum(color_2);
3197 return((int) intensity);
3200 #if defined(__cplusplus) || defined(c_plusplus)
3204 static MagickBooleanType SetGrayscaleImage(Image *image)
3226 assert(image != (Image *) NULL);
3227 assert(image->signature == MagickSignature);
3228 if (image->type != GrayscaleType)
3229 (void) TransformImageColorspace(image,GRAYColorspace);
3230 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3231 sizeof(*colormap_index));
3232 if (colormap_index == (ssize_t *) NULL)
3233 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3235 if (image->storage_class != PseudoClass)
3240 for (i=0; i <= (ssize_t) MaxMap; i++)
3241 colormap_index[i]=(-1);
3242 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3243 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3247 exception=(&image->exception);
3248 image_view=AcquireCacheView(image);
3249 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3250 #pragma omp parallel for schedule(dynamic,4) shared(status)
3252 for (y=0; y < (ssize_t) image->rows; y++)
3254 register IndexPacket
3257 register const PixelPacket
3263 if (status == MagickFalse)
3265 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3267 if (q == (PixelPacket *) NULL)
3272 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3273 for (x=0; x < (ssize_t) image->columns; x++)
3278 intensity=ScaleQuantumToMap(q->red);
3279 if (colormap_index[intensity] < 0)
3281 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3282 #pragma omp critical (MagickCore_SetGrayscaleImage)
3284 if (colormap_index[intensity] < 0)
3286 colormap_index[intensity]=(ssize_t) image->colors;
3287 image->colormap[image->colors]=(*q);
3291 indexes[x]=(IndexPacket) colormap_index[intensity];
3294 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3297 image_view=DestroyCacheView(image_view);
3299 for (i=0; i < (ssize_t) image->colors; i++)
3300 image->colormap[i].opacity=(unsigned short) i;
3301 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3303 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3305 if (colormap == (PixelPacket *) NULL)
3306 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3309 colormap[j]=image->colormap[0];
3310 for (i=0; i < (ssize_t) image->colors; i++)
3312 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3315 colormap[j]=image->colormap[i];
3317 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3319 image->colors=(size_t) (j+1);
3320 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3321 image->colormap=colormap;
3323 exception=(&image->exception);
3324 image_view=AcquireCacheView(image);
3325 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3326 #pragma omp parallel for schedule(dynamic,4) shared(status)
3328 for (y=0; y < (ssize_t) image->rows; y++)
3330 register IndexPacket
3333 register const PixelPacket
3339 if (status == MagickFalse)
3341 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3342 if (q == (PixelPacket *) NULL)
3347 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3348 for (x=0; x < (ssize_t) image->columns; x++)
3349 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3350 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3353 image_view=DestroyCacheView(image_view);
3354 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3355 image->type=GrayscaleType;
3356 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3357 image->type=BilevelType;