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"
202 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
207 #define ErrorQueueLength 16
208 #define MaxNodes 266817
209 #define MaxTreeDepth 8
210 #define NodesInAList 1920
215 typedef struct _RealPixelPacket
224 typedef struct _NodeInfo
245 typedef struct _Nodes
254 typedef struct _CubeInfo
292 error[ErrorQueueLength];
295 weights[ErrorQueueLength];
321 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
324 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
326 static MagickBooleanType
327 AssignImageColors(Image *,CubeInfo *),
328 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
329 DitherImage(Image *,CubeInfo *),
330 SetGrayscaleImage(Image *);
333 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
336 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
337 DestroyCubeInfo(CubeInfo *),
338 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
339 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
340 ReduceImageColors(const Image *,CubeInfo *);
343 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
347 % A c q u i r e Q u a n t i z e I n f o %
351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
353 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
355 % The format of the AcquireQuantizeInfo method is:
357 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
359 % A description of each parameter follows:
361 % o image_info: the image info.
364 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
369 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
370 if (quantize_info == (QuantizeInfo *) NULL)
371 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
372 GetQuantizeInfo(quantize_info);
373 if (image_info != (ImageInfo *) NULL)
378 quantize_info->dither=image_info->dither;
379 option=GetImageOption(image_info,"dither");
380 if (option != (const char *) NULL)
381 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
382 MagickDitherOptions,MagickFalse,option);
383 quantize_info->measure_error=image_info->verbose;
385 return(quantize_info);
389 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
393 + A s s i g n I m a g e C o l o r s %
397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399 % AssignImageColors() generates the output image from the pruned tree. The
400 % output image consists of two parts: (1) A color map, which is an array
401 % of color descriptions (RGB triples) for each color present in the
402 % output image; (2) A pixel array, which represents each pixel as an
403 % index into the color map array.
405 % First, the assignment phase makes one pass over the pruned color
406 % description tree to establish the image's color map. For each node
407 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
408 % color of all pixels that classify no lower than this node. Each of
409 % these colors becomes an entry in the color map.
411 % Finally, the assignment phase reclassifies each pixel in the pruned
412 % tree to identify the deepest node containing the pixel's color. The
413 % pixel's value in the pixel array becomes the index of this node's mean
414 % color in the color map.
416 % The format of the AssignImageColors() method is:
418 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
420 % A description of each parameter follows.
422 % o image: the image.
424 % o cube_info: A pointer to the Cube structure.
428 static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
429 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
434 if ((cube_info->associate_alpha == MagickFalse) ||
435 (pixel->opacity == OpaqueOpacity))
437 alpha_pixel->red=(MagickRealType) pixel->red;
438 alpha_pixel->green=(MagickRealType) pixel->green;
439 alpha_pixel->blue=(MagickRealType) pixel->blue;
440 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
443 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
444 alpha_pixel->red=alpha*pixel->red;
445 alpha_pixel->green=alpha*pixel->green;
446 alpha_pixel->blue=alpha*pixel->blue;
447 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
450 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
454 if (value >= QuantumRange)
455 return((Quantum) QuantumRange);
456 return((Quantum) (value+0.5));
459 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
460 const RealPixelPacket *pixel,size_t index)
466 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
467 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
468 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
469 if (cube_info->associate_alpha != MagickFalse)
470 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
475 static inline MagickBooleanType IsSameColor(const Image *image,
476 const PixelPacket *p,const PixelPacket *q)
478 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
480 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
485 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
487 #define AssignImageTag "Assign/Image"
502 register const NodeInfo
513 Allocate image colormap.
515 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
516 (cube_info->quantize_info->colorspace != CMYKColorspace))
517 (void) TransformImageColorspace((Image *) image,
518 cube_info->quantize_info->colorspace);
520 if ((image->colorspace != GRAYColorspace) &&
521 (image->colorspace != RGBColorspace) &&
522 (image->colorspace != CMYColorspace))
523 (void) TransformImageColorspace((Image *) image,RGBColorspace);
524 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
525 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
528 cube_info->transparent_pixels=0;
529 cube_info->transparent_index=(-1);
530 (void) DefineImageColormap(image,cube_info,cube_info->root);
532 Create a reduced color image.
534 if ((cube_info->quantize_info->dither != MagickFalse) &&
535 (cube_info->quantize_info->dither_method != NoDitherMethod))
536 (void) DitherImage(image,cube_info);
545 exception=(&image->exception);
546 image_view=AcquireCacheView(image);
547 for (y=0; y < (ssize_t) image->rows; y++)
555 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
557 if (q == (PixelPacket *) NULL)
559 indexes=GetCacheViewAuthenticIndexQueue(image_view);
560 for (x=0; x < (ssize_t) image->columns; x+=count)
563 Identify the deepest node containing the pixel's color.
565 for (count=1; (x+count) < (ssize_t) image->columns; count++)
566 if (IsSameColor(image,q,q+count) == MagickFalse)
568 AssociateAlphaPixel(cube_info,q,&pixel);
569 node_info=cube_info->root;
570 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
572 id=ColorToNodeId(cube_info,&pixel,index);
573 if (node_info->child[id] == (NodeInfo *) NULL)
575 node_info=node_info->child[id];
578 Find closest color among siblings and their children.
580 cube_info->target=pixel;
581 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
582 (QuantumRange+1.0)+1.0);
583 ClosestColor(image,cube_info,node_info->parent);
584 index=cube_info->color_number;
585 for (i=0; i < (ssize_t) count; i++)
587 if (image->storage_class == PseudoClass)
588 indexes[x+i]=(IndexPacket) index;
589 if (cube_info->quantize_info->measure_error == MagickFalse)
591 q->red=image->colormap[index].red;
592 q->green=image->colormap[index].green;
593 q->blue=image->colormap[index].blue;
594 if (cube_info->associate_alpha != MagickFalse)
595 q->opacity=image->colormap[index].opacity;
600 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
602 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
604 if (proceed == MagickFalse)
607 image_view=DestroyCacheView(image_view);
609 if (cube_info->quantize_info->measure_error != MagickFalse)
610 (void) GetImageQuantizeError(image);
611 if ((cube_info->quantize_info->number_colors == 2) &&
612 (cube_info->quantize_info->colorspace == GRAYColorspace))
624 for (i=0; i < (ssize_t) image->colors; i++)
626 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
627 QuantumRange/2.0) ? 0 : QuantumRange);
634 (void) SyncImage(image);
635 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
636 (cube_info->quantize_info->colorspace != CMYKColorspace))
637 (void) TransformImageColorspace((Image *) image,RGBColorspace);
642 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
646 + C l a s s i f y I m a g e C o l o r s %
650 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
652 % ClassifyImageColors() begins by initializing a color description tree
653 % of sufficient depth to represent each possible input color in a leaf.
654 % However, it is impractical to generate a fully-formed color
655 % description tree in the storage_class phase for realistic values of
656 % Cmax. If colors components in the input image are quantized to k-bit
657 % precision, so that Cmax= 2k-1, the tree would need k levels below the
658 % root node to allow representing each possible input color in a leaf.
659 % This becomes prohibitive because the tree's total number of nodes is
662 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
663 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
664 % Initializes data structures for nodes only as they are needed; (2)
665 % Chooses a maximum depth for the tree as a function of the desired
666 % number of colors in the output image (currently log2(colormap size)).
668 % For each pixel in the input image, storage_class scans downward from
669 % the root of the color description tree. At each level of the tree it
670 % identifies the single node which represents a cube in RGB space
671 % containing It updates the following data for each such node:
673 % n1 : Number of pixels whose color is contained in the RGB cube
674 % which this node represents;
676 % n2 : Number of pixels whose color is not represented in a node at
677 % lower depth in the tree; initially, n2 = 0 for all nodes except
678 % leaves of the tree.
680 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
681 % all pixels not classified at a lower depth. The combination of
682 % these sums and n2 will ultimately characterize the mean color of a
683 % set of pixels represented by this node.
685 % E: the distance squared in RGB space between each pixel contained
686 % within a node and the nodes' center. This represents the quantization
689 % The format of the ClassifyImageColors() method is:
691 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
692 % const Image *image,ExceptionInfo *exception)
694 % A description of each parameter follows.
696 % o cube_info: A pointer to the Cube structure.
698 % o image: the image.
702 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
707 associate_alpha=image->matte;
708 if (cube_info->quantize_info->colorspace == TransparentColorspace)
709 associate_alpha=MagickFalse;
710 if ((cube_info->quantize_info->number_colors == 2) &&
711 (cube_info->quantize_info->colorspace == GRAYColorspace))
712 associate_alpha=MagickFalse;
713 cube_info->associate_alpha=associate_alpha;
716 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
717 const Image *image,ExceptionInfo *exception)
719 #define ClassifyImageTag "Classify/Image"
751 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
753 SetAssociatedAlpha(image,cube_info);
754 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
755 (cube_info->quantize_info->colorspace != CMYKColorspace))
756 (void) TransformImageColorspace((Image *) image,
757 cube_info->quantize_info->colorspace);
759 if ((image->colorspace != GRAYColorspace) &&
760 (image->colorspace != CMYColorspace) &&
761 (image->colorspace != RGBColorspace))
762 (void) TransformImageColorspace((Image *) image,RGBColorspace);
763 midpoint.red=(MagickRealType) QuantumRange/2.0;
764 midpoint.green=(MagickRealType) QuantumRange/2.0;
765 midpoint.blue=(MagickRealType) QuantumRange/2.0;
766 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
768 image_view=AcquireCacheView(image);
769 for (y=0; y < (ssize_t) image->rows; y++)
771 register const PixelPacket
777 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
778 if (p == (const PixelPacket *) NULL)
780 if (cube_info->nodes > MaxNodes)
783 Prune one level if the color tree is too large.
785 PruneLevel(image,cube_info,cube_info->root);
788 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
791 Start at the root and descend the color cube tree.
793 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
794 if (IsSameColor(image,p,p+count) == MagickFalse)
796 AssociateAlphaPixel(cube_info,p,&pixel);
797 index=MaxTreeDepth-1;
798 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
800 node_info=cube_info->root;
801 for (level=1; level <= MaxTreeDepth; level++)
804 id=ColorToNodeId(cube_info,&pixel,index);
805 mid.red+=(id & 1) != 0 ? bisect : -bisect;
806 mid.green+=(id & 2) != 0 ? bisect : -bisect;
807 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
808 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
809 if (node_info->child[id] == (NodeInfo *) NULL)
812 Set colors of new node to contain pixel.
814 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
815 if (node_info->child[id] == (NodeInfo *) NULL)
816 (void) ThrowMagickException(exception,GetMagickModule(),
817 ResourceLimitError,"MemoryAllocationFailed","`%s'",
819 if (level == MaxTreeDepth)
823 Approximate the quantization error represented by this node.
825 node_info=node_info->child[id];
826 error.red=QuantumScale*(pixel.red-mid.red);
827 error.green=QuantumScale*(pixel.green-mid.green);
828 error.blue=QuantumScale*(pixel.blue-mid.blue);
829 if (cube_info->associate_alpha != MagickFalse)
830 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
831 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
832 count*error.green*error.green+count*error.blue*error.blue+
833 count*error.opacity*error.opacity));
834 cube_info->root->quantize_error+=node_info->quantize_error;
838 Sum RGB for this leaf for later derivation of the mean cube color.
840 node_info->number_unique+=count;
841 node_info->total_color.red+=count*QuantumScale*pixel.red;
842 node_info->total_color.green+=count*QuantumScale*pixel.green;
843 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
844 if (cube_info->associate_alpha != MagickFalse)
845 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
848 if (cube_info->colors > cube_info->maximum_colors)
850 PruneToCubeDepth(image,cube_info,cube_info->root);
853 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
855 if (proceed == MagickFalse)
858 for (y++; y < (ssize_t) image->rows; y++)
860 register const PixelPacket
866 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
867 if (p == (const PixelPacket *) NULL)
869 if (cube_info->nodes > MaxNodes)
872 Prune one level if the color tree is too large.
874 PruneLevel(image,cube_info,cube_info->root);
877 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
880 Start at the root and descend the color cube tree.
882 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
883 if (IsSameColor(image,p,p+count) == MagickFalse)
885 AssociateAlphaPixel(cube_info,p,&pixel);
886 index=MaxTreeDepth-1;
887 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
889 node_info=cube_info->root;
890 for (level=1; level <= cube_info->depth; level++)
893 id=ColorToNodeId(cube_info,&pixel,index);
894 mid.red+=(id & 1) != 0 ? bisect : -bisect;
895 mid.green+=(id & 2) != 0 ? bisect : -bisect;
896 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
897 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
898 if (node_info->child[id] == (NodeInfo *) NULL)
901 Set colors of new node to contain pixel.
903 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
904 if (node_info->child[id] == (NodeInfo *) NULL)
905 (void) ThrowMagickException(exception,GetMagickModule(),
906 ResourceLimitError,"MemoryAllocationFailed","%s",
908 if (level == cube_info->depth)
912 Approximate the quantization error represented by this node.
914 node_info=node_info->child[id];
915 error.red=QuantumScale*(pixel.red-mid.red);
916 error.green=QuantumScale*(pixel.green-mid.green);
917 error.blue=QuantumScale*(pixel.blue-mid.blue);
918 if (cube_info->associate_alpha != MagickFalse)
919 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
920 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
921 count*error.green*error.green+count*error.blue*error.blue+
922 count*error.opacity*error.opacity));
923 cube_info->root->quantize_error+=node_info->quantize_error;
927 Sum RGB for this leaf for later derivation of the mean cube color.
929 node_info->number_unique+=count;
930 node_info->total_color.red+=count*QuantumScale*pixel.red;
931 node_info->total_color.green+=count*QuantumScale*pixel.green;
932 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
933 if (cube_info->associate_alpha != MagickFalse)
934 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
937 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
939 if (proceed == MagickFalse)
942 image_view=DestroyCacheView(image_view);
943 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
944 (cube_info->quantize_info->colorspace != CMYKColorspace))
945 (void) TransformImageColorspace((Image *) image,RGBColorspace);
950 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
954 % C l o n e Q u a n t i z e I n f o %
958 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
960 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
961 % or if quantize info is NULL, a new one.
963 % The format of the CloneQuantizeInfo method is:
965 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
967 % A description of each parameter follows:
969 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
970 % quantize info, or if image info is NULL a new one.
972 % o quantize_info: a structure of type info.
975 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
980 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
981 if (clone_info == (QuantizeInfo *) NULL)
982 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
983 GetQuantizeInfo(clone_info);
984 if (quantize_info == (QuantizeInfo *) NULL)
986 clone_info->number_colors=quantize_info->number_colors;
987 clone_info->tree_depth=quantize_info->tree_depth;
988 clone_info->dither=quantize_info->dither;
989 clone_info->dither_method=quantize_info->dither_method;
990 clone_info->colorspace=quantize_info->colorspace;
991 clone_info->measure_error=quantize_info->measure_error;
996 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1000 + C l o s e s t C o l o r %
1004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1006 % ClosestColor() traverses the color cube tree at a particular node and
1007 % determines which colormap entry best represents the input color.
1009 % The format of the ClosestColor method is:
1011 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1012 % const NodeInfo *node_info)
1014 % A description of each parameter follows.
1016 % o image: the image.
1018 % o cube_info: A pointer to the Cube structure.
1020 % o node_info: the address of a structure of type NodeInfo which points to a
1021 % node in the color cube tree that is to be pruned.
1024 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1025 const NodeInfo *node_info)
1034 Traverse any children.
1036 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1037 for (i=0; i < (ssize_t) number_children; i++)
1038 if (node_info->child[i] != (NodeInfo *) NULL)
1039 ClosestColor(image,cube_info,node_info->child[i]);
1040 if (node_info->number_unique != 0)
1045 register MagickRealType
1050 register PixelPacket
1053 register RealPixelPacket
1057 Determine if this color is "closest".
1059 p=image->colormap+node_info->color_number;
1060 q=(&cube_info->target);
1063 if (cube_info->associate_alpha != MagickFalse)
1065 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1066 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1068 pixel=alpha*p->red-beta*q->red;
1069 distance=pixel*pixel;
1070 if (distance <= cube_info->distance)
1072 pixel=alpha*p->green-beta*q->green;
1073 distance+=pixel*pixel;
1074 if (distance <= cube_info->distance)
1076 pixel=alpha*p->blue-beta*q->blue;
1077 distance+=pixel*pixel;
1078 if (distance <= cube_info->distance)
1081 distance+=pixel*pixel;
1082 if (distance <= cube_info->distance)
1084 cube_info->distance=distance;
1085 cube_info->color_number=node_info->color_number;
1094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1098 % C o m p r e s s I m a g e C o l o r m a p %
1102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1104 % CompressImageColormap() compresses an image colormap by removing any
1105 % duplicate or unused color entries.
1107 % The format of the CompressImageColormap method is:
1109 % MagickBooleanType CompressImageColormap(Image *image)
1111 % A description of each parameter follows:
1113 % o image: the image.
1116 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1121 assert(image != (Image *) NULL);
1122 assert(image->signature == MagickSignature);
1123 if (image->debug != MagickFalse)
1124 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1125 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1126 return(MagickFalse);
1127 GetQuantizeInfo(&quantize_info);
1128 quantize_info.number_colors=image->colors;
1129 quantize_info.tree_depth=MaxTreeDepth;
1130 return(QuantizeImage(&quantize_info,image));
1134 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1138 + D e f i n e I m a g e C o l o r m a p %
1142 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1144 % DefineImageColormap() traverses the color cube tree and notes each colormap
1145 % entry. A colormap entry is any node in the color cube tree where the
1146 % of unique colors is not zero. DefineImageColormap() returns the number of
1147 % colors in the image colormap.
1149 % The format of the DefineImageColormap method is:
1151 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1152 % NodeInfo *node_info)
1154 % A description of each parameter follows.
1156 % o image: the image.
1158 % o cube_info: A pointer to the Cube structure.
1160 % o node_info: the address of a structure of type NodeInfo which points to a
1161 % node in the color cube tree that is to be pruned.
1164 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1165 NodeInfo *node_info)
1174 Traverse any children.
1176 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1177 for (i=0; i < (ssize_t) number_children; i++)
1178 if (node_info->child[i] != (NodeInfo *) NULL)
1179 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1180 if (node_info->number_unique != 0)
1182 register MagickRealType
1185 register PixelPacket
1189 Colormap entry is defined by the mean color in this cube.
1191 q=image->colormap+image->colors;
1192 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1193 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1194 if (cube_info->associate_alpha == MagickFalse)
1196 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1197 node_info->total_color.red));
1198 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1199 node_info->total_color.green));
1200 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1201 node_info->total_color.blue));
1202 SetOpacityPixelComponent(q,OpaqueOpacity);
1209 opacity=(MagickRealType) (alpha*QuantumRange*
1210 node_info->total_color.opacity);
1211 q->opacity=ClampToQuantum(opacity);
1212 if (q->opacity == OpaqueOpacity)
1214 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1215 node_info->total_color.red));
1216 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1217 node_info->total_color.green));
1218 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1219 node_info->total_color.blue));
1226 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1227 (MagickRealType) q->opacity));
1228 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1229 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1230 node_info->total_color.red));
1231 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1232 QuantumRange*node_info->total_color.green));
1233 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1234 node_info->total_color.blue));
1235 if (node_info->number_unique > cube_info->transparent_pixels)
1237 cube_info->transparent_pixels=node_info->number_unique;
1238 cube_info->transparent_index=(ssize_t) image->colors;
1242 node_info->color_number=image->colors++;
1244 return(image->colors);
1248 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1252 + D e s t r o y C u b e I n f o %
1256 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1258 % DestroyCubeInfo() deallocates memory associated with an image.
1260 % The format of the DestroyCubeInfo method is:
1262 % DestroyCubeInfo(CubeInfo *cube_info)
1264 % A description of each parameter follows:
1266 % o cube_info: the address of a structure of type CubeInfo.
1269 static void DestroyCubeInfo(CubeInfo *cube_info)
1275 Release color cube tree storage.
1279 nodes=cube_info->node_queue->next;
1280 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1281 cube_info->node_queue->nodes);
1282 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1283 cube_info->node_queue);
1284 cube_info->node_queue=nodes;
1285 } while (cube_info->node_queue != (Nodes *) NULL);
1286 if (cube_info->cache != (ssize_t *) NULL)
1287 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1288 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1289 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1293 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1297 % D e s t r o y Q u a n t i z e I n f o %
1301 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1303 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1306 % The format of the DestroyQuantizeInfo method is:
1308 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1310 % A description of each parameter follows:
1312 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1315 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1317 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1318 assert(quantize_info != (QuantizeInfo *) NULL);
1319 assert(quantize_info->signature == MagickSignature);
1320 quantize_info->signature=(~MagickSignature);
1321 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1322 return(quantize_info);
1326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1330 + D i t h e r I m a g e %
1334 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1336 % DitherImage() distributes the difference between an original image and
1337 % the corresponding color reduced algorithm to neighboring pixels using
1338 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1339 % MagickTrue if the image is dithered otherwise MagickFalse.
1341 % The format of the DitherImage method is:
1343 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1345 % A description of each parameter follows.
1347 % o image: the image.
1349 % o cube_info: A pointer to the Cube structure.
1353 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1354 const RealPixelPacket *pixel)
1356 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1357 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1358 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1359 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1365 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1366 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1367 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1368 if (cube_info->associate_alpha != MagickFalse)
1369 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1374 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1376 #define DitherImageTag "Dither/Image"
1406 Distribute quantization error using Floyd-Steinberg.
1408 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1409 2*sizeof(*scanlines));
1410 if (scanlines == (RealPixelPacket *) NULL)
1411 return(MagickFalse);
1413 exception=(&image->exception);
1414 image_view=AcquireCacheView(image);
1415 for (y=0; y < (ssize_t) image->rows; y++)
1417 register IndexPacket
1424 register PixelPacket
1427 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1428 if (q == (PixelPacket *) NULL)
1429 return(MagickFalse);
1430 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1431 current=scanlines+(y & 0x01)*image->columns;
1432 previous=scanlines+((y+1) & 0x01)*image->columns;
1433 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1434 for (x=0; x < (ssize_t) image->columns; x++)
1436 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1437 AssociateAlphaPixel(cube_info,q+u,&pixel);
1440 pixel.red+=7*current[u-v].red/16;
1441 pixel.green+=7*current[u-v].green/16;
1442 pixel.blue+=7*current[u-v].blue/16;
1443 if (cube_info->associate_alpha != MagickFalse)
1444 pixel.opacity+=7*current[u-v].opacity/16;
1448 if (x < (ssize_t) (image->columns-1))
1450 pixel.red+=previous[u+v].red/16;
1451 pixel.green+=previous[u+v].green/16;
1452 pixel.blue+=previous[u+v].blue/16;
1453 if (cube_info->associate_alpha != MagickFalse)
1454 pixel.opacity+=previous[u+v].opacity/16;
1456 pixel.red+=5*previous[u].red/16;
1457 pixel.green+=5*previous[u].green/16;
1458 pixel.blue+=5*previous[u].blue/16;
1459 if (cube_info->associate_alpha != MagickFalse)
1460 pixel.opacity+=5*previous[u].opacity/16;
1463 pixel.red+=3*previous[u-v].red/16;
1464 pixel.green+=3*previous[u-v].green/16;
1465 pixel.blue+=3*previous[u-v].blue/16;
1466 if (cube_info->associate_alpha != MagickFalse)
1467 pixel.opacity+=3*previous[u-v].opacity/16;
1470 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1471 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1472 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1473 if (cube_info->associate_alpha != MagickFalse)
1474 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1475 i=CacheOffset(cube_info,&pixel);
1476 if (p->cache[i] < 0)
1485 Identify the deepest node containing the pixel's color.
1488 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1490 id=ColorToNodeId(cube_info,&pixel,index);
1491 if (node_info->child[id] == (NodeInfo *) NULL)
1493 node_info=node_info->child[id];
1496 Find closest color among siblings and their children.
1499 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1501 ClosestColor(image,p,node_info->parent);
1502 p->cache[i]=(ssize_t) p->color_number;
1505 Assign pixel to closest colormap entry.
1507 index=(size_t) p->cache[i];
1508 if (image->storage_class == PseudoClass)
1509 indexes[u]=(IndexPacket) index;
1510 if (cube_info->quantize_info->measure_error == MagickFalse)
1512 (q+u)->red=image->colormap[index].red;
1513 (q+u)->green=image->colormap[index].green;
1514 (q+u)->blue=image->colormap[index].blue;
1515 if (cube_info->associate_alpha != MagickFalse)
1516 (q+u)->opacity=image->colormap[index].opacity;
1518 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1519 return(MagickFalse);
1523 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1524 current[u].red=pixel.red-color.red;
1525 current[u].green=pixel.green-color.green;
1526 current[u].blue=pixel.blue-color.blue;
1527 if (cube_info->associate_alpha != MagickFalse)
1528 current[u].opacity=pixel.opacity-color.opacity;
1529 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1530 if (proceed == MagickFalse)
1531 return(MagickFalse);
1535 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1536 image_view=DestroyCacheView(image_view);
1540 static MagickBooleanType
1541 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1543 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1544 const size_t level,const unsigned int direction)
1551 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1552 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1553 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1558 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1559 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1560 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1565 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1566 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1567 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1572 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1573 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1574 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1585 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1586 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1587 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1588 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1589 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1590 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1591 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1596 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1597 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1598 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1599 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1600 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1601 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1602 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1607 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1608 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1609 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1610 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1611 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1612 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1613 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1618 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1619 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1620 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1621 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1622 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1623 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1624 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1632 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1633 CubeInfo *cube_info,const unsigned int direction)
1635 #define DitherImageTag "Dither/Image"
1651 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1652 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1657 register IndexPacket
1663 register PixelPacket
1669 exception=(&image->exception);
1670 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1671 if (q == (PixelPacket *) NULL)
1672 return(MagickFalse);
1673 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1674 AssociateAlphaPixel(cube_info,q,&pixel);
1675 for (i=0; i < ErrorQueueLength; i++)
1677 pixel.red+=p->weights[i]*p->error[i].red;
1678 pixel.green+=p->weights[i]*p->error[i].green;
1679 pixel.blue+=p->weights[i]*p->error[i].blue;
1680 if (cube_info->associate_alpha != MagickFalse)
1681 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1683 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1684 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1685 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1686 if (cube_info->associate_alpha != MagickFalse)
1687 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1688 i=CacheOffset(cube_info,&pixel);
1689 if (p->cache[i] < 0)
1698 Identify the deepest node containing the pixel's color.
1701 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1703 id=ColorToNodeId(cube_info,&pixel,index);
1704 if (node_info->child[id] == (NodeInfo *) NULL)
1706 node_info=node_info->child[id];
1709 Find closest color among siblings and their children.
1712 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1713 QuantumRange+1.0)+1.0);
1714 ClosestColor(image,p,node_info->parent);
1715 p->cache[i]=(ssize_t) p->color_number;
1718 Assign pixel to closest colormap entry.
1720 index=(size_t) (1*p->cache[i]);
1721 if (image->storage_class == PseudoClass)
1722 *indexes=(IndexPacket) index;
1723 if (cube_info->quantize_info->measure_error == MagickFalse)
1725 q->red=image->colormap[index].red;
1726 q->green=image->colormap[index].green;
1727 q->blue=image->colormap[index].blue;
1728 if (cube_info->associate_alpha != MagickFalse)
1729 q->opacity=image->colormap[index].opacity;
1731 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1732 return(MagickFalse);
1734 Propagate the error as the last entry of the error queue.
1736 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1737 sizeof(p->error[0]));
1738 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1739 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1740 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1741 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1742 if (cube_info->associate_alpha != MagickFalse)
1743 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1744 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1745 if (proceed == MagickFalse)
1746 return(MagickFalse);
1751 case WestGravity: p->x--; break;
1752 case EastGravity: p->x++; break;
1753 case NorthGravity: p->y--; break;
1754 case SouthGravity: p->y++; break;
1759 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1766 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1773 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1787 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1788 return(FloydSteinbergDither(image,cube_info));
1790 Distribute quantization error along a Hilbert curve.
1792 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1793 sizeof(*cube_info->error));
1796 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1797 for (depth=1; i != 0; depth++)
1799 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1801 cube_info->offset=0;
1802 cube_info->span=(MagickSizeType) image->columns*image->rows;
1803 image_view=AcquireCacheView(image);
1805 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1806 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1807 image_view=DestroyCacheView(image_view);
1812 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1816 + G e t C u b e I n f o %
1820 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1822 % GetCubeInfo() initialize the Cube data structure.
1824 % The format of the GetCubeInfo method is:
1826 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1827 % const size_t depth,const size_t maximum_colors)
1829 % A description of each parameter follows.
1831 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1833 % o depth: Normally, this integer value is zero or one. A zero or
1834 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1835 % A tree of this depth generally allows the best representation of the
1836 % reference image with the least amount of memory and the fastest
1837 % computational speed. In some cases, such as an image with low color
1838 % dispersion (a few number of colors), a value other than
1839 % Log4(number_colors) is required. To expand the color tree completely,
1842 % o maximum_colors: maximum colors.
1845 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1846 const size_t depth,const size_t maximum_colors)
1862 Initialize tree to describe color cube_info.
1864 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1865 if (cube_info == (CubeInfo *) NULL)
1866 return((CubeInfo *) NULL);
1867 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1868 cube_info->depth=depth;
1869 if (cube_info->depth > MaxTreeDepth)
1870 cube_info->depth=MaxTreeDepth;
1871 if (cube_info->depth < 2)
1873 cube_info->maximum_colors=maximum_colors;
1875 Initialize root node.
1877 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1878 if (cube_info->root == (NodeInfo *) NULL)
1879 return((CubeInfo *) NULL);
1880 cube_info->root->parent=cube_info->root;
1881 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1882 if (cube_info->quantize_info->dither == MagickFalse)
1885 Initialize dither resources.
1887 length=(size_t) (1UL << (4*(8-CacheShift)));
1888 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1889 sizeof(*cube_info->cache));
1890 if (cube_info->cache == (ssize_t *) NULL)
1891 return((CubeInfo *) NULL);
1893 Initialize color cache.
1895 for (i=0; i < (ssize_t) length; i++)
1896 cube_info->cache[i]=(-1);
1898 Distribute weights along a curve of exponential decay.
1901 for (i=0; i < ErrorQueueLength; i++)
1903 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1904 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1907 Normalize the weighting factors.
1910 for (i=0; i < ErrorQueueLength; i++)
1911 weight+=cube_info->weights[i];
1913 for (i=0; i < ErrorQueueLength; i++)
1915 cube_info->weights[i]/=weight;
1916 sum+=cube_info->weights[i];
1918 cube_info->weights[0]+=1.0-sum;
1923 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1927 + G e t N o d e I n f o %
1931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1933 % GetNodeInfo() allocates memory for a new node in the color cube tree and
1934 % presets all fields to zero.
1936 % The format of the GetNodeInfo method is:
1938 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1939 % const size_t level,NodeInfo *parent)
1941 % A description of each parameter follows.
1943 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1945 % o id: Specifies the child number of the node.
1947 % o level: Specifies the level in the storage_class the node resides.
1950 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1951 const size_t level,NodeInfo *parent)
1956 if (cube_info->free_nodes == 0)
1962 Allocate a new queue of nodes.
1964 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
1965 if (nodes == (Nodes *) NULL)
1966 return((NodeInfo *) NULL);
1967 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1968 sizeof(*nodes->nodes));
1969 if (nodes->nodes == (NodeInfo *) NULL)
1970 return((NodeInfo *) NULL);
1971 nodes->next=cube_info->node_queue;
1972 cube_info->node_queue=nodes;
1973 cube_info->next_node=nodes->nodes;
1974 cube_info->free_nodes=NodesInAList;
1977 cube_info->free_nodes--;
1978 node_info=cube_info->next_node++;
1979 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1980 node_info->parent=parent;
1982 node_info->level=level;
1987 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1991 % G e t I m a g e Q u a n t i z e E r r o r %
1995 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1997 % GetImageQuantizeError() measures the difference between the original
1998 % and quantized images. This difference is the total quantization error.
1999 % The error is computed by summing over all pixels in an image the distance
2000 % squared in RGB space between each reference pixel value and its quantized
2001 % value. These values are computed:
2003 % o mean_error_per_pixel: This value is the mean error for any single
2004 % pixel in the image.
2006 % o normalized_mean_square_error: This value is the normalized mean
2007 % quantization error for any single pixel in the image. This distance
2008 % measure is normalized to a range between 0 and 1. It is independent
2009 % of the range of red, green, and blue values in the image.
2011 % o normalized_maximum_square_error: Thsi value is the normalized
2012 % maximum quantization error for any single pixel in the image. This
2013 % distance measure is normalized to a range between 0 and 1. It is
2014 % independent of the range of red, green, and blue values in your image.
2016 % The format of the GetImageQuantizeError method is:
2018 % MagickBooleanType GetImageQuantizeError(Image *image)
2020 % A description of each parameter follows.
2022 % o image: the image.
2025 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2046 mean_error_per_pixel;
2051 assert(image != (Image *) NULL);
2052 assert(image->signature == MagickSignature);
2053 if (image->debug != MagickFalse)
2054 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2055 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2056 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2057 if (image->storage_class == DirectClass)
2061 area=3.0*image->columns*image->rows;
2063 mean_error_per_pixel=0.0;
2065 exception=(&image->exception);
2066 image_view=AcquireCacheView(image);
2067 for (y=0; y < (ssize_t) image->rows; y++)
2069 register const PixelPacket
2075 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2076 if (p == (const PixelPacket *) NULL)
2078 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2079 for (x=0; x < (ssize_t) image->columns; x++)
2081 index=1UL*indexes[x];
2082 if (image->matte != MagickFalse)
2084 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2085 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2086 image->colormap[index].opacity));
2088 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2089 mean_error_per_pixel+=distance;
2090 mean_error+=distance*distance;
2091 if (distance > maximum_error)
2092 maximum_error=distance;
2093 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2094 mean_error_per_pixel+=distance;
2095 mean_error+=distance*distance;
2096 if (distance > maximum_error)
2097 maximum_error=distance;
2098 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2099 mean_error_per_pixel+=distance;
2100 mean_error+=distance*distance;
2101 if (distance > maximum_error)
2102 maximum_error=distance;
2106 image_view=DestroyCacheView(image_view);
2107 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2108 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2110 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2115 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2119 % G e t Q u a n t i z e I n f o %
2123 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2125 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2127 % The format of the GetQuantizeInfo method is:
2129 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2131 % A description of each parameter follows:
2133 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2136 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2138 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2139 assert(quantize_info != (QuantizeInfo *) NULL);
2140 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2141 quantize_info->number_colors=256;
2142 quantize_info->dither=MagickTrue;
2143 quantize_info->dither_method=RiemersmaDitherMethod;
2144 quantize_info->colorspace=UndefinedColorspace;
2145 quantize_info->measure_error=MagickFalse;
2146 quantize_info->signature=MagickSignature;
2150 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2154 % P o s t e r i z e I m a g e C h a n n e l %
2158 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2160 % PosterizeImage() reduces the image to a limited number of colors for a
2163 % The format of the PosterizeImage method is:
2165 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2166 % const MagickBooleanType dither)
2167 % MagickBooleanType PosterizeImageChannel(Image *image,
2168 % const ChannelType channel,const size_t levels,
2169 % const MagickBooleanType dither)
2171 % A description of each parameter follows:
2173 % o image: Specifies a pointer to an Image structure.
2175 % o levels: Number of color levels allowed in each channel. Very low values
2176 % (2, 3, or 4) have the most visible effect.
2178 % o dither: Set this integer value to something other than zero to dither
2183 static inline ssize_t MagickRound(MagickRealType x)
2186 Round the fraction to nearest integer.
2189 return((ssize_t) (x+0.5));
2190 return((ssize_t) (x-0.5));
2193 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2194 const MagickBooleanType dither)
2199 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2203 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2204 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2206 #define PosterizeImageTag "Posterize/Image"
2207 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2208 QuantumScale*pixel*(levels-1))/MagickMax(levels-1,1)))
2231 assert(image != (Image *) NULL);
2232 assert(image->signature == MagickSignature);
2233 if (image->debug != MagickFalse)
2234 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2235 if (image->storage_class == PseudoClass)
2236 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2237 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2239 for (i=0; i < (ssize_t) image->colors; i++)
2244 if ((channel & RedChannel) != 0)
2245 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2246 if ((channel & GreenChannel) != 0)
2247 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2248 if ((channel & BlueChannel) != 0)
2249 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2250 if ((channel & OpacityChannel) != 0)
2251 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2258 exception=(&image->exception);
2259 image_view=AcquireCacheView(image);
2260 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2261 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2263 for (y=0; y < (ssize_t) image->rows; y++)
2265 register IndexPacket
2268 register PixelPacket
2274 if (status == MagickFalse)
2276 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2277 if (q == (PixelPacket *) NULL)
2282 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2283 for (x=0; x < (ssize_t) image->columns; x++)
2285 if ((channel & RedChannel) != 0)
2286 q->red=PosterizePixel(q->red);
2287 if ((channel & GreenChannel) != 0)
2288 q->green=PosterizePixel(q->green);
2289 if ((channel & BlueChannel) != 0)
2290 q->blue=PosterizePixel(q->blue);
2291 if (((channel & OpacityChannel) != 0) &&
2292 (image->matte == MagickTrue))
2293 q->opacity=PosterizePixel(q->opacity);
2294 if (((channel & IndexChannel) != 0) &&
2295 (image->colorspace == CMYKColorspace))
2296 indexes[x]=PosterizePixel(indexes[x]);
2299 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2301 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2306 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2307 #pragma omp critical (MagickCore_PosterizeImageChannel)
2309 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2311 if (proceed == MagickFalse)
2315 image_view=DestroyCacheView(image_view);
2316 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2317 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2318 levels,MaxColormapSize+1);
2319 quantize_info->dither=dither;
2320 status=QuantizeImage(quantize_info,image);
2321 quantize_info=DestroyQuantizeInfo(quantize_info);
2326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2330 + P r u n e C h i l d %
2334 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2336 % PruneChild() deletes the given node and merges its statistics into its
2339 % The format of the PruneSubtree method is:
2341 % PruneChild(const Image *image,CubeInfo *cube_info,
2342 % const NodeInfo *node_info)
2344 % A description of each parameter follows.
2346 % o image: the image.
2348 % o cube_info: A pointer to the Cube structure.
2350 % o node_info: pointer to node in color cube tree that is to be pruned.
2353 static void PruneChild(const Image *image,CubeInfo *cube_info,
2354 const NodeInfo *node_info)
2366 Traverse any children.
2368 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2369 for (i=0; i < (ssize_t) number_children; i++)
2370 if (node_info->child[i] != (NodeInfo *) NULL)
2371 PruneChild(image,cube_info,node_info->child[i]);
2373 Merge color statistics into parent.
2375 parent=node_info->parent;
2376 parent->number_unique+=node_info->number_unique;
2377 parent->total_color.red+=node_info->total_color.red;
2378 parent->total_color.green+=node_info->total_color.green;
2379 parent->total_color.blue+=node_info->total_color.blue;
2380 parent->total_color.opacity+=node_info->total_color.opacity;
2381 parent->child[node_info->id]=(NodeInfo *) NULL;
2386 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2390 + P r u n e L e v e l %
2394 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2396 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2397 % their color statistics into their parent node.
2399 % The format of the PruneLevel method is:
2401 % PruneLevel(const Image *image,CubeInfo *cube_info,
2402 % const NodeInfo *node_info)
2404 % A description of each parameter follows.
2406 % o image: the image.
2408 % o cube_info: A pointer to the Cube structure.
2410 % o node_info: pointer to node in color cube tree that is to be pruned.
2413 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2414 const NodeInfo *node_info)
2423 Traverse any children.
2425 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2426 for (i=0; i < (ssize_t) number_children; i++)
2427 if (node_info->child[i] != (NodeInfo *) NULL)
2428 PruneLevel(image,cube_info,node_info->child[i]);
2429 if (node_info->level == cube_info->depth)
2430 PruneChild(image,cube_info,node_info);
2434 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2438 + P r u n e T o C u b e D e p t h %
2442 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2444 % PruneToCubeDepth() deletes any nodes at a depth greater than
2445 % cube_info->depth while merging their color statistics into their parent
2448 % The format of the PruneToCubeDepth method is:
2450 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2451 % const NodeInfo *node_info)
2453 % A description of each parameter follows.
2455 % o cube_info: A pointer to the Cube structure.
2457 % o node_info: pointer to node in color cube tree that is to be pruned.
2460 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2461 const NodeInfo *node_info)
2470 Traverse any children.
2472 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2473 for (i=0; i < (ssize_t) number_children; i++)
2474 if (node_info->child[i] != (NodeInfo *) NULL)
2475 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2476 if (node_info->level > cube_info->depth)
2477 PruneChild(image,cube_info,node_info);
2481 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2485 % Q u a n t i z e I m a g e %
2489 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2491 % QuantizeImage() analyzes the colors within a reference image and chooses a
2492 % fixed number of colors to represent the image. The goal of the algorithm
2493 % is to minimize the color difference between the input and output image while
2494 % minimizing the processing time.
2496 % The format of the QuantizeImage method is:
2498 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2501 % A description of each parameter follows:
2503 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2505 % o image: the image.
2508 static MagickBooleanType DirectToColormapImage(Image *image,
2509 ExceptionInfo *exception)
2527 number_colors=(size_t) (image->columns*image->rows);
2528 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2529 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2532 image_view=AcquireCacheView(image);
2533 for (y=0; y < (ssize_t) image->rows; y++)
2538 register IndexPacket
2541 register PixelPacket
2547 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2548 if (q == (const PixelPacket *) NULL)
2550 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2551 for (x=0; x < (ssize_t) image->columns; x++)
2553 indexes[x]=(IndexPacket) i;
2554 image->colormap[i++]=(*q++);
2556 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2558 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2560 if (proceed == MagickFalse)
2563 image_view=DestroyCacheView(image_view);
2567 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2580 assert(quantize_info != (const QuantizeInfo *) NULL);
2581 assert(quantize_info->signature == MagickSignature);
2582 assert(image != (Image *) NULL);
2583 assert(image->signature == MagickSignature);
2584 if (image->debug != MagickFalse)
2585 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2586 maximum_colors=quantize_info->number_colors;
2587 if (maximum_colors == 0)
2588 maximum_colors=MaxColormapSize;
2589 if (maximum_colors > MaxColormapSize)
2590 maximum_colors=MaxColormapSize;
2591 if ((image->columns*image->rows) <= maximum_colors)
2592 return(DirectToColormapImage(image,&image->exception));
2593 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2594 (image->matte == MagickFalse))
2595 (void) SetGrayscaleImage(image);
2596 if ((image->storage_class == PseudoClass) &&
2597 (image->colors <= maximum_colors))
2599 depth=quantize_info->tree_depth;
2606 Depth of color tree is: Log4(colormap size)+2.
2608 colors=maximum_colors;
2609 for (depth=1; colors != 0; depth++)
2611 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2613 if ((image->matte != MagickFalse) && (depth > 5))
2617 Initialize color cube.
2619 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2620 if (cube_info == (CubeInfo *) NULL)
2621 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2623 status=ClassifyImageColors(cube_info,image,&image->exception);
2624 if (status != MagickFalse)
2627 Reduce the number of colors in the image.
2629 ReduceImageColors(image,cube_info);
2630 status=AssignImageColors(image,cube_info);
2632 DestroyCubeInfo(cube_info);
2637 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2641 % Q u a n t i z e I m a g e s %
2645 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2647 % QuantizeImages() analyzes the colors within a set of reference images and
2648 % chooses a fixed number of colors to represent the set. The goal of the
2649 % algorithm is to minimize the color difference between the input and output
2650 % images while minimizing the processing time.
2652 % The format of the QuantizeImages method is:
2654 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2657 % A description of each parameter follows:
2659 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2661 % o images: Specifies a pointer to a list of Image structures.
2664 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2677 MagickProgressMonitor
2688 assert(quantize_info != (const QuantizeInfo *) NULL);
2689 assert(quantize_info->signature == MagickSignature);
2690 assert(images != (Image *) NULL);
2691 assert(images->signature == MagickSignature);
2692 if (images->debug != MagickFalse)
2693 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2694 if (GetNextImageInList(images) == (Image *) NULL)
2697 Handle a single image with QuantizeImage.
2699 status=QuantizeImage(quantize_info,images);
2703 maximum_colors=quantize_info->number_colors;
2704 if (maximum_colors == 0)
2705 maximum_colors=MaxColormapSize;
2706 if (maximum_colors > MaxColormapSize)
2707 maximum_colors=MaxColormapSize;
2708 depth=quantize_info->tree_depth;
2715 Depth of color tree is: Log4(colormap size)+2.
2717 colors=maximum_colors;
2718 for (depth=1; colors != 0; depth++)
2720 if (quantize_info->dither != MagickFalse)
2724 Initialize color cube.
2726 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2727 if (cube_info == (CubeInfo *) NULL)
2729 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2730 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2731 return(MagickFalse);
2733 number_images=GetImageListLength(images);
2735 for (i=0; image != (Image *) NULL; i++)
2737 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2738 image->client_data);
2739 status=ClassifyImageColors(cube_info,image,&image->exception);
2740 if (status == MagickFalse)
2742 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2743 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2745 if (proceed == MagickFalse)
2747 image=GetNextImageInList(image);
2749 if (status != MagickFalse)
2752 Reduce the number of colors in an image sequence.
2754 ReduceImageColors(images,cube_info);
2756 for (i=0; image != (Image *) NULL; i++)
2758 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2759 NULL,image->client_data);
2760 status=AssignImageColors(image,cube_info);
2761 if (status == MagickFalse)
2763 (void) SetImageProgressMonitor(image,progress_monitor,
2764 image->client_data);
2765 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2767 if (proceed == MagickFalse)
2769 image=GetNextImageInList(image);
2772 DestroyCubeInfo(cube_info);
2777 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2785 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2787 % Reduce() traverses the color cube tree and prunes any node whose
2788 % quantization error falls below a particular threshold.
2790 % The format of the Reduce method is:
2792 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2794 % A description of each parameter follows.
2796 % o image: the image.
2798 % o cube_info: A pointer to the Cube structure.
2800 % o node_info: pointer to node in color cube tree that is to be pruned.
2803 static void Reduce(const Image *image,CubeInfo *cube_info,
2804 const NodeInfo *node_info)
2813 Traverse any children.
2815 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2816 for (i=0; i < (ssize_t) number_children; i++)
2817 if (node_info->child[i] != (NodeInfo *) NULL)
2818 Reduce(image,cube_info,node_info->child[i]);
2819 if (node_info->quantize_error <= cube_info->pruning_threshold)
2820 PruneChild(image,cube_info,node_info);
2824 Find minimum pruning threshold.
2826 if (node_info->number_unique > 0)
2827 cube_info->colors++;
2828 if (node_info->quantize_error < cube_info->next_threshold)
2829 cube_info->next_threshold=node_info->quantize_error;
2834 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2838 + R e d u c e I m a g e C o l o r s %
2842 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2844 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2845 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2846 % in the output image. On any given iteration over the tree, it selects
2847 % those nodes whose E value is minimal for pruning and merges their
2848 % color statistics upward. It uses a pruning threshold, Ep, to govern
2849 % node selection as follows:
2852 % while number of nodes with (n2 > 0) > required maximum number of colors
2853 % prune all nodes such that E <= Ep
2854 % Set Ep to minimum E in remaining nodes
2856 % This has the effect of minimizing any quantization error when merging
2857 % two nodes together.
2859 % When a node to be pruned has offspring, the pruning procedure invokes
2860 % itself recursively in order to prune the tree from the leaves upward.
2861 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2862 % corresponding data in that node's parent. This retains the pruned
2863 % node's color characteristics for later averaging.
2865 % For each node, n2 pixels exist for which that node represents the
2866 % smallest volume in RGB space containing those pixel's colors. When n2
2867 % > 0 the node will uniquely define a color in the output image. At the
2868 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2869 % the tree which represent colors present in the input image.
2871 % The other pixel count, n1, indicates the total number of colors
2872 % within the cubic volume which the node represents. This includes n1 -
2873 % n2 pixels whose colors should be defined by nodes at a lower level in
2876 % The format of the ReduceImageColors method is:
2878 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2880 % A description of each parameter follows.
2882 % o image: the image.
2884 % o cube_info: A pointer to the Cube structure.
2887 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2889 #define ReduceImageTag "Reduce/Image"
2900 cube_info->next_threshold=0.0;
2901 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2903 cube_info->pruning_threshold=cube_info->next_threshold;
2904 cube_info->next_threshold=cube_info->root->quantize_error-1;
2905 cube_info->colors=0;
2906 Reduce(image,cube_info,cube_info->root);
2907 offset=(MagickOffsetType) span-cube_info->colors;
2908 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2909 cube_info->maximum_colors+1);
2910 if (proceed == MagickFalse)
2916 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2920 % R e m a p I m a g e %
2924 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2926 % RemapImage() replaces the colors of an image with the closest color from
2927 % a reference image.
2929 % The format of the RemapImage method is:
2931 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2932 % Image *image,const Image *remap_image)
2934 % A description of each parameter follows:
2936 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2938 % o image: the image.
2940 % o remap_image: the reference image.
2943 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2944 Image *image,const Image *remap_image)
2953 Initialize color cube.
2955 assert(image != (Image *) NULL);
2956 assert(image->signature == MagickSignature);
2957 if (image->debug != MagickFalse)
2958 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2959 assert(remap_image != (Image *) NULL);
2960 assert(remap_image->signature == MagickSignature);
2961 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2962 quantize_info->number_colors);
2963 if (cube_info == (CubeInfo *) NULL)
2964 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2966 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2967 if (status != MagickFalse)
2970 Classify image colors from the reference image.
2972 cube_info->quantize_info->number_colors=cube_info->colors;
2973 status=AssignImageColors(image,cube_info);
2975 DestroyCubeInfo(cube_info);
2980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2984 % R e m a p I m a g e s %
2988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2990 % RemapImages() replaces the colors of a sequence of images with the
2991 % closest color from a reference image.
2993 % The format of the RemapImage method is:
2995 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2996 % Image *images,Image *remap_image)
2998 % A description of each parameter follows:
3000 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3002 % o images: the image sequence.
3004 % o remap_image: the reference image.
3007 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3008 Image *images,const Image *remap_image)
3019 assert(images != (Image *) NULL);
3020 assert(images->signature == MagickSignature);
3021 if (images->debug != MagickFalse)
3022 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3024 if (remap_image == (Image *) NULL)
3027 Create a global colormap for an image sequence.
3029 status=QuantizeImages(quantize_info,images);
3033 Classify image colors from the reference image.
3035 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3036 quantize_info->number_colors);
3037 if (cube_info == (CubeInfo *) NULL)
3038 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3040 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3041 if (status != MagickFalse)
3044 Classify image colors from the reference image.
3046 cube_info->quantize_info->number_colors=cube_info->colors;
3048 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3050 status=AssignImageColors(image,cube_info);
3051 if (status == MagickFalse)
3055 DestroyCubeInfo(cube_info);
3060 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3064 % S e t G r a y s c a l e I m a g e %
3068 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3070 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3072 % The format of the SetGrayscaleImage method is:
3074 % MagickBooleanType SetGrayscaleImage(Image *image)
3076 % A description of each parameter follows:
3078 % o image: The image.
3082 #if defined(__cplusplus) || defined(c_plusplus)
3086 static int IntensityCompare(const void *x,const void *y)
3095 color_1=(PixelPacket *) x;
3096 color_2=(PixelPacket *) y;
3097 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3098 PixelIntensityToQuantum(color_2);
3099 return((int) intensity);
3102 #if defined(__cplusplus) || defined(c_plusplus)
3106 static MagickBooleanType SetGrayscaleImage(Image *image)
3130 assert(image != (Image *) NULL);
3131 assert(image->signature == MagickSignature);
3132 if (image->type != GrayscaleType)
3133 (void) TransformImageColorspace(image,GRAYColorspace);
3134 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3135 sizeof(*colormap_index));
3136 if (colormap_index == (ssize_t *) NULL)
3137 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3139 if (image->storage_class != PseudoClass)
3144 for (i=0; i <= (ssize_t) MaxMap; i++)
3145 colormap_index[i]=(-1);
3146 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3147 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3151 exception=(&image->exception);
3152 image_view=AcquireCacheView(image);
3153 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3154 #pragma omp parallel for schedule(dynamic,4) shared(status)
3156 for (y=0; y < (ssize_t) image->rows; y++)
3158 register IndexPacket
3164 register const PixelPacket
3167 if (status == MagickFalse)
3169 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3171 if (q == (PixelPacket *) NULL)
3176 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3177 for (x=0; x < (ssize_t) image->columns; x++)
3182 intensity=ScaleQuantumToMap(q->red);
3183 if (colormap_index[intensity] < 0)
3185 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3186 #pragma omp critical (MagickCore_SetGrayscaleImage)
3188 if (colormap_index[intensity] < 0)
3190 colormap_index[intensity]=(ssize_t) image->colors;
3191 image->colormap[image->colors]=(*q);
3195 indexes[x]=(IndexPacket) colormap_index[intensity];
3198 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3201 image_view=DestroyCacheView(image_view);
3203 for (i=0; i < (ssize_t) image->colors; i++)
3204 image->colormap[i].opacity=(unsigned short) i;
3205 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3207 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3209 if (colormap == (PixelPacket *) NULL)
3210 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3213 colormap[j]=image->colormap[0];
3214 for (i=0; i < (ssize_t) image->colors; i++)
3216 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3219 colormap[j]=image->colormap[i];
3221 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3223 image->colors=(size_t) (j+1);
3224 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3225 image->colormap=colormap;
3227 exception=(&image->exception);
3228 image_view=AcquireCacheView(image);
3229 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3230 #pragma omp parallel for schedule(dynamic,4) shared(status)
3232 for (y=0; y < (ssize_t) image->rows; y++)
3234 register IndexPacket
3240 register const PixelPacket
3243 if (status == MagickFalse)
3245 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3246 if (q == (PixelPacket *) NULL)
3251 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3252 for (x=0; x < (ssize_t) image->columns; x++)
3253 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3254 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3257 image_view=DestroyCacheView(image_view);
3258 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3259 image->type=GrayscaleType;
3260 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3261 image->type=BilevelType;