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"
495 register const NodeInfo
511 Allocate image colormap.
513 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
514 (cube_info->quantize_info->colorspace != CMYKColorspace))
515 (void) TransformImageColorspace((Image *) image,
516 cube_info->quantize_info->colorspace);
518 if ((image->colorspace != GRAYColorspace) &&
519 (image->colorspace != RGBColorspace) &&
520 (image->colorspace != CMYColorspace))
521 (void) TransformImageColorspace((Image *) image,RGBColorspace);
522 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
523 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
526 cube_info->transparent_pixels=0;
527 cube_info->transparent_index=(-1);
528 (void) DefineImageColormap(image,cube_info,cube_info->root);
530 Create a reduced color image.
532 if ((cube_info->quantize_info->dither != MagickFalse) &&
533 (cube_info->quantize_info->dither_method != NoDitherMethod))
534 (void) DitherImage(image,cube_info);
543 exception=(&image->exception);
544 image_view=AcquireCacheView(image);
545 for (y=0; y < (ssize_t) image->rows; y++)
553 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
555 if (q == (PixelPacket *) NULL)
557 indexes=GetCacheViewAuthenticIndexQueue(image_view);
558 for (x=0; x < (ssize_t) image->columns; x+=count)
561 Identify the deepest node containing the pixel's color.
563 for (count=1; (x+count) < (ssize_t) image->columns; count++)
564 if (IsSameColor(image,q,q+count) == MagickFalse)
566 AssociateAlphaPixel(cube_info,q,&pixel);
567 node_info=cube_info->root;
568 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
570 id=ColorToNodeId(cube_info,&pixel,index);
571 if (node_info->child[id] == (NodeInfo *) NULL)
573 node_info=node_info->child[id];
575 node_info=node_info->parent;
577 Find closest color among siblings and their children.
579 cube_info->target=pixel;
580 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
581 (QuantumRange+1.0)+1.0);
582 ClosestColor(image,cube_info,node_info->parent);
583 index=cube_info->color_number;
584 for (i=0; i < (ssize_t) count; i++)
586 if (image->storage_class == PseudoClass)
587 indexes[x+i]=(IndexPacket) index;
588 if (cube_info->quantize_info->measure_error == MagickFalse)
590 q->red=image->colormap[index].red;
591 q->green=image->colormap[index].green;
592 q->blue=image->colormap[index].blue;
593 if (cube_info->associate_alpha != MagickFalse)
594 q->opacity=image->colormap[index].opacity;
599 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
601 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
603 if (proceed == MagickFalse)
606 image_view=DestroyCacheView(image_view);
608 if (cube_info->quantize_info->measure_error != MagickFalse)
609 (void) GetImageQuantizeError(image);
610 if ((cube_info->quantize_info->number_colors == 2) &&
611 (cube_info->quantize_info->colorspace == GRAYColorspace))
623 for (i=0; i < (ssize_t) image->colors; i++)
625 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
626 QuantumRange/2.0) ? 0 : QuantumRange);
633 (void) SyncImage(image);
634 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
635 (cube_info->quantize_info->colorspace != CMYKColorspace))
636 (void) TransformImageColorspace((Image *) image,RGBColorspace);
641 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
645 + C l a s s i f y I m a g e C o l o r s %
649 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
651 % ClassifyImageColors() begins by initializing a color description tree
652 % of sufficient depth to represent each possible input color in a leaf.
653 % However, it is impractical to generate a fully-formed color
654 % description tree in the storage_class phase for realistic values of
655 % Cmax. If colors components in the input image are quantized to k-bit
656 % precision, so that Cmax= 2k-1, the tree would need k levels below the
657 % root node to allow representing each possible input color in a leaf.
658 % This becomes prohibitive because the tree's total number of nodes is
661 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
662 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
663 % Initializes data structures for nodes only as they are needed; (2)
664 % Chooses a maximum depth for the tree as a function of the desired
665 % number of colors in the output image (currently log2(colormap size)).
667 % For each pixel in the input image, storage_class scans downward from
668 % the root of the color description tree. At each level of the tree it
669 % identifies the single node which represents a cube in RGB space
670 % containing It updates the following data for each such node:
672 % n1 : Number of pixels whose color is contained in the RGB cube
673 % which this node represents;
675 % n2 : Number of pixels whose color is not represented in a node at
676 % lower depth in the tree; initially, n2 = 0 for all nodes except
677 % leaves of the tree.
679 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
680 % all pixels not classified at a lower depth. The combination of
681 % these sums and n2 will ultimately characterize the mean color of a
682 % set of pixels represented by this node.
684 % E: the distance squared in RGB space between each pixel contained
685 % within a node and the nodes' center. This represents the quantization
688 % The format of the ClassifyImageColors() method is:
690 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
691 % const Image *image,ExceptionInfo *exception)
693 % A description of each parameter follows.
695 % o cube_info: A pointer to the Cube structure.
697 % o image: the image.
701 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
706 associate_alpha=image->matte;
707 if (cube_info->quantize_info->colorspace == TransparentColorspace)
708 associate_alpha=MagickFalse;
709 if ((cube_info->quantize_info->number_colors == 2) &&
710 (cube_info->quantize_info->colorspace == GRAYColorspace))
711 associate_alpha=MagickFalse;
712 cube_info->associate_alpha=associate_alpha;
715 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
716 const Image *image,ExceptionInfo *exception)
718 #define ClassifyImageTag "Classify/Image"
748 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
750 SetAssociatedAlpha(image,cube_info);
751 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
752 (cube_info->quantize_info->colorspace != CMYKColorspace))
753 (void) TransformImageColorspace((Image *) image,
754 cube_info->quantize_info->colorspace);
756 if ((image->colorspace != GRAYColorspace) &&
757 (image->colorspace != CMYColorspace) &&
758 (image->colorspace != RGBColorspace))
759 (void) TransformImageColorspace((Image *) image,RGBColorspace);
760 midpoint.red=(MagickRealType) QuantumRange/2.0;
761 midpoint.green=(MagickRealType) QuantumRange/2.0;
762 midpoint.blue=(MagickRealType) QuantumRange/2.0;
763 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
765 image_view=AcquireCacheView(image);
766 for (y=0; y < (ssize_t) image->rows; y++)
768 register const PixelPacket
774 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
775 if (p == (const PixelPacket *) NULL)
777 if (cube_info->nodes > MaxNodes)
780 Prune one level if the color tree is too large.
782 PruneLevel(image,cube_info,cube_info->root);
785 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
788 Start at the root and descend the color cube tree.
790 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
791 if (IsSameColor(image,p,p+count) == MagickFalse)
793 AssociateAlphaPixel(cube_info,p,&pixel);
794 index=MaxTreeDepth-1;
795 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
797 node_info=cube_info->root;
798 for (level=1; level <= MaxTreeDepth; level++)
801 id=ColorToNodeId(cube_info,&pixel,index);
802 mid.red+=(id & 1) != 0 ? bisect : -bisect;
803 mid.green+=(id & 2) != 0 ? bisect : -bisect;
804 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
805 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
806 if (node_info->child[id] == (NodeInfo *) NULL)
809 Set colors of new node to contain pixel.
811 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
812 if (node_info->child[id] == (NodeInfo *) NULL)
813 (void) ThrowMagickException(exception,GetMagickModule(),
814 ResourceLimitError,"MemoryAllocationFailed","`%s'",
816 if (level == MaxTreeDepth)
820 Approximate the quantization error represented by this node.
822 node_info=node_info->child[id];
823 error.red=QuantumScale*(pixel.red-mid.red);
824 error.green=QuantumScale*(pixel.green-mid.green);
825 error.blue=QuantumScale*(pixel.blue-mid.blue);
826 if (cube_info->associate_alpha != MagickFalse)
827 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
828 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
829 count*error.green*error.green+count*error.blue*error.blue+
830 count*error.opacity*error.opacity));
831 cube_info->root->quantize_error+=node_info->quantize_error;
835 Sum RGB for this leaf for later derivation of the mean cube color.
837 node_info->number_unique+=count;
838 node_info->total_color.red+=count*QuantumScale*pixel.red;
839 node_info->total_color.green+=count*QuantumScale*pixel.green;
840 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
841 if (cube_info->associate_alpha != MagickFalse)
842 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
845 if (cube_info->colors > cube_info->maximum_colors)
847 PruneToCubeDepth(image,cube_info,cube_info->root);
850 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
852 if (proceed == MagickFalse)
855 for (y++; y < (ssize_t) image->rows; y++)
857 register const PixelPacket
863 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
864 if (p == (const PixelPacket *) NULL)
866 if (cube_info->nodes > MaxNodes)
869 Prune one level if the color tree is too large.
871 PruneLevel(image,cube_info,cube_info->root);
874 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
877 Start at the root and descend the color cube tree.
879 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
880 if (IsSameColor(image,p,p+count) == MagickFalse)
882 AssociateAlphaPixel(cube_info,p,&pixel);
883 index=MaxTreeDepth-1;
884 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
886 node_info=cube_info->root;
887 for (level=1; level <= cube_info->depth; level++)
890 id=ColorToNodeId(cube_info,&pixel,index);
891 mid.red+=(id & 1) != 0 ? bisect : -bisect;
892 mid.green+=(id & 2) != 0 ? bisect : -bisect;
893 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
894 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
895 if (node_info->child[id] == (NodeInfo *) NULL)
898 Set colors of new node to contain pixel.
900 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
901 if (node_info->child[id] == (NodeInfo *) NULL)
902 (void) ThrowMagickException(exception,GetMagickModule(),
903 ResourceLimitError,"MemoryAllocationFailed","%s",
905 if (level == cube_info->depth)
909 Approximate the quantization error represented by this node.
911 node_info=node_info->child[id];
912 error.red=QuantumScale*(pixel.red-mid.red);
913 error.green=QuantumScale*(pixel.green-mid.green);
914 error.blue=QuantumScale*(pixel.blue-mid.blue);
915 if (cube_info->associate_alpha != MagickFalse)
916 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
917 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
918 count*error.green*error.green+count*error.blue*error.blue+
919 count*error.opacity*error.opacity));
920 cube_info->root->quantize_error+=node_info->quantize_error;
924 Sum RGB for this leaf for later derivation of the mean cube color.
926 node_info->number_unique+=count;
927 node_info->total_color.red+=count*QuantumScale*pixel.red;
928 node_info->total_color.green+=count*QuantumScale*pixel.green;
929 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
930 if (cube_info->associate_alpha != MagickFalse)
931 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
934 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
936 if (proceed == MagickFalse)
939 image_view=DestroyCacheView(image_view);
940 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
941 (cube_info->quantize_info->colorspace != CMYKColorspace))
942 (void) TransformImageColorspace((Image *) image,RGBColorspace);
947 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
951 % C l o n e Q u a n t i z e I n f o %
955 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
957 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
958 % or if quantize info is NULL, a new one.
960 % The format of the CloneQuantizeInfo method is:
962 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
964 % A description of each parameter follows:
966 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
967 % quantize info, or if image info is NULL a new one.
969 % o quantize_info: a structure of type info.
972 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
977 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
978 if (clone_info == (QuantizeInfo *) NULL)
979 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
980 GetQuantizeInfo(clone_info);
981 if (quantize_info == (QuantizeInfo *) NULL)
983 clone_info->number_colors=quantize_info->number_colors;
984 clone_info->tree_depth=quantize_info->tree_depth;
985 clone_info->dither=quantize_info->dither;
986 clone_info->dither_method=quantize_info->dither_method;
987 clone_info->colorspace=quantize_info->colorspace;
988 clone_info->measure_error=quantize_info->measure_error;
993 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
997 + C l o s e s t C o l o r %
1001 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1003 % ClosestColor() traverses the color cube tree at a particular node and
1004 % determines which colormap entry best represents the input color.
1006 % The format of the ClosestColor method is:
1008 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1009 % const NodeInfo *node_info)
1011 % A description of each parameter follows.
1013 % o image: the image.
1015 % o cube_info: A pointer to the Cube structure.
1017 % o node_info: the address of a structure of type NodeInfo which points to a
1018 % node in the color cube tree that is to be pruned.
1021 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1022 const NodeInfo *node_info)
1031 Traverse any children.
1033 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1034 for (i=0; i < (ssize_t) number_children; i++)
1035 if (node_info->child[i] != (NodeInfo *) NULL)
1036 ClosestColor(image,cube_info,node_info->child[i]);
1037 if (node_info->number_unique != 0)
1042 register MagickRealType
1047 register PixelPacket
1050 register RealPixelPacket
1054 Determine if this color is "closest".
1056 p=image->colormap+node_info->color_number;
1057 q=(&cube_info->target);
1060 if (cube_info->associate_alpha != MagickFalse)
1062 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1063 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1065 pixel=alpha*p->red-beta*q->red;
1066 distance=pixel*pixel;
1067 if (distance <= cube_info->distance)
1069 pixel=alpha*p->green-beta*q->green;
1070 distance+=pixel*pixel;
1071 if (distance <= cube_info->distance)
1073 pixel=alpha*p->blue-beta*q->blue;
1074 distance+=pixel*pixel;
1075 if (distance <= cube_info->distance)
1078 distance+=pixel*pixel;
1079 if (distance <= cube_info->distance)
1081 cube_info->distance=distance;
1082 cube_info->color_number=node_info->color_number;
1091 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1095 % C o m p r e s s I m a g e C o l o r m a p %
1099 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1101 % CompressImageColormap() compresses an image colormap by removing any
1102 % duplicate or unused color entries.
1104 % The format of the CompressImageColormap method is:
1106 % MagickBooleanType CompressImageColormap(Image *image)
1108 % A description of each parameter follows:
1110 % o image: the image.
1113 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1118 assert(image != (Image *) NULL);
1119 assert(image->signature == MagickSignature);
1120 if (image->debug != MagickFalse)
1121 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1122 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1123 return(MagickFalse);
1124 GetQuantizeInfo(&quantize_info);
1125 quantize_info.number_colors=image->colors;
1126 quantize_info.tree_depth=MaxTreeDepth;
1127 return(QuantizeImage(&quantize_info,image));
1131 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1135 + D e f i n e I m a g e C o l o r m a p %
1139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1141 % DefineImageColormap() traverses the color cube tree and notes each colormap
1142 % entry. A colormap entry is any node in the color cube tree where the
1143 % of unique colors is not zero. DefineImageColormap() returns the number of
1144 % colors in the image colormap.
1146 % The format of the DefineImageColormap method is:
1148 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1149 % NodeInfo *node_info)
1151 % A description of each parameter follows.
1153 % o image: the image.
1155 % o cube_info: A pointer to the Cube structure.
1157 % o node_info: the address of a structure of type NodeInfo which points to a
1158 % node in the color cube tree that is to be pruned.
1161 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1162 NodeInfo *node_info)
1171 Traverse any children.
1173 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1174 for (i=0; i < (ssize_t) number_children; i++)
1175 if (node_info->child[i] != (NodeInfo *) NULL)
1176 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1177 if (node_info->number_unique != 0)
1179 register MagickRealType
1182 register PixelPacket
1186 Colormap entry is defined by the mean color in this cube.
1188 q=image->colormap+image->colors;
1189 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1190 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1191 if (cube_info->associate_alpha == MagickFalse)
1193 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1194 node_info->total_color.red));
1195 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1196 node_info->total_color.green));
1197 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1198 node_info->total_color.blue));
1199 SetOpacityPixelComponent(q,OpaqueOpacity);
1206 opacity=(MagickRealType) (alpha*QuantumRange*
1207 node_info->total_color.opacity);
1208 q->opacity=ClampToQuantum(opacity);
1209 if (q->opacity == OpaqueOpacity)
1211 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1212 node_info->total_color.red));
1213 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1214 node_info->total_color.green));
1215 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1216 node_info->total_color.blue));
1223 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1224 (MagickRealType) q->opacity));
1225 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1226 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1227 node_info->total_color.red));
1228 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1229 QuantumRange*node_info->total_color.green));
1230 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1231 node_info->total_color.blue));
1232 if (node_info->number_unique > cube_info->transparent_pixels)
1234 cube_info->transparent_pixels=node_info->number_unique;
1235 cube_info->transparent_index=(ssize_t) image->colors;
1239 node_info->color_number=image->colors++;
1241 return(image->colors);
1245 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1249 + D e s t r o y C u b e I n f o %
1253 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1255 % DestroyCubeInfo() deallocates memory associated with an image.
1257 % The format of the DestroyCubeInfo method is:
1259 % DestroyCubeInfo(CubeInfo *cube_info)
1261 % A description of each parameter follows:
1263 % o cube_info: the address of a structure of type CubeInfo.
1266 static void DestroyCubeInfo(CubeInfo *cube_info)
1272 Release color cube tree storage.
1276 nodes=cube_info->node_queue->next;
1277 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1278 cube_info->node_queue->nodes);
1279 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1280 cube_info->node_queue);
1281 cube_info->node_queue=nodes;
1282 } while (cube_info->node_queue != (Nodes *) NULL);
1283 if (cube_info->cache != (ssize_t *) NULL)
1284 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1285 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1286 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1290 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1294 % D e s t r o y Q u a n t i z e I n f o %
1298 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1300 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1303 % The format of the DestroyQuantizeInfo method is:
1305 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1307 % A description of each parameter follows:
1309 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1312 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1314 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1315 assert(quantize_info != (QuantizeInfo *) NULL);
1316 assert(quantize_info->signature == MagickSignature);
1317 quantize_info->signature=(~MagickSignature);
1318 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1319 return(quantize_info);
1323 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1327 + D i t h e r I m a g e %
1331 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1333 % DitherImage() distributes the difference between an original image and
1334 % the corresponding color reduced algorithm to neighboring pixels using
1335 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1336 % MagickTrue if the image is dithered otherwise MagickFalse.
1338 % The format of the DitherImage method is:
1340 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1342 % A description of each parameter follows.
1344 % o image: the image.
1346 % o cube_info: A pointer to the Cube structure.
1350 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1351 const RealPixelPacket *pixel)
1353 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1354 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1355 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1356 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1362 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1363 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1364 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1365 if (cube_info->associate_alpha != MagickFalse)
1366 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1371 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1373 #define DitherImageTag "Dither/Image"
1403 Distribute quantization error using Floyd-Steinberg.
1405 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1406 2*sizeof(*scanlines));
1407 if (scanlines == (RealPixelPacket *) NULL)
1408 return(MagickFalse);
1410 exception=(&image->exception);
1411 image_view=AcquireCacheView(image);
1412 for (y=0; y < (ssize_t) image->rows; y++)
1414 register IndexPacket
1417 register PixelPacket
1424 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1425 if (q == (PixelPacket *) NULL)
1426 return(MagickFalse);
1427 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1428 current=scanlines+(y & 0x01)*image->columns;
1429 previous=scanlines+((y+1) & 0x01)*image->columns;
1430 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1431 for (x=0; x < (ssize_t) image->columns; x++)
1433 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1434 AssociateAlphaPixel(cube_info,q+u,&pixel);
1437 pixel.red+=7*current[u-v].red/16;
1438 pixel.green+=7*current[u-v].green/16;
1439 pixel.blue+=7*current[u-v].blue/16;
1440 if (cube_info->associate_alpha != MagickFalse)
1441 pixel.opacity+=7*current[u-v].opacity/16;
1445 if (x < (ssize_t) (image->columns-1))
1447 pixel.red+=previous[u+v].red/16;
1448 pixel.green+=previous[u+v].green/16;
1449 pixel.blue+=previous[u+v].blue/16;
1450 if (cube_info->associate_alpha != MagickFalse)
1451 pixel.opacity+=previous[u+v].opacity/16;
1453 pixel.red+=5*previous[u].red/16;
1454 pixel.green+=5*previous[u].green/16;
1455 pixel.blue+=5*previous[u].blue/16;
1456 if (cube_info->associate_alpha != MagickFalse)
1457 pixel.opacity+=5*previous[u].opacity/16;
1460 pixel.red+=3*previous[u-v].red/16;
1461 pixel.green+=3*previous[u-v].green/16;
1462 pixel.blue+=3*previous[u-v].blue/16;
1463 if (cube_info->associate_alpha != MagickFalse)
1464 pixel.opacity+=3*previous[u-v].opacity/16;
1467 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1468 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1469 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1470 if (cube_info->associate_alpha != MagickFalse)
1471 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1472 i=CacheOffset(cube_info,&pixel);
1473 if (p->cache[i] < 0)
1482 Identify the deepest node containing the pixel's color.
1485 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1487 id=ColorToNodeId(cube_info,&pixel,index);
1488 if (node_info->child[id] == (NodeInfo *) NULL)
1490 node_info=node_info->child[id];
1492 node_info=node_info->parent;
1494 Find closest color among siblings and their children.
1497 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1499 ClosestColor(image,p,node_info->parent);
1500 p->cache[i]=(ssize_t) p->color_number;
1503 Assign pixel to closest colormap entry.
1505 index=(size_t) p->cache[i];
1506 if (image->storage_class == PseudoClass)
1507 indexes[u]=(IndexPacket) index;
1508 if (cube_info->quantize_info->measure_error == MagickFalse)
1510 (q+u)->red=image->colormap[index].red;
1511 (q+u)->green=image->colormap[index].green;
1512 (q+u)->blue=image->colormap[index].blue;
1513 if (cube_info->associate_alpha != MagickFalse)
1514 (q+u)->opacity=image->colormap[index].opacity;
1516 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1517 return(MagickFalse);
1521 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1522 current[u].red=pixel.red-color.red;
1523 current[u].green=pixel.green-color.green;
1524 current[u].blue=pixel.blue-color.blue;
1525 if (cube_info->associate_alpha != MagickFalse)
1526 current[u].opacity=pixel.opacity-color.opacity;
1527 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1528 if (proceed == MagickFalse)
1529 return(MagickFalse);
1533 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1534 image_view=DestroyCacheView(image_view);
1538 static MagickBooleanType
1539 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1541 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1542 const size_t level,const unsigned int direction)
1549 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1550 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1551 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1556 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1557 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1558 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1563 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1564 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1565 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1570 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1571 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1572 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1583 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1584 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1585 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1586 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1587 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1588 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1589 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1594 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1595 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1596 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1597 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1598 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1599 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1600 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1605 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1606 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1607 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1608 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1609 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1610 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1611 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1616 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1617 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1618 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1619 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1620 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1621 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1622 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1630 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1631 CubeInfo *cube_info,const unsigned int direction)
1633 #define DitherImageTag "Dither/Image"
1649 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1650 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1655 register IndexPacket
1658 register PixelPacket
1667 exception=(&image->exception);
1668 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1669 if (q == (PixelPacket *) NULL)
1670 return(MagickFalse);
1671 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1672 AssociateAlphaPixel(cube_info,q,&pixel);
1673 for (i=0; i < ErrorQueueLength; i++)
1675 pixel.red+=p->weights[i]*p->error[i].red;
1676 pixel.green+=p->weights[i]*p->error[i].green;
1677 pixel.blue+=p->weights[i]*p->error[i].blue;
1678 if (cube_info->associate_alpha != MagickFalse)
1679 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1681 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1682 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1683 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1684 if (cube_info->associate_alpha != MagickFalse)
1685 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1686 i=CacheOffset(cube_info,&pixel);
1687 if (p->cache[i] < 0)
1696 Identify the deepest node containing the pixel's color.
1699 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1701 id=ColorToNodeId(cube_info,&pixel,index);
1702 if (node_info->child[id] == (NodeInfo *) NULL)
1704 node_info=node_info->child[id];
1706 node_info=node_info->parent;
1708 Find closest color among siblings and their children.
1711 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1712 QuantumRange+1.0)+1.0);
1713 ClosestColor(image,p,node_info->parent);
1714 p->cache[i]=(ssize_t) p->color_number;
1717 Assign pixel to closest colormap entry.
1719 index=(size_t) (1*p->cache[i]);
1720 if (image->storage_class == PseudoClass)
1721 *indexes=(IndexPacket) index;
1722 if (cube_info->quantize_info->measure_error == MagickFalse)
1724 q->red=image->colormap[index].red;
1725 q->green=image->colormap[index].green;
1726 q->blue=image->colormap[index].blue;
1727 if (cube_info->associate_alpha != MagickFalse)
1728 q->opacity=image->colormap[index].opacity;
1730 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1731 return(MagickFalse);
1733 Propagate the error as the last entry of the error queue.
1735 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1736 sizeof(p->error[0]));
1737 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1738 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1739 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1740 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1741 if (cube_info->associate_alpha != MagickFalse)
1742 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1743 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1744 if (proceed == MagickFalse)
1745 return(MagickFalse);
1750 case WestGravity: p->x--; break;
1751 case EastGravity: p->x++; break;
1752 case NorthGravity: p->y--; break;
1753 case SouthGravity: p->y++; break;
1758 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1765 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1772 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1786 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1787 return(FloydSteinbergDither(image,cube_info));
1789 Distribute quantization error along a Hilbert curve.
1791 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1792 sizeof(*cube_info->error));
1795 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1796 for (depth=1; i != 0; depth++)
1798 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1800 cube_info->offset=0;
1801 cube_info->span=(MagickSizeType) image->columns*image->rows;
1802 image_view=AcquireCacheView(image);
1804 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1805 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1806 image_view=DestroyCacheView(image_view);
1811 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1815 + G e t C u b e I n f o %
1819 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1821 % GetCubeInfo() initialize the Cube data structure.
1823 % The format of the GetCubeInfo method is:
1825 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1826 % const size_t depth,const size_t maximum_colors)
1828 % A description of each parameter follows.
1830 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1832 % o depth: Normally, this integer value is zero or one. A zero or
1833 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1834 % A tree of this depth generally allows the best representation of the
1835 % reference image with the least amount of memory and the fastest
1836 % computational speed. In some cases, such as an image with low color
1837 % dispersion (a few number of colors), a value other than
1838 % Log4(number_colors) is required. To expand the color tree completely,
1841 % o maximum_colors: maximum colors.
1844 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1845 const size_t depth,const size_t maximum_colors)
1861 Initialize tree to describe color cube_info.
1863 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1864 if (cube_info == (CubeInfo *) NULL)
1865 return((CubeInfo *) NULL);
1866 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1867 cube_info->depth=depth;
1868 if (cube_info->depth > MaxTreeDepth)
1869 cube_info->depth=MaxTreeDepth;
1870 if (cube_info->depth < 2)
1872 cube_info->maximum_colors=maximum_colors;
1874 Initialize root node.
1876 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1877 if (cube_info->root == (NodeInfo *) NULL)
1878 return((CubeInfo *) NULL);
1879 cube_info->root->parent=cube_info->root;
1880 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1881 if (cube_info->quantize_info->dither == MagickFalse)
1884 Initialize dither resources.
1886 length=(size_t) (1UL << (4*(8-CacheShift)));
1887 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1888 sizeof(*cube_info->cache));
1889 if (cube_info->cache == (ssize_t *) NULL)
1890 return((CubeInfo *) NULL);
1892 Initialize color cache.
1894 for (i=0; i < (ssize_t) length; i++)
1895 cube_info->cache[i]=(-1);
1897 Distribute weights along a curve of exponential decay.
1900 for (i=0; i < ErrorQueueLength; i++)
1902 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1903 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1906 Normalize the weighting factors.
1909 for (i=0; i < ErrorQueueLength; i++)
1910 weight+=cube_info->weights[i];
1912 for (i=0; i < ErrorQueueLength; i++)
1914 cube_info->weights[i]/=weight;
1915 sum+=cube_info->weights[i];
1917 cube_info->weights[0]+=1.0-sum;
1922 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1926 + G e t N o d e I n f o %
1930 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1932 % GetNodeInfo() allocates memory for a new node in the color cube tree and
1933 % presets all fields to zero.
1935 % The format of the GetNodeInfo method is:
1937 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1938 % const size_t level,NodeInfo *parent)
1940 % A description of each parameter follows.
1942 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1944 % o id: Specifies the child number of the node.
1946 % o level: Specifies the level in the storage_class the node resides.
1949 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1950 const size_t level,NodeInfo *parent)
1955 if (cube_info->free_nodes == 0)
1961 Allocate a new queue of nodes.
1963 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
1964 if (nodes == (Nodes *) NULL)
1965 return((NodeInfo *) NULL);
1966 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1967 sizeof(*nodes->nodes));
1968 if (nodes->nodes == (NodeInfo *) NULL)
1969 return((NodeInfo *) NULL);
1970 nodes->next=cube_info->node_queue;
1971 cube_info->node_queue=nodes;
1972 cube_info->next_node=nodes->nodes;
1973 cube_info->free_nodes=NodesInAList;
1976 cube_info->free_nodes--;
1977 node_info=cube_info->next_node++;
1978 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1979 node_info->parent=parent;
1981 node_info->level=level;
1986 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1990 % G e t I m a g e Q u a n t i z e E r r o r %
1994 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1996 % GetImageQuantizeError() measures the difference between the original
1997 % and quantized images. This difference is the total quantization error.
1998 % The error is computed by summing over all pixels in an image the distance
1999 % squared in RGB space between each reference pixel value and its quantized
2000 % value. These values are computed:
2002 % o mean_error_per_pixel: This value is the mean error for any single
2003 % pixel in the image.
2005 % o normalized_mean_square_error: This value is the normalized mean
2006 % quantization error for any single pixel in the image. This distance
2007 % measure is normalized to a range between 0 and 1. It is independent
2008 % of the range of red, green, and blue values in the image.
2010 % o normalized_maximum_square_error: Thsi value is the normalized
2011 % maximum quantization error for any single pixel in the image. This
2012 % distance measure is normalized to a range between 0 and 1. It is
2013 % independent of the range of red, green, and blue values in your image.
2015 % The format of the GetImageQuantizeError method is:
2017 % MagickBooleanType GetImageQuantizeError(Image *image)
2019 % A description of each parameter follows.
2021 % o image: the image.
2024 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2042 mean_error_per_pixel;
2050 assert(image != (Image *) NULL);
2051 assert(image->signature == MagickSignature);
2052 if (image->debug != MagickFalse)
2053 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2054 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2055 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2056 if (image->storage_class == DirectClass)
2060 area=3.0*image->columns*image->rows;
2062 mean_error_per_pixel=0.0;
2064 exception=(&image->exception);
2065 image_view=AcquireCacheView(image);
2066 for (y=0; y < (ssize_t) image->rows; y++)
2068 register const PixelPacket
2074 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2075 if (p == (const PixelPacket *) NULL)
2077 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2078 for (x=0; x < (ssize_t) image->columns; x++)
2080 index=1UL*indexes[x];
2081 if (image->matte != MagickFalse)
2083 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2084 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2085 image->colormap[index].opacity));
2087 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2088 mean_error_per_pixel+=distance;
2089 mean_error+=distance*distance;
2090 if (distance > maximum_error)
2091 maximum_error=distance;
2092 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2093 mean_error_per_pixel+=distance;
2094 mean_error+=distance*distance;
2095 if (distance > maximum_error)
2096 maximum_error=distance;
2097 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2098 mean_error_per_pixel+=distance;
2099 mean_error+=distance*distance;
2100 if (distance > maximum_error)
2101 maximum_error=distance;
2105 image_view=DestroyCacheView(image_view);
2106 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2107 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2109 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2114 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2118 % G e t Q u a n t i z e I n f o %
2122 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2124 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2126 % The format of the GetQuantizeInfo method is:
2128 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2130 % A description of each parameter follows:
2132 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2135 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2137 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2138 assert(quantize_info != (QuantizeInfo *) NULL);
2139 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2140 quantize_info->number_colors=256;
2141 quantize_info->dither=MagickTrue;
2142 quantize_info->dither_method=RiemersmaDitherMethod;
2143 quantize_info->colorspace=UndefinedColorspace;
2144 quantize_info->measure_error=MagickFalse;
2145 quantize_info->signature=MagickSignature;
2149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2153 % P o s t e r i z e I m a g e C h a n n e l %
2157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2159 % PosterizeImage() reduces the image to a limited number of colors for a
2162 % The format of the PosterizeImage method is:
2164 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2165 % const MagickBooleanType dither)
2166 % MagickBooleanType PosterizeImageChannel(Image *image,
2167 % const ChannelType channel,const size_t levels,
2168 % const MagickBooleanType dither)
2170 % A description of each parameter follows:
2172 % o image: Specifies a pointer to an Image structure.
2174 % o levels: Number of color levels allowed in each channel. Very low values
2175 % (2, 3, or 4) have the most visible effect.
2177 % o dither: Set this integer value to something other than zero to dither
2182 static inline ssize_t MagickRound(MagickRealType x)
2185 Round the fraction to nearest integer.
2188 return((ssize_t) (x+0.5));
2189 return((ssize_t) (x-0.5));
2192 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2193 const MagickBooleanType dither)
2198 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2202 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2203 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2205 #define PosterizeImageTag "Posterize/Image"
2206 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2207 QuantumScale*pixel*(levels-1)))/(levels-1))
2230 assert(image != (Image *) NULL);
2231 assert(image->signature == MagickSignature);
2232 if (image->debug != MagickFalse)
2233 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2234 if (image->storage_class == PseudoClass)
2235 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2236 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2238 for (i=0; i < (ssize_t) image->colors; i++)
2243 if ((channel & RedChannel) != 0)
2244 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2245 if ((channel & GreenChannel) != 0)
2246 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2247 if ((channel & BlueChannel) != 0)
2248 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2249 if ((channel & OpacityChannel) != 0)
2250 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2257 exception=(&image->exception);
2258 image_view=AcquireCacheView(image);
2259 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2260 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2262 for (y=0; y < (ssize_t) image->rows; y++)
2264 register IndexPacket
2267 register PixelPacket
2273 if (status == MagickFalse)
2275 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2276 if (q == (PixelPacket *) NULL)
2281 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2282 for (x=0; x < (ssize_t) image->columns; x++)
2284 if ((channel & RedChannel) != 0)
2285 q->red=PosterizePixel(q->red);
2286 if ((channel & GreenChannel) != 0)
2287 q->green=PosterizePixel(q->green);
2288 if ((channel & BlueChannel) != 0)
2289 q->blue=PosterizePixel(q->blue);
2290 if (((channel & OpacityChannel) != 0) &&
2291 (image->matte == MagickTrue))
2292 q->opacity=PosterizePixel(q->opacity);
2293 if (((channel & IndexChannel) != 0) &&
2294 (image->colorspace == CMYKColorspace))
2295 indexes[x]=PosterizePixel(indexes[x]);
2298 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2300 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2305 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2306 #pragma omp critical (MagickCore_PosterizeImageChannel)
2308 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2310 if (proceed == MagickFalse)
2314 image_view=DestroyCacheView(image_view);
2315 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2316 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2317 levels,MaxColormapSize+1);
2318 quantize_info->dither=dither;
2319 status=QuantizeImage(quantize_info,image);
2320 quantize_info=DestroyQuantizeInfo(quantize_info);
2325 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2329 + P r u n e C h i l d %
2333 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2335 % PruneChild() deletes the given node and merges its statistics into its
2338 % The format of the PruneSubtree method is:
2340 % PruneChild(const Image *image,CubeInfo *cube_info,
2341 % const NodeInfo *node_info)
2343 % A description of each parameter follows.
2345 % o image: the image.
2347 % o cube_info: A pointer to the Cube structure.
2349 % o node_info: pointer to node in color cube tree that is to be pruned.
2352 static void PruneChild(const Image *image,CubeInfo *cube_info,
2353 const NodeInfo *node_info)
2365 Traverse any children.
2367 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2368 for (i=0; i < (ssize_t) number_children; i++)
2369 if (node_info->child[i] != (NodeInfo *) NULL)
2370 PruneChild(image,cube_info,node_info->child[i]);
2372 Merge color statistics into parent.
2374 parent=node_info->parent;
2375 parent->number_unique+=node_info->number_unique;
2376 parent->total_color.red+=node_info->total_color.red;
2377 parent->total_color.green+=node_info->total_color.green;
2378 parent->total_color.blue+=node_info->total_color.blue;
2379 parent->total_color.opacity+=node_info->total_color.opacity;
2380 parent->child[node_info->id]=(NodeInfo *) NULL;
2385 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2389 + P r u n e L e v e l %
2393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2395 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2396 % their color statistics into their parent node.
2398 % The format of the PruneLevel method is:
2400 % PruneLevel(const Image *image,CubeInfo *cube_info,
2401 % const NodeInfo *node_info)
2403 % A description of each parameter follows.
2405 % o image: the image.
2407 % o cube_info: A pointer to the Cube structure.
2409 % o node_info: pointer to node in color cube tree that is to be pruned.
2412 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2413 const NodeInfo *node_info)
2422 Traverse any children.
2424 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2425 for (i=0; i < (ssize_t) number_children; i++)
2426 if (node_info->child[i] != (NodeInfo *) NULL)
2427 PruneLevel(image,cube_info,node_info->child[i]);
2428 if (node_info->level == cube_info->depth)
2429 PruneChild(image,cube_info,node_info);
2433 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2437 + P r u n e T o C u b e D e p t h %
2441 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2443 % PruneToCubeDepth() deletes any nodes at a depth greater than
2444 % cube_info->depth while merging their color statistics into their parent
2447 % The format of the PruneToCubeDepth method is:
2449 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2450 % const NodeInfo *node_info)
2452 % A description of each parameter follows.
2454 % o cube_info: A pointer to the Cube structure.
2456 % o node_info: pointer to node in color cube tree that is to be pruned.
2459 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2460 const NodeInfo *node_info)
2469 Traverse any children.
2471 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2472 for (i=0; i < (ssize_t) number_children; i++)
2473 if (node_info->child[i] != (NodeInfo *) NULL)
2474 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2475 if (node_info->level > cube_info->depth)
2476 PruneChild(image,cube_info,node_info);
2480 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2484 % Q u a n t i z e I m a g e %
2488 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2490 % QuantizeImage() analyzes the colors within a reference image and chooses a
2491 % fixed number of colors to represent the image. The goal of the algorithm
2492 % is to minimize the color difference between the input and output image while
2493 % minimizing the processing time.
2495 % The format of the QuantizeImage method is:
2497 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2500 % A description of each parameter follows:
2502 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2504 % o image: the image.
2507 static MagickBooleanType DirectToColormapImage(Image *image,
2508 ExceptionInfo *exception)
2526 number_colors=(size_t) (image->columns*image->rows);
2527 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2528 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2531 image_view=AcquireCacheView(image);
2532 for (y=0; y < (ssize_t) image->rows; y++)
2537 register IndexPacket
2540 register PixelPacket
2546 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2547 if (q == (const PixelPacket *) NULL)
2549 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2550 for (x=0; x < (ssize_t) image->columns; x++)
2552 indexes[x]=(IndexPacket) i;
2553 image->colormap[i++]=(*q++);
2555 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2557 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2559 if (proceed == MagickFalse)
2562 image_view=DestroyCacheView(image_view);
2566 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2579 assert(quantize_info != (const QuantizeInfo *) NULL);
2580 assert(quantize_info->signature == MagickSignature);
2581 assert(image != (Image *) NULL);
2582 assert(image->signature == MagickSignature);
2583 if (image->debug != MagickFalse)
2584 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2585 maximum_colors=quantize_info->number_colors;
2586 if (maximum_colors == 0)
2587 maximum_colors=MaxColormapSize;
2588 if (maximum_colors > MaxColormapSize)
2589 maximum_colors=MaxColormapSize;
2590 if ((image->columns*image->rows) <= maximum_colors)
2591 return(DirectToColormapImage(image,&image->exception));
2592 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2593 (image->matte == MagickFalse))
2594 (void) SetGrayscaleImage(image);
2595 if ((image->storage_class == PseudoClass) &&
2596 (image->colors <= maximum_colors))
2598 depth=quantize_info->tree_depth;
2605 Depth of color tree is: Log4(colormap size)+2.
2607 colors=maximum_colors;
2608 for (depth=1; colors != 0; depth++)
2610 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2612 if ((image->matte != MagickFalse) && (depth > 5))
2616 Initialize color cube.
2618 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2619 if (cube_info == (CubeInfo *) NULL)
2620 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2622 status=ClassifyImageColors(cube_info,image,&image->exception);
2623 if (status != MagickFalse)
2626 Reduce the number of colors in the image.
2628 ReduceImageColors(image,cube_info);
2629 status=AssignImageColors(image,cube_info);
2631 DestroyCubeInfo(cube_info);
2636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2640 % Q u a n t i z e I m a g e s %
2644 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2646 % QuantizeImages() analyzes the colors within a set of reference images and
2647 % chooses a fixed number of colors to represent the set. The goal of the
2648 % algorithm is to minimize the color difference between the input and output
2649 % images while minimizing the processing time.
2651 % The format of the QuantizeImages method is:
2653 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2656 % A description of each parameter follows:
2658 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2660 % o images: Specifies a pointer to a list of Image structures.
2663 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2676 MagickProgressMonitor
2687 assert(quantize_info != (const QuantizeInfo *) NULL);
2688 assert(quantize_info->signature == MagickSignature);
2689 assert(images != (Image *) NULL);
2690 assert(images->signature == MagickSignature);
2691 if (images->debug != MagickFalse)
2692 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2693 if (GetNextImageInList(images) == (Image *) NULL)
2696 Handle a single image with QuantizeImage.
2698 status=QuantizeImage(quantize_info,images);
2702 maximum_colors=quantize_info->number_colors;
2703 if (maximum_colors == 0)
2704 maximum_colors=MaxColormapSize;
2705 if (maximum_colors > MaxColormapSize)
2706 maximum_colors=MaxColormapSize;
2707 depth=quantize_info->tree_depth;
2714 Depth of color tree is: Log4(colormap size)+2.
2716 colors=maximum_colors;
2717 for (depth=1; colors != 0; depth++)
2719 if (quantize_info->dither != MagickFalse)
2723 Initialize color cube.
2725 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2726 if (cube_info == (CubeInfo *) NULL)
2728 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2729 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2730 return(MagickFalse);
2732 number_images=GetImageListLength(images);
2734 for (i=0; image != (Image *) NULL; i++)
2736 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2737 image->client_data);
2738 status=ClassifyImageColors(cube_info,image,&image->exception);
2739 if (status == MagickFalse)
2741 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2742 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2744 if (proceed == MagickFalse)
2746 image=GetNextImageInList(image);
2748 if (status != MagickFalse)
2751 Reduce the number of colors in an image sequence.
2753 ReduceImageColors(images,cube_info);
2755 for (i=0; image != (Image *) NULL; i++)
2757 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2758 NULL,image->client_data);
2759 status=AssignImageColors(image,cube_info);
2760 if (status == MagickFalse)
2762 (void) SetImageProgressMonitor(image,progress_monitor,
2763 image->client_data);
2764 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2766 if (proceed == MagickFalse)
2768 image=GetNextImageInList(image);
2771 DestroyCubeInfo(cube_info);
2776 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2784 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2786 % Reduce() traverses the color cube tree and prunes any node whose
2787 % quantization error falls below a particular threshold.
2789 % The format of the Reduce method is:
2791 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2793 % A description of each parameter follows.
2795 % o image: the image.
2797 % o cube_info: A pointer to the Cube structure.
2799 % o node_info: pointer to node in color cube tree that is to be pruned.
2802 static void Reduce(const Image *image,CubeInfo *cube_info,
2803 const NodeInfo *node_info)
2812 Traverse any children.
2814 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2815 for (i=0; i < (ssize_t) number_children; i++)
2816 if (node_info->child[i] != (NodeInfo *) NULL)
2817 Reduce(image,cube_info,node_info->child[i]);
2818 if (node_info->quantize_error <= cube_info->pruning_threshold)
2819 PruneChild(image,cube_info,node_info);
2823 Find minimum pruning threshold.
2825 if (node_info->number_unique > 0)
2826 cube_info->colors++;
2827 if (node_info->quantize_error < cube_info->next_threshold)
2828 cube_info->next_threshold=node_info->quantize_error;
2833 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2837 + R e d u c e I m a g e C o l o r s %
2841 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2843 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2844 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2845 % in the output image. On any given iteration over the tree, it selects
2846 % those nodes whose E value is minimal for pruning and merges their
2847 % color statistics upward. It uses a pruning threshold, Ep, to govern
2848 % node selection as follows:
2851 % while number of nodes with (n2 > 0) > required maximum number of colors
2852 % prune all nodes such that E <= Ep
2853 % Set Ep to minimum E in remaining nodes
2855 % This has the effect of minimizing any quantization error when merging
2856 % two nodes together.
2858 % When a node to be pruned has offspring, the pruning procedure invokes
2859 % itself recursively in order to prune the tree from the leaves upward.
2860 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2861 % corresponding data in that node's parent. This retains the pruned
2862 % node's color characteristics for later averaging.
2864 % For each node, n2 pixels exist for which that node represents the
2865 % smallest volume in RGB space containing those pixel's colors. When n2
2866 % > 0 the node will uniquely define a color in the output image. At the
2867 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2868 % the tree which represent colors present in the input image.
2870 % The other pixel count, n1, indicates the total number of colors
2871 % within the cubic volume which the node represents. This includes n1 -
2872 % n2 pixels whose colors should be defined by nodes at a lower level in
2875 % The format of the ReduceImageColors method is:
2877 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2879 % A description of each parameter follows.
2881 % o image: the image.
2883 % o cube_info: A pointer to the Cube structure.
2886 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2888 #define ReduceImageTag "Reduce/Image"
2899 cube_info->next_threshold=0.0;
2900 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2902 cube_info->pruning_threshold=cube_info->next_threshold;
2903 cube_info->next_threshold=cube_info->root->quantize_error-1;
2904 cube_info->colors=0;
2905 Reduce(image,cube_info,cube_info->root);
2906 offset=(MagickOffsetType) span-cube_info->colors;
2907 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2908 cube_info->maximum_colors+1);
2909 if (proceed == MagickFalse)
2915 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2919 % R e m a p I m a g e %
2923 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2925 % RemapImage() replaces the colors of an image with the closest color from
2926 % a reference image.
2928 % The format of the RemapImage method is:
2930 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2931 % Image *image,const Image *remap_image)
2933 % A description of each parameter follows:
2935 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2937 % o image: the image.
2939 % o remap_image: the reference image.
2942 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2943 Image *image,const Image *remap_image)
2952 Initialize color cube.
2954 assert(image != (Image *) NULL);
2955 assert(image->signature == MagickSignature);
2956 if (image->debug != MagickFalse)
2957 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2958 assert(remap_image != (Image *) NULL);
2959 assert(remap_image->signature == MagickSignature);
2960 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2961 quantize_info->number_colors);
2962 if (cube_info == (CubeInfo *) NULL)
2963 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2965 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2966 if (status != MagickFalse)
2969 Classify image colors from the reference image.
2971 cube_info->quantize_info->number_colors=cube_info->colors;
2972 status=AssignImageColors(image,cube_info);
2974 DestroyCubeInfo(cube_info);
2979 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2983 % R e m a p I m a g e s %
2987 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2989 % RemapImages() replaces the colors of a sequence of images with the
2990 % closest color from a reference image.
2992 % The format of the RemapImage method is:
2994 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2995 % Image *images,Image *remap_image)
2997 % A description of each parameter follows:
2999 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3001 % o images: the image sequence.
3003 % o remap_image: the reference image.
3006 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3007 Image *images,const Image *remap_image)
3018 assert(images != (Image *) NULL);
3019 assert(images->signature == MagickSignature);
3020 if (images->debug != MagickFalse)
3021 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3023 if (remap_image == (Image *) NULL)
3026 Create a global colormap for an image sequence.
3028 status=QuantizeImages(quantize_info,images);
3032 Classify image colors from the reference image.
3034 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3035 quantize_info->number_colors);
3036 if (cube_info == (CubeInfo *) NULL)
3037 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3039 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3040 if (status != MagickFalse)
3043 Classify image colors from the reference image.
3045 cube_info->quantize_info->number_colors=cube_info->colors;
3047 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3049 status=AssignImageColors(image,cube_info);
3050 if (status == MagickFalse)
3054 DestroyCubeInfo(cube_info);
3059 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3063 % S e t G r a y s c a l e I m a g e %
3067 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3069 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3071 % The format of the SetGrayscaleImage method is:
3073 % MagickBooleanType SetGrayscaleImage(Image *image)
3075 % A description of each parameter follows:
3077 % o image: The image.
3081 #if defined(__cplusplus) || defined(c_plusplus)
3085 static int IntensityCompare(const void *x,const void *y)
3094 color_1=(PixelPacket *) x;
3095 color_2=(PixelPacket *) y;
3096 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3097 PixelIntensityToQuantum(color_2);
3098 return((int) intensity);
3101 #if defined(__cplusplus) || defined(c_plusplus)
3105 static MagickBooleanType SetGrayscaleImage(Image *image)
3127 assert(image != (Image *) NULL);
3128 assert(image->signature == MagickSignature);
3129 if (image->type != GrayscaleType)
3130 (void) TransformImageColorspace(image,GRAYColorspace);
3131 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3132 sizeof(*colormap_index));
3133 if (colormap_index == (ssize_t *) NULL)
3134 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3136 if (image->storage_class != PseudoClass)
3141 for (i=0; i <= (ssize_t) MaxMap; i++)
3142 colormap_index[i]=(-1);
3143 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3144 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3148 exception=(&image->exception);
3149 image_view=AcquireCacheView(image);
3150 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3151 #pragma omp parallel for schedule(dynamic,4) shared(status)
3153 for (y=0; y < (ssize_t) image->rows; y++)
3155 register IndexPacket
3158 register const PixelPacket
3164 if (status == MagickFalse)
3166 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3168 if (q == (PixelPacket *) NULL)
3173 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3174 for (x=0; x < (ssize_t) image->columns; x++)
3179 intensity=ScaleQuantumToMap(q->red);
3180 if (colormap_index[intensity] < 0)
3182 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3183 #pragma omp critical (MagickCore_SetGrayscaleImage)
3185 if (colormap_index[intensity] < 0)
3187 colormap_index[intensity]=(ssize_t) image->colors;
3188 image->colormap[image->colors]=(*q);
3192 indexes[x]=(IndexPacket) colormap_index[intensity];
3195 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3198 image_view=DestroyCacheView(image_view);
3200 for (i=0; i < (ssize_t) image->colors; i++)
3201 image->colormap[i].opacity=(unsigned short) i;
3202 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3204 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3206 if (colormap == (PixelPacket *) NULL)
3207 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3210 colormap[j]=image->colormap[0];
3211 for (i=0; i < (ssize_t) image->colors; i++)
3213 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3216 colormap[j]=image->colormap[i];
3218 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3220 image->colors=(size_t) (j+1);
3221 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3222 image->colormap=colormap;
3224 exception=(&image->exception);
3225 image_view=AcquireCacheView(image);
3226 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3227 #pragma omp parallel for schedule(dynamic,4) shared(status)
3229 for (y=0; y < (ssize_t) image->rows; y++)
3231 register IndexPacket
3234 register const PixelPacket
3240 if (status == MagickFalse)
3242 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3243 if (q == (PixelPacket *) NULL)
3248 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3249 for (x=0; x < (ssize_t) image->columns; x++)
3250 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3251 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3254 image_view=DestroyCacheView(image_view);
3255 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3256 image->type=GrayscaleType;
3257 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3258 image->type=BilevelType;