2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
7 % Q Q U U A A NN N T I ZZ E %
8 % Q Q U U AAAAA N N N T I ZZZ EEEEE %
9 % Q QQ U U A A N NN T I ZZ E %
10 % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
13 % MagickCore Methods to Reduce the Number of Unique Colors in an Image %
20 % Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
28 % Unless required by applicable law or agreed to in writing, software %
29 % distributed under the License is distributed on an "AS IS" BASIS, %
30 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31 % See the License for the specific language governing permissions and %
32 % limitations under the License. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Realism in computer graphics typically requires using 24 bits/pixel to
37 % generate an image. Yet many graphic display devices do not contain the
38 % amount of memory necessary to match the spatial and color resolution of
39 % the human eye. The Quantize methods takes a 24 bit image and reduces
40 % the number of colors so it can be displayed on raster device with less
41 % bits per pixel. In most instances, the quantized image closely
42 % resembles the original reference image.
44 % A reduction of colors in an image is also desirable for image
45 % transmission and real-time animation.
47 % QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 % them down to some fixed number of colors.
50 % For purposes of color allocation, an image is a set of n pixels, where
51 % each pixel is a point in RGB space. RGB space is a 3-dimensional
52 % vector space, and each pixel, Pi, is defined by an ordered triple of
53 % red, green, and blue coordinates, (Ri, Gi, Bi).
55 % Each primary color component (red, green, or blue) represents an
56 % intensity which varies linearly from 0 to a maximum value, Cmax, which
57 % corresponds to full saturation of that color. Color allocation is
58 % defined over a domain consisting of the cube in RGB space with opposite
59 % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
62 % The algorithm maps this domain onto a tree in which each node
63 % represents a cube within that domain. In the following discussion
64 % these cubes are defined by the coordinate of two opposite vertices:
65 % The vertex nearest the origin in RGB space and the vertex farthest from
68 % The tree's root node represents the entire domain, (0,0,0) through
69 % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70 % subdividing one node's cube into eight smaller cubes of equal size.
71 % This corresponds to bisecting the parent cube with planes passing
72 % through the midpoints of each edge.
74 % The basic algorithm operates in three phases: Classification,
75 % Reduction, and Assignment. Classification builds a color description
76 % tree for the image. Reduction collapses the tree until the number it
77 % represents, at most, the number of colors desired in the output image.
78 % Assignment defines the output image's color map and sets each pixel's
79 % color by restorage_class in the reduced tree. Our goal is to minimize
80 % the numerical discrepancies between the original colors and quantized
81 % colors (quantization error).
83 % Classification begins by initializing a color description tree of
84 % sufficient depth to represent each possible input color in a leaf.
85 % However, it is impractical to generate a fully-formed color description
86 % tree in the storage_class phase for realistic values of Cmax. If
87 % colors components in the input image are quantized to k-bit precision,
88 % so that Cmax= 2k-1, the tree would need k levels below the root node to
89 % allow representing each possible input color in a leaf. This becomes
90 % prohibitive because the tree's total number of nodes is 1 +
93 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95 % Initializes data structures for nodes only as they are needed; (2)
96 % Chooses a maximum depth for the tree as a function of the desired
97 % number of colors in the output image (currently log2(colormap size)).
99 % For each pixel in the input image, storage_class scans downward from
100 % the root of the color description tree. At each level of the tree it
101 % identifies the single node which represents a cube in RGB space
102 % containing the pixel's color. It updates the following data for each
105 % n1: Number of pixels whose color is contained in the RGB cube which
106 % this node represents;
108 % n2: Number of pixels whose color is not represented in a node at
109 % lower depth in the tree; initially, n2 = 0 for all nodes except
110 % leaves of the tree.
112 % Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113 % pixels not classified at a lower depth. The combination of these sums
114 % and n2 will ultimately characterize the mean color of a set of
115 % pixels represented by this node.
117 % E: the distance squared in RGB space between each pixel contained
118 % within a node and the nodes' center. This represents the
119 % quantization error for a node.
121 % Reduction repeatedly prunes the tree until the number of nodes with n2
122 % > 0 is less than or equal to the maximum number of colors allowed in
123 % the output image. On any given iteration over the tree, it selects
124 % those nodes whose E count is minimal for pruning and merges their color
125 % statistics upward. It uses a pruning threshold, Ep, to govern node
126 % selection as follows:
129 % while number of nodes with (n2 > 0) > required maximum number of colors
130 % prune all nodes such that E <= Ep
131 % Set Ep to minimum E in remaining nodes
133 % This has the effect of minimizing any quantization error when merging
134 % two nodes together.
136 % When a node to be pruned has offspring, the pruning procedure invokes
137 % itself recursively in order to prune the tree from the leaves upward.
138 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
139 % corresponding data in that node's parent. This retains the pruned
140 % node's color characteristics for later averaging.
142 % For each node, n2 pixels exist for which that node represents the
143 % smallest volume in RGB space containing those pixel's colors. When n2
144 % > 0 the node will uniquely define a color in the output image. At the
145 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
146 % the tree which represent colors present in the input image.
148 % The other pixel count, n1, indicates the total number of colors within
149 % the cubic volume which the node represents. This includes n1 - n2
150 % pixels whose colors should be defined by nodes at a lower level in the
153 % Assignment generates the output image from the pruned tree. The output
154 % image consists of two parts: (1) A color map, which is an array of
155 % color descriptions (RGB triples) for each color present in the output
156 % image; (2) A pixel array, which represents each pixel as an index
157 % into the color map array.
159 % First, the assignment phase makes one pass over the pruned color
160 % description tree to establish the image's color map. For each node
161 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162 % color of all pixels that classify no lower than this node. Each of
163 % these colors becomes an entry in the color map.
165 % Finally, the assignment phase reclassifies each pixel in the pruned
166 % tree to identify the deepest node containing the pixel's color. The
167 % pixel's value in the pixel array becomes the index of this node's mean
168 % color in the color map.
170 % This method is based on a similar algorithm written by Paul Raveling.
175 Include declarations.
177 #include "magick/studio.h"
178 #include "magick/cache-view.h"
179 #include "magick/color.h"
180 #include "magick/color-private.h"
181 #include "magick/colormap.h"
182 #include "magick/colorspace.h"
183 #include "magick/enhance.h"
184 #include "magick/exception.h"
185 #include "magick/exception-private.h"
186 #include "magick/histogram.h"
187 #include "magick/image.h"
188 #include "magick/image-private.h"
189 #include "magick/list.h"
190 #include "magick/memory_.h"
191 #include "magick/monitor.h"
192 #include "magick/monitor-private.h"
193 #include "magick/option.h"
194 #include "magick/pixel-private.h"
195 #include "magick/quantize.h"
196 #include "magick/quantum.h"
197 #include "magick/string_.h"
198 #include "magick/thread-private.h"
203 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
208 #define ErrorQueueLength 16
209 #define MaxNodes 266817
210 #define MaxTreeDepth 8
211 #define NodesInAList 1920
216 typedef struct _RealPixelPacket
225 typedef struct _NodeInfo
246 typedef struct _Nodes
255 typedef struct _CubeInfo
293 error[ErrorQueueLength];
296 weights[ErrorQueueLength];
322 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
325 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
327 static MagickBooleanType
328 AssignImageColors(Image *,CubeInfo *),
329 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
330 DitherImage(Image *,CubeInfo *),
331 SetGrayscaleImage(Image *);
334 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
337 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
338 DestroyCubeInfo(CubeInfo *),
339 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
340 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
341 ReduceImageColors(const Image *,CubeInfo *);
344 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
348 % A c q u i r e Q u a n t i z e I n f o %
352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
354 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
356 % The format of the AcquireQuantizeInfo method is:
358 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
360 % A description of each parameter follows:
362 % o image_info: the image info.
365 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
370 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
371 if (quantize_info == (QuantizeInfo *) NULL)
372 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
373 GetQuantizeInfo(quantize_info);
374 if (image_info != (ImageInfo *) NULL)
379 quantize_info->dither=image_info->dither;
380 option=GetImageOption(image_info,"dither");
381 if (option != (const char *) NULL)
382 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
383 MagickDitherOptions,MagickFalse,option);
384 quantize_info->measure_error=image_info->verbose;
386 return(quantize_info);
390 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
394 + A s s i g n I m a g e C o l o r s %
398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
400 % AssignImageColors() generates the output image from the pruned tree. The
401 % output image consists of two parts: (1) A color map, which is an array
402 % of color descriptions (RGB triples) for each color present in the
403 % output image; (2) A pixel array, which represents each pixel as an
404 % index into the color map array.
406 % First, the assignment phase makes one pass over the pruned color
407 % description tree to establish the image's color map. For each node
408 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
409 % color of all pixels that classify no lower than this node. Each of
410 % these colors becomes an entry in the color map.
412 % Finally, the assignment phase reclassifies each pixel in the pruned
413 % tree to identify the deepest node containing the pixel's color. The
414 % pixel's value in the pixel array becomes the index of this node's mean
415 % color in the color map.
417 % The format of the AssignImageColors() method is:
419 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
421 % A description of each parameter follows.
423 % o image: the image.
425 % o cube_info: A pointer to the Cube structure.
429 static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
430 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
435 if ((cube_info->associate_alpha == MagickFalse) ||
436 (pixel->opacity == OpaqueOpacity))
438 alpha_pixel->red=(MagickRealType) GetRedPixelComponent(pixel);
439 alpha_pixel->green=(MagickRealType) GetGreenPixelComponent(pixel);
440 alpha_pixel->blue=(MagickRealType) GetBluePixelComponent(pixel);
441 alpha_pixel->opacity=(MagickRealType) GetOpacityPixelComponent(pixel);
444 alpha=(MagickRealType) (QuantumScale*(QuantumRange-
445 GetOpacityPixelComponent(pixel)));
446 alpha_pixel->red=alpha*GetRedPixelComponent(pixel);
447 alpha_pixel->green=alpha*GetGreenPixelComponent(pixel);
448 alpha_pixel->blue=alpha*GetBluePixelComponent(pixel);
449 alpha_pixel->opacity=(MagickRealType) GetOpacityPixelComponent(pixel);
452 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
456 if (value >= QuantumRange)
457 return((Quantum) QuantumRange);
458 return((Quantum) (value+0.5));
461 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
462 const RealPixelPacket *pixel,size_t index)
467 id=(size_t) (((ScaleQuantumToChar(ClampToUnsignedQuantum(
468 GetRedPixelComponent(pixel))) >> index) & 0x01) |
469 ((ScaleQuantumToChar(ClampToUnsignedQuantum(
470 GetGreenPixelComponent(pixel))) >> index) & 0x01) << 1 |
471 ((ScaleQuantumToChar(ClampToUnsignedQuantum(
472 GetBluePixelComponent(pixel))) >> index) & 0x01) << 2);
473 if (cube_info->associate_alpha != MagickFalse)
474 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(
475 GetOpacityPixelComponent(pixel))) >> index) & 0x1) << 3;
479 static inline MagickBooleanType IsSameColor(const Image *image,
480 const PixelPacket *p,const PixelPacket *q)
482 if ((GetRedPixelComponent(p) != GetRedPixelComponent(q)) ||
483 (GetGreenPixelComponent(p) != GetGreenPixelComponent(q)) ||
484 (GetBluePixelComponent(p) != GetBluePixelComponent(q)))
486 if ((image->matte != MagickFalse) &&
487 (GetOpacityPixelComponent(p) != GetOpacityPixelComponent(q)))
492 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
494 #define AssignImageTag "Assign/Image"
500 Allocate image colormap.
502 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
503 (cube_info->quantize_info->colorspace != CMYKColorspace))
504 (void) TransformImageColorspace((Image *) image,
505 cube_info->quantize_info->colorspace);
507 if ((image->colorspace != GRAYColorspace) &&
508 (image->colorspace != RGBColorspace) &&
509 (image->colorspace != CMYColorspace))
510 (void) TransformImageColorspace((Image *) image,RGBColorspace);
511 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
512 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
515 cube_info->transparent_pixels=0;
516 cube_info->transparent_index=(-1);
517 (void) DefineImageColormap(image,cube_info,cube_info->root);
519 Create a reduced color image.
521 if ((cube_info->quantize_info->dither != MagickFalse) &&
522 (cube_info->quantize_info->dither_method != NoDitherMethod))
523 (void) DitherImage(image,cube_info);
536 exception=(&image->exception);
537 image_view=AcquireCacheView(image);
538 #if defined(MAGICKCORE_OPENMP_SUPPORT)
539 #pragma omp parallel for schedule(dynamic,4) shared(status)
541 for (y=0; y < (ssize_t) image->rows; y++)
558 if (status == MagickFalse)
560 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
562 if (q == (PixelPacket *) NULL)
567 indexes=GetCacheViewAuthenticIndexQueue(image_view);
569 for (x=0; x < (ssize_t) image->columns; x+=count)
574 register const NodeInfo
585 Identify the deepest node containing the pixel's color.
587 for (count=1; (x+count) < (ssize_t) image->columns; count++)
588 if (IsSameColor(image,q,q+count) == MagickFalse)
590 AssociateAlphaPixel(&cube,q,&pixel);
592 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
594 id=ColorToNodeId(&cube,&pixel,index);
595 if (node_info->child[id] == (NodeInfo *) NULL)
597 node_info=node_info->child[id];
600 Find closest color among siblings and their children.
603 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
604 (QuantumRange+1.0)+1.0);
605 ClosestColor(image,&cube,node_info->parent);
606 index=cube.color_number;
607 for (i=0; i < (ssize_t) count; i++)
609 if (image->storage_class == PseudoClass)
610 SetIndexPixelComponent(indexes+x+i,index);
611 if (cube.quantize_info->measure_error == MagickFalse)
613 SetRGBPixelComponents(q,image->colormap+index);
614 if (cube.associate_alpha != MagickFalse)
615 SetOpacityPixelComponent(q,image->colormap[index].opacity);
620 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
622 if (image->progress_monitor != (MagickProgressMonitor) NULL)
627 #if defined(MAGICKCORE_OPENMP_SUPPORT)
628 #pragma omp critical (MagickCore_AssignImageColors)
630 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
632 if (proceed == MagickFalse)
636 image_view=DestroyCacheView(image_view);
638 if (cube_info->quantize_info->measure_error != MagickFalse)
639 (void) GetImageQuantizeError(image);
640 if ((cube_info->quantize_info->number_colors == 2) &&
641 (cube_info->quantize_info->colorspace == GRAYColorspace))
656 for (i=0; i < (ssize_t) image->colors; i++)
658 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
659 QuantumRange/2.0) ? 0 : QuantumRange);
660 SetRedPixelComponent(q,intensity);
661 SetGreenPixelComponent(q,intensity);
662 SetBluePixelComponent(q,intensity);
666 (void) SyncImage(image);
667 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
668 (cube_info->quantize_info->colorspace != CMYKColorspace))
669 (void) TransformImageColorspace((Image *) image,RGBColorspace);
674 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
678 + C l a s s i f y I m a g e C o l o r s %
682 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
684 % ClassifyImageColors() begins by initializing a color description tree
685 % of sufficient depth to represent each possible input color in a leaf.
686 % However, it is impractical to generate a fully-formed color
687 % description tree in the storage_class phase for realistic values of
688 % Cmax. If colors components in the input image are quantized to k-bit
689 % precision, so that Cmax= 2k-1, the tree would need k levels below the
690 % root node to allow representing each possible input color in a leaf.
691 % This becomes prohibitive because the tree's total number of nodes is
694 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
695 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
696 % Initializes data structures for nodes only as they are needed; (2)
697 % Chooses a maximum depth for the tree as a function of the desired
698 % number of colors in the output image (currently log2(colormap size)).
700 % For each pixel in the input image, storage_class scans downward from
701 % the root of the color description tree. At each level of the tree it
702 % identifies the single node which represents a cube in RGB space
703 % containing It updates the following data for each such node:
705 % n1 : Number of pixels whose color is contained in the RGB cube
706 % which this node represents;
708 % n2 : Number of pixels whose color is not represented in a node at
709 % lower depth in the tree; initially, n2 = 0 for all nodes except
710 % leaves of the tree.
712 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
713 % all pixels not classified at a lower depth. The combination of
714 % these sums and n2 will ultimately characterize the mean color of a
715 % set of pixels represented by this node.
717 % E: the distance squared in RGB space between each pixel contained
718 % within a node and the nodes' center. This represents the quantization
721 % The format of the ClassifyImageColors() method is:
723 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
724 % const Image *image,ExceptionInfo *exception)
726 % A description of each parameter follows.
728 % o cube_info: A pointer to the Cube structure.
730 % o image: the image.
734 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
739 associate_alpha=image->matte;
740 if (cube_info->quantize_info->colorspace == TransparentColorspace)
741 associate_alpha=MagickFalse;
742 if ((cube_info->quantize_info->number_colors == 2) &&
743 (cube_info->quantize_info->colorspace == GRAYColorspace))
744 associate_alpha=MagickFalse;
745 cube_info->associate_alpha=associate_alpha;
748 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
749 const Image *image,ExceptionInfo *exception)
751 #define ClassifyImageTag "Classify/Image"
781 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
783 SetAssociatedAlpha(image,cube_info);
784 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
785 (cube_info->quantize_info->colorspace != CMYKColorspace))
786 (void) TransformImageColorspace((Image *) image,
787 cube_info->quantize_info->colorspace);
789 if ((image->colorspace != GRAYColorspace) &&
790 (image->colorspace != CMYColorspace) &&
791 (image->colorspace != RGBColorspace))
792 (void) TransformImageColorspace((Image *) image,RGBColorspace);
793 midpoint.red=(MagickRealType) QuantumRange/2.0;
794 midpoint.green=(MagickRealType) QuantumRange/2.0;
795 midpoint.blue=(MagickRealType) QuantumRange/2.0;
796 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
798 image_view=AcquireCacheView(image);
799 for (y=0; y < (ssize_t) image->rows; y++)
801 register const PixelPacket
807 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
808 if (p == (const PixelPacket *) NULL)
810 if (cube_info->nodes > MaxNodes)
813 Prune one level if the color tree is too large.
815 PruneLevel(image,cube_info,cube_info->root);
818 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
821 Start at the root and descend the color cube tree.
823 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
824 if (IsSameColor(image,p,p+count) == MagickFalse)
826 AssociateAlphaPixel(cube_info,p,&pixel);
827 index=MaxTreeDepth-1;
828 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
830 node_info=cube_info->root;
831 for (level=1; level <= MaxTreeDepth; level++)
834 id=ColorToNodeId(cube_info,&pixel,index);
835 mid.red+=(id & 1) != 0 ? bisect : -bisect;
836 mid.green+=(id & 2) != 0 ? bisect : -bisect;
837 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
838 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
839 if (node_info->child[id] == (NodeInfo *) NULL)
842 Set colors of new node to contain pixel.
844 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
845 if (node_info->child[id] == (NodeInfo *) NULL)
846 (void) ThrowMagickException(exception,GetMagickModule(),
847 ResourceLimitError,"MemoryAllocationFailed","`%s'",
849 if (level == MaxTreeDepth)
853 Approximate the quantization error represented by this node.
855 node_info=node_info->child[id];
856 error.red=QuantumScale*(pixel.red-mid.red);
857 error.green=QuantumScale*(pixel.green-mid.green);
858 error.blue=QuantumScale*(pixel.blue-mid.blue);
859 if (cube_info->associate_alpha != MagickFalse)
860 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
861 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
862 count*error.green*error.green+count*error.blue*error.blue+
863 count*error.opacity*error.opacity));
864 cube_info->root->quantize_error+=node_info->quantize_error;
868 Sum RGB for this leaf for later derivation of the mean cube color.
870 node_info->number_unique+=count;
871 node_info->total_color.red+=count*QuantumScale*pixel.red;
872 node_info->total_color.green+=count*QuantumScale*pixel.green;
873 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
874 if (cube_info->associate_alpha != MagickFalse)
875 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
878 if (cube_info->colors > cube_info->maximum_colors)
880 PruneToCubeDepth(image,cube_info,cube_info->root);
883 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
885 if (proceed == MagickFalse)
888 for (y++; y < (ssize_t) image->rows; y++)
890 register const PixelPacket
896 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
897 if (p == (const PixelPacket *) NULL)
899 if (cube_info->nodes > MaxNodes)
902 Prune one level if the color tree is too large.
904 PruneLevel(image,cube_info,cube_info->root);
907 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
910 Start at the root and descend the color cube tree.
912 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
913 if (IsSameColor(image,p,p+count) == MagickFalse)
915 AssociateAlphaPixel(cube_info,p,&pixel);
916 index=MaxTreeDepth-1;
917 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
919 node_info=cube_info->root;
920 for (level=1; level <= cube_info->depth; level++)
923 id=ColorToNodeId(cube_info,&pixel,index);
924 mid.red+=(id & 1) != 0 ? bisect : -bisect;
925 mid.green+=(id & 2) != 0 ? bisect : -bisect;
926 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
927 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
928 if (node_info->child[id] == (NodeInfo *) NULL)
931 Set colors of new node to contain pixel.
933 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
934 if (node_info->child[id] == (NodeInfo *) NULL)
935 (void) ThrowMagickException(exception,GetMagickModule(),
936 ResourceLimitError,"MemoryAllocationFailed","%s",
938 if (level == cube_info->depth)
942 Approximate the quantization error represented by this node.
944 node_info=node_info->child[id];
945 error.red=QuantumScale*(pixel.red-mid.red);
946 error.green=QuantumScale*(pixel.green-mid.green);
947 error.blue=QuantumScale*(pixel.blue-mid.blue);
948 if (cube_info->associate_alpha != MagickFalse)
949 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
950 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
951 count*error.green*error.green+count*error.blue*error.blue+
952 count*error.opacity*error.opacity));
953 cube_info->root->quantize_error+=node_info->quantize_error;
957 Sum RGB for this leaf for later derivation of the mean cube color.
959 node_info->number_unique+=count;
960 node_info->total_color.red+=count*QuantumScale*pixel.red;
961 node_info->total_color.green+=count*QuantumScale*pixel.green;
962 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
963 if (cube_info->associate_alpha != MagickFalse)
964 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
967 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
969 if (proceed == MagickFalse)
972 image_view=DestroyCacheView(image_view);
973 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
974 (cube_info->quantize_info->colorspace != CMYKColorspace))
975 (void) TransformImageColorspace((Image *) image,RGBColorspace);
980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
984 % C l o n e Q u a n t i z e I n f o %
988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
990 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
991 % or if quantize info is NULL, a new one.
993 % The format of the CloneQuantizeInfo method is:
995 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
997 % A description of each parameter follows:
999 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1000 % quantize info, or if image info is NULL a new one.
1002 % o quantize_info: a structure of type info.
1005 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1010 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1011 if (clone_info == (QuantizeInfo *) NULL)
1012 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1013 GetQuantizeInfo(clone_info);
1014 if (quantize_info == (QuantizeInfo *) NULL)
1016 clone_info->number_colors=quantize_info->number_colors;
1017 clone_info->tree_depth=quantize_info->tree_depth;
1018 clone_info->dither=quantize_info->dither;
1019 clone_info->dither_method=quantize_info->dither_method;
1020 clone_info->colorspace=quantize_info->colorspace;
1021 clone_info->measure_error=quantize_info->measure_error;
1026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1030 + C l o s e s t C o l o r %
1034 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1036 % ClosestColor() traverses the color cube tree at a particular node and
1037 % determines which colormap entry best represents the input color.
1039 % The format of the ClosestColor method is:
1041 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1042 % const NodeInfo *node_info)
1044 % A description of each parameter follows.
1046 % o image: the image.
1048 % o cube_info: A pointer to the Cube structure.
1050 % o node_info: the address of a structure of type NodeInfo which points to a
1051 % node in the color cube tree that is to be pruned.
1054 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1055 const NodeInfo *node_info)
1064 Traverse any children.
1066 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1067 for (i=0; i < (ssize_t) number_children; i++)
1068 if (node_info->child[i] != (NodeInfo *) NULL)
1069 ClosestColor(image,cube_info,node_info->child[i]);
1070 if (node_info->number_unique != 0)
1075 register MagickRealType
1080 register PixelPacket
1083 register RealPixelPacket
1087 Determine if this color is "closest".
1089 p=image->colormap+node_info->color_number;
1090 q=(&cube_info->target);
1093 if (cube_info->associate_alpha != MagickFalse)
1095 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1096 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1098 pixel=alpha*GetRedPixelComponent(p)-beta*GetRedPixelComponent(q);
1099 distance=pixel*pixel;
1100 if (distance <= cube_info->distance)
1102 pixel=alpha*GetGreenPixelComponent(p)-beta*GetGreenPixelComponent(q);
1103 distance+=pixel*pixel;
1104 if (distance <= cube_info->distance)
1106 pixel=alpha*GetBluePixelComponent(p)-beta*
1107 GetBluePixelComponent(q);
1108 distance+=pixel*pixel;
1109 if (distance <= cube_info->distance)
1112 distance+=pixel*pixel;
1113 if (distance <= cube_info->distance)
1115 cube_info->distance=distance;
1116 cube_info->color_number=node_info->color_number;
1125 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1129 % C o m p r e s s I m a g e C o l o r m a p %
1133 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1135 % CompressImageColormap() compresses an image colormap by removing any
1136 % duplicate or unused color entries.
1138 % The format of the CompressImageColormap method is:
1140 % MagickBooleanType CompressImageColormap(Image *image)
1142 % A description of each parameter follows:
1144 % o image: the image.
1147 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1152 assert(image != (Image *) NULL);
1153 assert(image->signature == MagickSignature);
1154 if (image->debug != MagickFalse)
1155 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1156 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1157 return(MagickFalse);
1158 GetQuantizeInfo(&quantize_info);
1159 quantize_info.number_colors=image->colors;
1160 quantize_info.tree_depth=MaxTreeDepth;
1161 return(QuantizeImage(&quantize_info,image));
1165 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1169 + D e f i n e I m a g e C o l o r m a p %
1173 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1175 % DefineImageColormap() traverses the color cube tree and notes each colormap
1176 % entry. A colormap entry is any node in the color cube tree where the
1177 % of unique colors is not zero. DefineImageColormap() returns the number of
1178 % colors in the image colormap.
1180 % The format of the DefineImageColormap method is:
1182 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1183 % NodeInfo *node_info)
1185 % A description of each parameter follows.
1187 % o image: the image.
1189 % o cube_info: A pointer to the Cube structure.
1191 % o node_info: the address of a structure of type NodeInfo which points to a
1192 % node in the color cube tree that is to be pruned.
1195 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1196 NodeInfo *node_info)
1205 Traverse any children.
1207 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1208 for (i=0; i < (ssize_t) number_children; i++)
1209 if (node_info->child[i] != (NodeInfo *) NULL)
1210 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1211 if (node_info->number_unique != 0)
1213 register MagickRealType
1216 register PixelPacket
1220 Colormap entry is defined by the mean color in this cube.
1222 q=image->colormap+image->colors;
1223 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1224 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1225 if (cube_info->associate_alpha == MagickFalse)
1227 SetRedPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1228 QuantumRange*node_info->total_color.red)));
1229 SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1230 QuantumRange*node_info->total_color.green)));
1231 SetBluePixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1232 QuantumRange*node_info->total_color.blue)));
1233 SetOpacityPixelComponent(q,OpaqueOpacity);
1240 opacity=(MagickRealType) (alpha*QuantumRange*
1241 node_info->total_color.opacity);
1242 SetOpacityPixelComponent(q,ClampToQuantum(opacity));
1243 if (q->opacity == OpaqueOpacity)
1245 SetRedPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1246 QuantumRange*node_info->total_color.red)));
1247 SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1248 QuantumRange*node_info->total_color.green)));
1249 SetBluePixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1250 QuantumRange*node_info->total_color.blue)));
1257 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1258 (MagickRealType) q->opacity));
1259 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1260 SetRedPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1261 gamma*QuantumRange*node_info->total_color.red)));
1262 SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1263 gamma*QuantumRange*node_info->total_color.green)));
1264 SetBluePixelComponent(q,ClampToQuantum((MagickRealType) (
1265 alpha*gamma*QuantumRange*node_info->total_color.blue)));
1266 if (node_info->number_unique > cube_info->transparent_pixels)
1268 cube_info->transparent_pixels=node_info->number_unique;
1269 cube_info->transparent_index=(ssize_t) image->colors;
1273 node_info->color_number=image->colors++;
1275 return(image->colors);
1279 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1283 + D e s t r o y C u b e I n f o %
1287 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1289 % DestroyCubeInfo() deallocates memory associated with an image.
1291 % The format of the DestroyCubeInfo method is:
1293 % DestroyCubeInfo(CubeInfo *cube_info)
1295 % A description of each parameter follows:
1297 % o cube_info: the address of a structure of type CubeInfo.
1300 static void DestroyCubeInfo(CubeInfo *cube_info)
1306 Release color cube tree storage.
1310 nodes=cube_info->node_queue->next;
1311 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1312 cube_info->node_queue->nodes);
1313 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1314 cube_info->node_queue);
1315 cube_info->node_queue=nodes;
1316 } while (cube_info->node_queue != (Nodes *) NULL);
1317 if (cube_info->cache != (ssize_t *) NULL)
1318 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1319 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1320 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1324 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1328 % D e s t r o y Q u a n t i z e I n f o %
1332 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1334 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1337 % The format of the DestroyQuantizeInfo method is:
1339 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1341 % A description of each parameter follows:
1343 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1346 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1348 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1349 assert(quantize_info != (QuantizeInfo *) NULL);
1350 assert(quantize_info->signature == MagickSignature);
1351 quantize_info->signature=(~MagickSignature);
1352 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1353 return(quantize_info);
1357 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1361 + D i t h e r I m a g e %
1365 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1367 % DitherImage() distributes the difference between an original image and
1368 % the corresponding color reduced algorithm to neighboring pixels using
1369 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1370 % MagickTrue if the image is dithered otherwise MagickFalse.
1372 % The format of the DitherImage method is:
1374 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1376 % A description of each parameter follows.
1378 % o image: the image.
1380 % o cube_info: A pointer to the Cube structure.
1384 static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1389 assert(pixels != (RealPixelPacket **) NULL);
1390 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1391 if (pixels[i] != (RealPixelPacket *) NULL)
1392 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1393 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1397 static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1408 number_threads=GetOpenMPMaximumThreads();
1409 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1411 if (pixels == (RealPixelPacket **) NULL)
1412 return((RealPixelPacket **) NULL);
1413 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1414 for (i=0; i < (ssize_t) number_threads; i++)
1416 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1417 2*sizeof(**pixels));
1418 if (pixels[i] == (RealPixelPacket *) NULL)
1419 return(DestroyPixelThreadSet(pixels));
1424 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1425 const RealPixelPacket *pixel)
1427 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1428 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1429 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1430 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1436 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1437 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1438 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1439 if (cube_info->associate_alpha != MagickFalse)
1440 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1445 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1447 #define DitherImageTag "Dither/Image"
1465 Distribute quantization error using Floyd-Steinberg.
1467 pixels=AcquirePixelThreadSet(image->columns);
1468 if (pixels == (RealPixelPacket **) NULL)
1469 return(MagickFalse);
1470 exception=(&image->exception);
1472 image_view=AcquireCacheView(image);
1473 for (y=0; y < (ssize_t) image->rows; y++)
1476 id = GetOpenMPThreadId();
1485 register IndexPacket
1488 register PixelPacket
1500 if (status == MagickFalse)
1502 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1503 if (q == (PixelPacket *) NULL)
1508 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1510 current=pixels[id]+(y & 0x01)*image->columns;
1511 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1512 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1513 for (x=0; x < (ssize_t) image->columns; x++)
1525 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1526 AssociateAlphaPixel(&cube,q+u,&pixel);
1529 pixel.red+=7*current[u-v].red/16;
1530 pixel.green+=7*current[u-v].green/16;
1531 pixel.blue+=7*current[u-v].blue/16;
1532 if (cube.associate_alpha != MagickFalse)
1533 pixel.opacity+=7*current[u-v].opacity/16;
1537 if (x < (ssize_t) (image->columns-1))
1539 pixel.red+=previous[u+v].red/16;
1540 pixel.green+=previous[u+v].green/16;
1541 pixel.blue+=previous[u+v].blue/16;
1542 if (cube.associate_alpha != MagickFalse)
1543 pixel.opacity+=previous[u+v].opacity/16;
1545 pixel.red+=5*previous[u].red/16;
1546 pixel.green+=5*previous[u].green/16;
1547 pixel.blue+=5*previous[u].blue/16;
1548 if (cube.associate_alpha != MagickFalse)
1549 pixel.opacity+=5*previous[u].opacity/16;
1552 pixel.red+=3*previous[u-v].red/16;
1553 pixel.green+=3*previous[u-v].green/16;
1554 pixel.blue+=3*previous[u-v].blue/16;
1555 if (cube.associate_alpha != MagickFalse)
1556 pixel.opacity+=3*previous[u-v].opacity/16;
1559 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1560 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1561 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1562 if (cube.associate_alpha != MagickFalse)
1563 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1564 i=CacheOffset(&cube,&pixel);
1565 if (cube.cache[i] < 0)
1574 Identify the deepest node containing the pixel's color.
1576 node_info=cube.root;
1577 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1579 id=ColorToNodeId(&cube,&pixel,index);
1580 if (node_info->child[id] == (NodeInfo *) NULL)
1582 node_info=node_info->child[id];
1585 Find closest color among siblings and their children.
1588 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1590 ClosestColor(image,&cube,node_info->parent);
1591 cube.cache[i]=(ssize_t) cube.color_number;
1594 Assign pixel to closest colormap entry.
1596 index=(size_t) cube.cache[i];
1597 if (image->storage_class == PseudoClass)
1598 SetIndexPixelComponent(indexes+u,index);
1599 if (cube.quantize_info->measure_error == MagickFalse)
1601 SetRGBPixelComponents(q+u,image->colormap+index);
1602 if (cube.associate_alpha != MagickFalse)
1603 SetOpacityPixelComponent(q+u,image->colormap[index].opacity);
1605 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1610 AssociateAlphaPixel(&cube,image->colormap+index,&color);
1611 current[u].red=pixel.red-color.red;
1612 current[u].green=pixel.green-color.green;
1613 current[u].blue=pixel.blue-color.blue;
1614 if (cube.associate_alpha != MagickFalse)
1615 current[u].opacity=pixel.opacity-color.opacity;
1616 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1621 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1622 #pragma omp critical (MagickCore_FloydSteinbergDither)
1624 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1626 if (proceed == MagickFalse)
1631 image_view=DestroyCacheView(image_view);
1632 pixels=DestroyPixelThreadSet(pixels);
1636 static MagickBooleanType
1637 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1639 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1640 const size_t level,const unsigned int direction)
1647 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1648 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1649 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1654 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1655 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1656 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1661 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1662 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1663 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1668 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1669 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1670 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1681 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1682 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1683 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1684 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1685 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1686 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1687 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1692 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1693 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1694 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1695 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1696 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1697 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1698 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1703 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1704 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1705 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1707 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1709 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1714 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1715 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1716 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1717 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1718 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1719 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1720 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1728 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1729 CubeInfo *cube_info,const unsigned int direction)
1731 #define DitherImageTag "Dither/Image"
1747 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1748 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1753 register IndexPacket
1756 register PixelPacket
1765 exception=(&image->exception);
1766 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1767 if (q == (PixelPacket *) NULL)
1768 return(MagickFalse);
1769 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1770 AssociateAlphaPixel(cube_info,q,&pixel);
1771 for (i=0; i < ErrorQueueLength; i++)
1773 pixel.red+=p->weights[i]*p->error[i].red;
1774 pixel.green+=p->weights[i]*p->error[i].green;
1775 pixel.blue+=p->weights[i]*p->error[i].blue;
1776 if (cube_info->associate_alpha != MagickFalse)
1777 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1779 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1780 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1781 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1782 if (cube_info->associate_alpha != MagickFalse)
1783 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1784 i=CacheOffset(cube_info,&pixel);
1785 if (p->cache[i] < 0)
1794 Identify the deepest node containing the pixel's color.
1797 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1799 id=ColorToNodeId(cube_info,&pixel,index);
1800 if (node_info->child[id] == (NodeInfo *) NULL)
1802 node_info=node_info->child[id];
1804 node_info=node_info->parent;
1806 Find closest color among siblings and their children.
1809 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1810 QuantumRange+1.0)+1.0);
1811 ClosestColor(image,p,node_info->parent);
1812 p->cache[i]=(ssize_t) p->color_number;
1815 Assign pixel to closest colormap entry.
1817 index=(size_t) (1*p->cache[i]);
1818 if (image->storage_class == PseudoClass)
1819 *indexes=(IndexPacket) index;
1820 if (cube_info->quantize_info->measure_error == MagickFalse)
1822 SetRGBPixelComponents(q,image->colormap+index);
1823 if (cube_info->associate_alpha != MagickFalse)
1824 SetOpacityPixelComponent(q,image->colormap[index].opacity);
1826 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1827 return(MagickFalse);
1829 Propagate the error as the last entry of the error queue.
1831 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1832 sizeof(p->error[0]));
1833 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1834 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1835 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1836 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1837 if (cube_info->associate_alpha != MagickFalse)
1838 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1839 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1840 if (proceed == MagickFalse)
1841 return(MagickFalse);
1846 case WestGravity: p->x--; break;
1847 case EastGravity: p->x++; break;
1848 case NorthGravity: p->y--; break;
1849 case SouthGravity: p->y++; break;
1854 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1861 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1868 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1882 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1883 return(FloydSteinbergDither(image,cube_info));
1885 Distribute quantization error along a Hilbert curve.
1887 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1888 sizeof(*cube_info->error));
1891 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1892 for (depth=1; i != 0; depth++)
1894 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1896 cube_info->offset=0;
1897 cube_info->span=(MagickSizeType) image->columns*image->rows;
1898 image_view=AcquireCacheView(image);
1900 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1901 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1902 image_view=DestroyCacheView(image_view);
1907 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1911 + G e t C u b e I n f o %
1915 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1917 % GetCubeInfo() initialize the Cube data structure.
1919 % The format of the GetCubeInfo method is:
1921 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1922 % const size_t depth,const size_t maximum_colors)
1924 % A description of each parameter follows.
1926 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1928 % o depth: Normally, this integer value is zero or one. A zero or
1929 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1930 % A tree of this depth generally allows the best representation of the
1931 % reference image with the least amount of memory and the fastest
1932 % computational speed. In some cases, such as an image with low color
1933 % dispersion (a few number of colors), a value other than
1934 % Log4(number_colors) is required. To expand the color tree completely,
1937 % o maximum_colors: maximum colors.
1940 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1941 const size_t depth,const size_t maximum_colors)
1957 Initialize tree to describe color cube_info.
1959 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1960 if (cube_info == (CubeInfo *) NULL)
1961 return((CubeInfo *) NULL);
1962 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1963 cube_info->depth=depth;
1964 if (cube_info->depth > MaxTreeDepth)
1965 cube_info->depth=MaxTreeDepth;
1966 if (cube_info->depth < 2)
1968 cube_info->maximum_colors=maximum_colors;
1970 Initialize root node.
1972 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1973 if (cube_info->root == (NodeInfo *) NULL)
1974 return((CubeInfo *) NULL);
1975 cube_info->root->parent=cube_info->root;
1976 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1977 if (cube_info->quantize_info->dither == MagickFalse)
1980 Initialize dither resources.
1982 length=(size_t) (1UL << (4*(8-CacheShift)));
1983 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1984 sizeof(*cube_info->cache));
1985 if (cube_info->cache == (ssize_t *) NULL)
1986 return((CubeInfo *) NULL);
1988 Initialize color cache.
1990 for (i=0; i < (ssize_t) length; i++)
1991 cube_info->cache[i]=(-1);
1993 Distribute weights along a curve of exponential decay.
1996 for (i=0; i < ErrorQueueLength; i++)
1998 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1999 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2002 Normalize the weighting factors.
2005 for (i=0; i < ErrorQueueLength; i++)
2006 weight+=cube_info->weights[i];
2008 for (i=0; i < ErrorQueueLength; i++)
2010 cube_info->weights[i]/=weight;
2011 sum+=cube_info->weights[i];
2013 cube_info->weights[0]+=1.0-sum;
2018 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2022 + G e t N o d e I n f o %
2026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2028 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2029 % presets all fields to zero.
2031 % The format of the GetNodeInfo method is:
2033 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2034 % const size_t level,NodeInfo *parent)
2036 % A description of each parameter follows.
2038 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2040 % o id: Specifies the child number of the node.
2042 % o level: Specifies the level in the storage_class the node resides.
2045 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2046 const size_t level,NodeInfo *parent)
2051 if (cube_info->free_nodes == 0)
2057 Allocate a new queue of nodes.
2059 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2060 if (nodes == (Nodes *) NULL)
2061 return((NodeInfo *) NULL);
2062 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2063 sizeof(*nodes->nodes));
2064 if (nodes->nodes == (NodeInfo *) NULL)
2065 return((NodeInfo *) NULL);
2066 nodes->next=cube_info->node_queue;
2067 cube_info->node_queue=nodes;
2068 cube_info->next_node=nodes->nodes;
2069 cube_info->free_nodes=NodesInAList;
2072 cube_info->free_nodes--;
2073 node_info=cube_info->next_node++;
2074 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2075 node_info->parent=parent;
2077 node_info->level=level;
2082 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2086 % G e t I m a g e Q u a n t i z e E r r o r %
2090 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2092 % GetImageQuantizeError() measures the difference between the original
2093 % and quantized images. This difference is the total quantization error.
2094 % The error is computed by summing over all pixels in an image the distance
2095 % squared in RGB space between each reference pixel value and its quantized
2096 % value. These values are computed:
2098 % o mean_error_per_pixel: This value is the mean error for any single
2099 % pixel in the image.
2101 % o normalized_mean_square_error: This value is the normalized mean
2102 % quantization error for any single pixel in the image. This distance
2103 % measure is normalized to a range between 0 and 1. It is independent
2104 % of the range of red, green, and blue values in the image.
2106 % o normalized_maximum_square_error: Thsi value is the normalized
2107 % maximum quantization error for any single pixel in the image. This
2108 % distance measure is normalized to a range between 0 and 1. It is
2109 % independent of the range of red, green, and blue values in your image.
2111 % The format of the GetImageQuantizeError method is:
2113 % MagickBooleanType GetImageQuantizeError(Image *image)
2115 % A description of each parameter follows.
2117 % o image: the image.
2120 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2138 mean_error_per_pixel;
2146 assert(image != (Image *) NULL);
2147 assert(image->signature == MagickSignature);
2148 if (image->debug != MagickFalse)
2149 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2150 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2151 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2152 if (image->storage_class == DirectClass)
2156 area=3.0*image->columns*image->rows;
2158 mean_error_per_pixel=0.0;
2160 exception=(&image->exception);
2161 image_view=AcquireCacheView(image);
2162 for (y=0; y < (ssize_t) image->rows; y++)
2164 register const PixelPacket
2170 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2171 if (p == (const PixelPacket *) NULL)
2173 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2174 for (x=0; x < (ssize_t) image->columns; x++)
2176 index=1UL*GetIndexPixelComponent(indexes+x);
2177 if (image->matte != MagickFalse)
2179 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2180 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2181 image->colormap[index].opacity));
2183 distance=fabs(alpha*GetRedPixelComponent(p)-beta*
2184 image->colormap[index].red);
2185 mean_error_per_pixel+=distance;
2186 mean_error+=distance*distance;
2187 if (distance > maximum_error)
2188 maximum_error=distance;
2189 distance=fabs(alpha*GetGreenPixelComponent(p)-beta*
2190 image->colormap[index].green);
2191 mean_error_per_pixel+=distance;
2192 mean_error+=distance*distance;
2193 if (distance > maximum_error)
2194 maximum_error=distance;
2195 distance=fabs(alpha*GetBluePixelComponent(p)-beta*
2196 image->colormap[index].blue);
2197 mean_error_per_pixel+=distance;
2198 mean_error+=distance*distance;
2199 if (distance > maximum_error)
2200 maximum_error=distance;
2204 image_view=DestroyCacheView(image_view);
2205 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2206 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2208 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2217 % G e t Q u a n t i z e I n f o %
2221 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2223 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2225 % The format of the GetQuantizeInfo method is:
2227 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2229 % A description of each parameter follows:
2231 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2234 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2236 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2237 assert(quantize_info != (QuantizeInfo *) NULL);
2238 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2239 quantize_info->number_colors=256;
2240 quantize_info->dither=MagickTrue;
2241 quantize_info->dither_method=RiemersmaDitherMethod;
2242 quantize_info->colorspace=UndefinedColorspace;
2243 quantize_info->measure_error=MagickFalse;
2244 quantize_info->signature=MagickSignature;
2248 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2252 % P o s t e r i z e I m a g e C h a n n e l %
2256 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2258 % PosterizeImage() reduces the image to a limited number of colors for a
2261 % The format of the PosterizeImage method is:
2263 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2264 % const MagickBooleanType dither)
2265 % MagickBooleanType PosterizeImageChannel(Image *image,
2266 % const ChannelType channel,const size_t levels,
2267 % const MagickBooleanType dither)
2269 % A description of each parameter follows:
2271 % o image: Specifies a pointer to an Image structure.
2273 % o levels: Number of color levels allowed in each channel. Very low values
2274 % (2, 3, or 4) have the most visible effect.
2276 % o dither: Set this integer value to something other than zero to dither
2281 static inline ssize_t MagickRound(MagickRealType x)
2284 Round the fraction to nearest integer.
2287 return((ssize_t) (x+0.5));
2288 return((ssize_t) (x-0.5));
2291 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2292 const MagickBooleanType dither)
2297 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2301 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2302 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2304 #define PosterizeImageTag "Posterize/Image"
2305 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2306 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2329 assert(image != (Image *) NULL);
2330 assert(image->signature == MagickSignature);
2331 if (image->debug != MagickFalse)
2332 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2333 if (image->storage_class == PseudoClass)
2334 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2335 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2337 for (i=0; i < (ssize_t) image->colors; i++)
2342 if ((channel & RedChannel) != 0)
2343 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2344 if ((channel & GreenChannel) != 0)
2345 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2346 if ((channel & BlueChannel) != 0)
2347 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2348 if ((channel & OpacityChannel) != 0)
2349 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2356 exception=(&image->exception);
2357 image_view=AcquireCacheView(image);
2358 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2359 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2361 for (y=0; y < (ssize_t) image->rows; y++)
2363 register IndexPacket
2366 register PixelPacket
2372 if (status == MagickFalse)
2374 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2375 if (q == (PixelPacket *) NULL)
2380 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2381 for (x=0; x < (ssize_t) image->columns; x++)
2383 if ((channel & RedChannel) != 0)
2384 SetRedPixelComponent(q,PosterizePixel(GetRedPixelComponent(q)));
2385 if ((channel & GreenChannel) != 0)
2386 SetGreenPixelComponent(q,PosterizePixel(GetGreenPixelComponent(q)));
2387 if ((channel & BlueChannel) != 0)
2388 SetBluePixelComponent(q,PosterizePixel(GetBluePixelComponent(q)));
2389 if (((channel & OpacityChannel) != 0) &&
2390 (image->matte == MagickTrue))
2391 SetOpacityPixelComponent(q,PosterizePixel(GetOpacityPixelComponent(q)));
2392 if (((channel & IndexChannel) != 0) &&
2393 (image->colorspace == CMYKColorspace))
2394 SetIndexPixelComponent(indexes+x,PosterizePixel(
2395 GetIndexPixelComponent(indexes+x)));
2398 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2400 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2405 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2406 #pragma omp critical (MagickCore_PosterizeImageChannel)
2408 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2410 if (proceed == MagickFalse)
2414 image_view=DestroyCacheView(image_view);
2415 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2416 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2417 levels,MaxColormapSize+1);
2418 quantize_info->dither=dither;
2419 quantize_info->tree_depth=MaxTreeDepth;
2420 status=QuantizeImage(quantize_info,image);
2421 quantize_info=DestroyQuantizeInfo(quantize_info);
2426 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2430 + P r u n e C h i l d %
2434 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2436 % PruneChild() deletes the given node and merges its statistics into its
2439 % The format of the PruneSubtree method is:
2441 % PruneChild(const Image *image,CubeInfo *cube_info,
2442 % const NodeInfo *node_info)
2444 % A description of each parameter follows.
2446 % o image: the image.
2448 % o cube_info: A pointer to the Cube structure.
2450 % o node_info: pointer to node in color cube tree that is to be pruned.
2453 static void PruneChild(const Image *image,CubeInfo *cube_info,
2454 const NodeInfo *node_info)
2466 Traverse any children.
2468 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2469 for (i=0; i < (ssize_t) number_children; i++)
2470 if (node_info->child[i] != (NodeInfo *) NULL)
2471 PruneChild(image,cube_info,node_info->child[i]);
2473 Merge color statistics into parent.
2475 parent=node_info->parent;
2476 parent->number_unique+=node_info->number_unique;
2477 parent->total_color.red+=node_info->total_color.red;
2478 parent->total_color.green+=node_info->total_color.green;
2479 parent->total_color.blue+=node_info->total_color.blue;
2480 parent->total_color.opacity+=node_info->total_color.opacity;
2481 parent->child[node_info->id]=(NodeInfo *) NULL;
2486 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2490 + P r u n e L e v e l %
2494 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2496 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2497 % their color statistics into their parent node.
2499 % The format of the PruneLevel method is:
2501 % PruneLevel(const Image *image,CubeInfo *cube_info,
2502 % const NodeInfo *node_info)
2504 % A description of each parameter follows.
2506 % o image: the image.
2508 % o cube_info: A pointer to the Cube structure.
2510 % o node_info: pointer to node in color cube tree that is to be pruned.
2513 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2514 const NodeInfo *node_info)
2523 Traverse any children.
2525 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2526 for (i=0; i < (ssize_t) number_children; i++)
2527 if (node_info->child[i] != (NodeInfo *) NULL)
2528 PruneLevel(image,cube_info,node_info->child[i]);
2529 if (node_info->level == cube_info->depth)
2530 PruneChild(image,cube_info,node_info);
2534 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2538 + P r u n e T o C u b e D e p t h %
2542 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2544 % PruneToCubeDepth() deletes any nodes at a depth greater than
2545 % cube_info->depth while merging their color statistics into their parent
2548 % The format of the PruneToCubeDepth method is:
2550 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2551 % const NodeInfo *node_info)
2553 % A description of each parameter follows.
2555 % o cube_info: A pointer to the Cube structure.
2557 % o node_info: pointer to node in color cube tree that is to be pruned.
2560 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2561 const NodeInfo *node_info)
2570 Traverse any children.
2572 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2573 for (i=0; i < (ssize_t) number_children; i++)
2574 if (node_info->child[i] != (NodeInfo *) NULL)
2575 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2576 if (node_info->level > cube_info->depth)
2577 PruneChild(image,cube_info,node_info);
2581 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2585 % Q u a n t i z e I m a g e %
2589 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2591 % QuantizeImage() analyzes the colors within a reference image and chooses a
2592 % fixed number of colors to represent the image. The goal of the algorithm
2593 % is to minimize the color difference between the input and output image while
2594 % minimizing the processing time.
2596 % The format of the QuantizeImage method is:
2598 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2601 % A description of each parameter follows:
2603 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2605 % o image: the image.
2608 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2621 assert(quantize_info != (const QuantizeInfo *) NULL);
2622 assert(quantize_info->signature == MagickSignature);
2623 assert(image != (Image *) NULL);
2624 assert(image->signature == MagickSignature);
2625 if (image->debug != MagickFalse)
2626 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2627 maximum_colors=quantize_info->number_colors;
2628 if (maximum_colors == 0)
2629 maximum_colors=MaxColormapSize;
2630 if (maximum_colors > MaxColormapSize)
2631 maximum_colors=MaxColormapSize;
2632 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2633 (image->matte == MagickFalse))
2634 (void) SetGrayscaleImage(image);
2635 if ((image->storage_class == PseudoClass) &&
2636 (image->colors <= maximum_colors))
2638 depth=quantize_info->tree_depth;
2645 Depth of color tree is: Log4(colormap size)+2.
2647 colors=maximum_colors;
2648 for (depth=1; colors != 0; depth++)
2650 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2652 if ((image->matte != MagickFalse) && (depth > 5))
2656 Initialize color cube.
2658 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2659 if (cube_info == (CubeInfo *) NULL)
2660 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2662 status=ClassifyImageColors(cube_info,image,&image->exception);
2663 if (status != MagickFalse)
2666 Reduce the number of colors in the image.
2668 ReduceImageColors(image,cube_info);
2669 status=AssignImageColors(image,cube_info);
2671 DestroyCubeInfo(cube_info);
2676 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2680 % Q u a n t i z e I m a g e s %
2684 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2686 % QuantizeImages() analyzes the colors within a set of reference images and
2687 % chooses a fixed number of colors to represent the set. The goal of the
2688 % algorithm is to minimize the color difference between the input and output
2689 % images while minimizing the processing time.
2691 % The format of the QuantizeImages method is:
2693 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2696 % A description of each parameter follows:
2698 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2700 % o images: Specifies a pointer to a list of Image structures.
2703 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2716 MagickProgressMonitor
2727 assert(quantize_info != (const QuantizeInfo *) NULL);
2728 assert(quantize_info->signature == MagickSignature);
2729 assert(images != (Image *) NULL);
2730 assert(images->signature == MagickSignature);
2731 if (images->debug != MagickFalse)
2732 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2733 if (GetNextImageInList(images) == (Image *) NULL)
2736 Handle a single image with QuantizeImage.
2738 status=QuantizeImage(quantize_info,images);
2742 maximum_colors=quantize_info->number_colors;
2743 if (maximum_colors == 0)
2744 maximum_colors=MaxColormapSize;
2745 if (maximum_colors > MaxColormapSize)
2746 maximum_colors=MaxColormapSize;
2747 depth=quantize_info->tree_depth;
2754 Depth of color tree is: Log4(colormap size)+2.
2756 colors=maximum_colors;
2757 for (depth=1; colors != 0; depth++)
2759 if (quantize_info->dither != MagickFalse)
2763 Initialize color cube.
2765 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2766 if (cube_info == (CubeInfo *) NULL)
2768 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2769 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2770 return(MagickFalse);
2772 number_images=GetImageListLength(images);
2774 for (i=0; image != (Image *) NULL; i++)
2776 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2777 image->client_data);
2778 status=ClassifyImageColors(cube_info,image,&image->exception);
2779 if (status == MagickFalse)
2781 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2782 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2784 if (proceed == MagickFalse)
2786 image=GetNextImageInList(image);
2788 if (status != MagickFalse)
2791 Reduce the number of colors in an image sequence.
2793 ReduceImageColors(images,cube_info);
2795 for (i=0; image != (Image *) NULL; i++)
2797 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2798 NULL,image->client_data);
2799 status=AssignImageColors(image,cube_info);
2800 if (status == MagickFalse)
2802 (void) SetImageProgressMonitor(image,progress_monitor,
2803 image->client_data);
2804 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2806 if (proceed == MagickFalse)
2808 image=GetNextImageInList(image);
2811 DestroyCubeInfo(cube_info);
2816 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2824 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2826 % Reduce() traverses the color cube tree and prunes any node whose
2827 % quantization error falls below a particular threshold.
2829 % The format of the Reduce method is:
2831 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2833 % A description of each parameter follows.
2835 % o image: the image.
2837 % o cube_info: A pointer to the Cube structure.
2839 % o node_info: pointer to node in color cube tree that is to be pruned.
2842 static void Reduce(const Image *image,CubeInfo *cube_info,
2843 const NodeInfo *node_info)
2852 Traverse any children.
2854 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2855 for (i=0; i < (ssize_t) number_children; i++)
2856 if (node_info->child[i] != (NodeInfo *) NULL)
2857 Reduce(image,cube_info,node_info->child[i]);
2858 if (node_info->quantize_error <= cube_info->pruning_threshold)
2859 PruneChild(image,cube_info,node_info);
2863 Find minimum pruning threshold.
2865 if (node_info->number_unique > 0)
2866 cube_info->colors++;
2867 if (node_info->quantize_error < cube_info->next_threshold)
2868 cube_info->next_threshold=node_info->quantize_error;
2873 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2877 + R e d u c e I m a g e C o l o r s %
2881 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2883 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2884 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2885 % in the output image. On any given iteration over the tree, it selects
2886 % those nodes whose E value is minimal for pruning and merges their
2887 % color statistics upward. It uses a pruning threshold, Ep, to govern
2888 % node selection as follows:
2891 % while number of nodes with (n2 > 0) > required maximum number of colors
2892 % prune all nodes such that E <= Ep
2893 % Set Ep to minimum E in remaining nodes
2895 % This has the effect of minimizing any quantization error when merging
2896 % two nodes together.
2898 % When a node to be pruned has offspring, the pruning procedure invokes
2899 % itself recursively in order to prune the tree from the leaves upward.
2900 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2901 % corresponding data in that node's parent. This retains the pruned
2902 % node's color characteristics for later averaging.
2904 % For each node, n2 pixels exist for which that node represents the
2905 % smallest volume in RGB space containing those pixel's colors. When n2
2906 % > 0 the node will uniquely define a color in the output image. At the
2907 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2908 % the tree which represent colors present in the input image.
2910 % The other pixel count, n1, indicates the total number of colors
2911 % within the cubic volume which the node represents. This includes n1 -
2912 % n2 pixels whose colors should be defined by nodes at a lower level in
2915 % The format of the ReduceImageColors method is:
2917 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2919 % A description of each parameter follows.
2921 % o image: the image.
2923 % o cube_info: A pointer to the Cube structure.
2926 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2928 #define ReduceImageTag "Reduce/Image"
2939 cube_info->next_threshold=0.0;
2940 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2942 cube_info->pruning_threshold=cube_info->next_threshold;
2943 cube_info->next_threshold=cube_info->root->quantize_error-1;
2944 cube_info->colors=0;
2945 Reduce(image,cube_info,cube_info->root);
2946 offset=(MagickOffsetType) span-cube_info->colors;
2947 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2948 cube_info->maximum_colors+1);
2949 if (proceed == MagickFalse)
2955 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2959 % R e m a p I m a g e %
2963 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2965 % RemapImage() replaces the colors of an image with the closest color from
2966 % a reference image.
2968 % The format of the RemapImage method is:
2970 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2971 % Image *image,const Image *remap_image)
2973 % A description of each parameter follows:
2975 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2977 % o image: the image.
2979 % o remap_image: the reference image.
2982 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2983 Image *image,const Image *remap_image)
2992 Initialize color cube.
2994 assert(image != (Image *) NULL);
2995 assert(image->signature == MagickSignature);
2996 if (image->debug != MagickFalse)
2997 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2998 assert(remap_image != (Image *) NULL);
2999 assert(remap_image->signature == MagickSignature);
3000 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3001 quantize_info->number_colors);
3002 if (cube_info == (CubeInfo *) NULL)
3003 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3005 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3006 if (status != MagickFalse)
3009 Classify image colors from the reference image.
3011 cube_info->quantize_info->number_colors=cube_info->colors;
3012 status=AssignImageColors(image,cube_info);
3014 DestroyCubeInfo(cube_info);
3019 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3023 % R e m a p I m a g e s %
3027 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3029 % RemapImages() replaces the colors of a sequence of images with the
3030 % closest color from a reference image.
3032 % The format of the RemapImage method is:
3034 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3035 % Image *images,Image *remap_image)
3037 % A description of each parameter follows:
3039 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3041 % o images: the image sequence.
3043 % o remap_image: the reference image.
3046 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3047 Image *images,const Image *remap_image)
3058 assert(images != (Image *) NULL);
3059 assert(images->signature == MagickSignature);
3060 if (images->debug != MagickFalse)
3061 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3063 if (remap_image == (Image *) NULL)
3066 Create a global colormap for an image sequence.
3068 status=QuantizeImages(quantize_info,images);
3072 Classify image colors from the reference image.
3074 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3075 quantize_info->number_colors);
3076 if (cube_info == (CubeInfo *) NULL)
3077 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3079 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3080 if (status != MagickFalse)
3083 Classify image colors from the reference image.
3085 cube_info->quantize_info->number_colors=cube_info->colors;
3087 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3089 status=AssignImageColors(image,cube_info);
3090 if (status == MagickFalse)
3094 DestroyCubeInfo(cube_info);
3099 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3103 % S e t G r a y s c a l e I m a g e %
3107 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3109 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3111 % The format of the SetGrayscaleImage method is:
3113 % MagickBooleanType SetGrayscaleImage(Image *image)
3115 % A description of each parameter follows:
3117 % o image: The image.
3121 #if defined(__cplusplus) || defined(c_plusplus)
3125 static int IntensityCompare(const void *x,const void *y)
3134 color_1=(PixelPacket *) x;
3135 color_2=(PixelPacket *) y;
3136 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3137 PixelIntensityToQuantum(color_2);
3138 return((int) intensity);
3141 #if defined(__cplusplus) || defined(c_plusplus)
3145 static MagickBooleanType SetGrayscaleImage(Image *image)
3167 assert(image != (Image *) NULL);
3168 assert(image->signature == MagickSignature);
3169 if (image->type != GrayscaleType)
3170 (void) TransformImageColorspace(image,GRAYColorspace);
3171 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3172 sizeof(*colormap_index));
3173 if (colormap_index == (ssize_t *) NULL)
3174 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3176 if (image->storage_class != PseudoClass)
3181 for (i=0; i <= (ssize_t) MaxMap; i++)
3182 colormap_index[i]=(-1);
3183 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3184 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3188 exception=(&image->exception);
3189 image_view=AcquireCacheView(image);
3190 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3191 #pragma omp parallel for schedule(dynamic,4) shared(status)
3193 for (y=0; y < (ssize_t) image->rows; y++)
3195 register IndexPacket
3198 register const PixelPacket
3204 if (status == MagickFalse)
3206 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3208 if (q == (PixelPacket *) NULL)
3213 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3214 for (x=0; x < (ssize_t) image->columns; x++)
3219 intensity=ScaleQuantumToMap(GetRedPixelComponent(q));
3220 if (colormap_index[intensity] < 0)
3222 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3223 #pragma omp critical (MagickCore_SetGrayscaleImage)
3225 if (colormap_index[intensity] < 0)
3227 colormap_index[intensity]=(ssize_t) image->colors;
3228 image->colormap[image->colors].red=GetRedPixelComponent(q);
3229 image->colormap[image->colors].green=
3230 GetGreenPixelComponent(q);
3231 image->colormap[image->colors].blue=GetBluePixelComponent(q);
3235 SetIndexPixelComponent(indexes+x,colormap_index[intensity]);
3238 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3241 image_view=DestroyCacheView(image_view);
3243 for (i=0; i < (ssize_t) image->colors; i++)
3244 image->colormap[i].opacity=(unsigned short) i;
3245 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3247 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3249 if (colormap == (PixelPacket *) NULL)
3250 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3253 colormap[j]=image->colormap[0];
3254 for (i=0; i < (ssize_t) image->colors; i++)
3256 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3259 colormap[j]=image->colormap[i];
3261 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3263 image->colors=(size_t) (j+1);
3264 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3265 image->colormap=colormap;
3267 exception=(&image->exception);
3268 image_view=AcquireCacheView(image);
3269 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3270 #pragma omp parallel for schedule(dynamic,4) shared(status)
3272 for (y=0; y < (ssize_t) image->rows; y++)
3274 register IndexPacket
3277 register const PixelPacket
3283 if (status == MagickFalse)
3285 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3286 if (q == (PixelPacket *) NULL)
3291 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3292 for (x=0; x < (ssize_t) image->columns; x++)
3293 SetIndexPixelComponent(indexes+x,colormap_index[ScaleQuantumToMap(
3294 GetIndexPixelComponent(indexes+x))]);
3295 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3298 image_view=DestroyCacheView(image_view);
3299 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3300 image->type=GrayscaleType;
3301 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3302 image->type=BilevelType;