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) pixel->red;
439 alpha_pixel->green=(MagickRealType) pixel->green;
440 alpha_pixel->blue=(MagickRealType) pixel->blue;
441 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
444 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
445 alpha_pixel->red=alpha*pixel->red;
446 alpha_pixel->green=alpha*pixel->green;
447 alpha_pixel->blue=alpha*pixel->blue;
448 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
451 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
455 if (value >= QuantumRange)
456 return((Quantum) QuantumRange);
457 return((Quantum) (value+0.5));
460 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
461 const RealPixelPacket *pixel,size_t index)
467 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
468 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
469 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
470 if (cube_info->associate_alpha != MagickFalse)
471 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
476 static inline MagickBooleanType IsSameColor(const Image *image,
477 const PixelPacket *p,const PixelPacket *q)
479 if ((GetRedPixelComponent(p) != q->red) || (GetGreenPixelComponent(p) != q->green) || (GetBluePixelComponent(p) != q->blue))
481 if ((image->matte != MagickFalse) && (GetOpacityPixelComponent(p) != q->opacity))
486 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
488 #define AssignImageTag "Assign/Image"
494 Allocate image colormap.
496 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
497 (cube_info->quantize_info->colorspace != CMYKColorspace))
498 (void) TransformImageColorspace((Image *) image,
499 cube_info->quantize_info->colorspace);
501 if ((image->colorspace != GRAYColorspace) &&
502 (image->colorspace != RGBColorspace) &&
503 (image->colorspace != CMYColorspace))
504 (void) TransformImageColorspace((Image *) image,RGBColorspace);
505 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
506 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
509 cube_info->transparent_pixels=0;
510 cube_info->transparent_index=(-1);
511 (void) DefineImageColormap(image,cube_info,cube_info->root);
513 Create a reduced color image.
515 if ((cube_info->quantize_info->dither != MagickFalse) &&
516 (cube_info->quantize_info->dither_method != NoDitherMethod))
517 (void) DitherImage(image,cube_info);
530 exception=(&image->exception);
531 image_view=AcquireCacheView(image);
532 #if defined(MAGICKCORE_OPENMP_SUPPORT)
533 #pragma omp parallel for schedule(dynamic,4) shared(status)
535 for (y=0; y < (ssize_t) image->rows; y++)
552 if (status == MagickFalse)
554 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
556 if (q == (PixelPacket *) NULL)
561 indexes=GetCacheViewAuthenticIndexQueue(image_view);
563 for (x=0; x < (ssize_t) image->columns; x+=count)
568 register const NodeInfo
579 Identify the deepest node containing the pixel's color.
581 for (count=1; (x+count) < (ssize_t) image->columns; count++)
582 if (IsSameColor(image,q,q+count) == MagickFalse)
584 AssociateAlphaPixel(&cube,q,&pixel);
586 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
588 id=ColorToNodeId(&cube,&pixel,index);
589 if (node_info->child[id] == (NodeInfo *) NULL)
591 node_info=node_info->child[id];
594 Find closest color among siblings and their children.
597 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
598 (QuantumRange+1.0)+1.0);
599 ClosestColor(image,&cube,node_info->parent);
600 index=cube.color_number;
601 for (i=0; i < (ssize_t) count; i++)
603 if (image->storage_class == PseudoClass)
604 indexes[x+i]=(IndexPacket) index;
605 if (cube.quantize_info->measure_error == MagickFalse)
607 q->red=image->colormap[index].red;
608 q->green=image->colormap[index].green;
609 q->blue=image->colormap[index].blue;
610 if (cube.associate_alpha != MagickFalse)
611 q->opacity=image->colormap[index].opacity;
616 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
618 if (image->progress_monitor != (MagickProgressMonitor) NULL)
623 #if defined(MAGICKCORE_OPENMP_SUPPORT)
624 #pragma omp critical (MagickCore_AssignImageColors)
626 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
628 if (proceed == MagickFalse)
632 image_view=DestroyCacheView(image_view);
634 if (cube_info->quantize_info->measure_error != MagickFalse)
635 (void) GetImageQuantizeError(image);
636 if ((cube_info->quantize_info->number_colors == 2) &&
637 (cube_info->quantize_info->colorspace == GRAYColorspace))
652 for (i=0; i < (ssize_t) image->colors; i++)
654 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
655 QuantumRange/2.0) ? 0 : QuantumRange);
662 (void) SyncImage(image);
663 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
664 (cube_info->quantize_info->colorspace != CMYKColorspace))
665 (void) TransformImageColorspace((Image *) image,RGBColorspace);
670 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
674 + C l a s s i f y I m a g e C o l o r s %
678 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
680 % ClassifyImageColors() begins by initializing a color description tree
681 % of sufficient depth to represent each possible input color in a leaf.
682 % However, it is impractical to generate a fully-formed color
683 % description tree in the storage_class phase for realistic values of
684 % Cmax. If colors components in the input image are quantized to k-bit
685 % precision, so that Cmax= 2k-1, the tree would need k levels below the
686 % root node to allow representing each possible input color in a leaf.
687 % This becomes prohibitive because the tree's total number of nodes is
690 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
691 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
692 % Initializes data structures for nodes only as they are needed; (2)
693 % Chooses a maximum depth for the tree as a function of the desired
694 % number of colors in the output image (currently log2(colormap size)).
696 % For each pixel in the input image, storage_class scans downward from
697 % the root of the color description tree. At each level of the tree it
698 % identifies the single node which represents a cube in RGB space
699 % containing It updates the following data for each such node:
701 % n1 : Number of pixels whose color is contained in the RGB cube
702 % which this node represents;
704 % n2 : Number of pixels whose color is not represented in a node at
705 % lower depth in the tree; initially, n2 = 0 for all nodes except
706 % leaves of the tree.
708 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
709 % all pixels not classified at a lower depth. The combination of
710 % these sums and n2 will ultimately characterize the mean color of a
711 % set of pixels represented by this node.
713 % E: the distance squared in RGB space between each pixel contained
714 % within a node and the nodes' center. This represents the quantization
717 % The format of the ClassifyImageColors() method is:
719 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
720 % const Image *image,ExceptionInfo *exception)
722 % A description of each parameter follows.
724 % o cube_info: A pointer to the Cube structure.
726 % o image: the image.
730 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
735 associate_alpha=image->matte;
736 if (cube_info->quantize_info->colorspace == TransparentColorspace)
737 associate_alpha=MagickFalse;
738 if ((cube_info->quantize_info->number_colors == 2) &&
739 (cube_info->quantize_info->colorspace == GRAYColorspace))
740 associate_alpha=MagickFalse;
741 cube_info->associate_alpha=associate_alpha;
744 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
745 const Image *image,ExceptionInfo *exception)
747 #define ClassifyImageTag "Classify/Image"
777 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
779 SetAssociatedAlpha(image,cube_info);
780 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
781 (cube_info->quantize_info->colorspace != CMYKColorspace))
782 (void) TransformImageColorspace((Image *) image,
783 cube_info->quantize_info->colorspace);
785 if ((image->colorspace != GRAYColorspace) &&
786 (image->colorspace != CMYColorspace) &&
787 (image->colorspace != RGBColorspace))
788 (void) TransformImageColorspace((Image *) image,RGBColorspace);
789 midpoint.red=(MagickRealType) QuantumRange/2.0;
790 midpoint.green=(MagickRealType) QuantumRange/2.0;
791 midpoint.blue=(MagickRealType) QuantumRange/2.0;
792 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
794 image_view=AcquireCacheView(image);
795 for (y=0; y < (ssize_t) image->rows; y++)
797 register const PixelPacket
803 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
804 if (p == (const PixelPacket *) NULL)
806 if (cube_info->nodes > MaxNodes)
809 Prune one level if the color tree is too large.
811 PruneLevel(image,cube_info,cube_info->root);
814 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
817 Start at the root and descend the color cube tree.
819 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
820 if (IsSameColor(image,p,p+count) == MagickFalse)
822 AssociateAlphaPixel(cube_info,p,&pixel);
823 index=MaxTreeDepth-1;
824 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
826 node_info=cube_info->root;
827 for (level=1; level <= MaxTreeDepth; level++)
830 id=ColorToNodeId(cube_info,&pixel,index);
831 mid.red+=(id & 1) != 0 ? bisect : -bisect;
832 mid.green+=(id & 2) != 0 ? bisect : -bisect;
833 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
834 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
835 if (node_info->child[id] == (NodeInfo *) NULL)
838 Set colors of new node to contain pixel.
840 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
841 if (node_info->child[id] == (NodeInfo *) NULL)
842 (void) ThrowMagickException(exception,GetMagickModule(),
843 ResourceLimitError,"MemoryAllocationFailed","`%s'",
845 if (level == MaxTreeDepth)
849 Approximate the quantization error represented by this node.
851 node_info=node_info->child[id];
852 error.red=QuantumScale*(pixel.red-mid.red);
853 error.green=QuantumScale*(pixel.green-mid.green);
854 error.blue=QuantumScale*(pixel.blue-mid.blue);
855 if (cube_info->associate_alpha != MagickFalse)
856 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
857 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
858 count*error.green*error.green+count*error.blue*error.blue+
859 count*error.opacity*error.opacity));
860 cube_info->root->quantize_error+=node_info->quantize_error;
864 Sum RGB for this leaf for later derivation of the mean cube color.
866 node_info->number_unique+=count;
867 node_info->total_color.red+=count*QuantumScale*pixel.red;
868 node_info->total_color.green+=count*QuantumScale*pixel.green;
869 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
870 if (cube_info->associate_alpha != MagickFalse)
871 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
874 if (cube_info->colors > cube_info->maximum_colors)
876 PruneToCubeDepth(image,cube_info,cube_info->root);
879 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
881 if (proceed == MagickFalse)
884 for (y++; y < (ssize_t) image->rows; y++)
886 register const PixelPacket
892 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
893 if (p == (const PixelPacket *) NULL)
895 if (cube_info->nodes > MaxNodes)
898 Prune one level if the color tree is too large.
900 PruneLevel(image,cube_info,cube_info->root);
903 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
906 Start at the root and descend the color cube tree.
908 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
909 if (IsSameColor(image,p,p+count) == MagickFalse)
911 AssociateAlphaPixel(cube_info,p,&pixel);
912 index=MaxTreeDepth-1;
913 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
915 node_info=cube_info->root;
916 for (level=1; level <= cube_info->depth; level++)
919 id=ColorToNodeId(cube_info,&pixel,index);
920 mid.red+=(id & 1) != 0 ? bisect : -bisect;
921 mid.green+=(id & 2) != 0 ? bisect : -bisect;
922 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
923 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
924 if (node_info->child[id] == (NodeInfo *) NULL)
927 Set colors of new node to contain pixel.
929 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
930 if (node_info->child[id] == (NodeInfo *) NULL)
931 (void) ThrowMagickException(exception,GetMagickModule(),
932 ResourceLimitError,"MemoryAllocationFailed","%s",
934 if (level == cube_info->depth)
938 Approximate the quantization error represented by this node.
940 node_info=node_info->child[id];
941 error.red=QuantumScale*(pixel.red-mid.red);
942 error.green=QuantumScale*(pixel.green-mid.green);
943 error.blue=QuantumScale*(pixel.blue-mid.blue);
944 if (cube_info->associate_alpha != MagickFalse)
945 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
946 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
947 count*error.green*error.green+count*error.blue*error.blue+
948 count*error.opacity*error.opacity));
949 cube_info->root->quantize_error+=node_info->quantize_error;
953 Sum RGB for this leaf for later derivation of the mean cube color.
955 node_info->number_unique+=count;
956 node_info->total_color.red+=count*QuantumScale*pixel.red;
957 node_info->total_color.green+=count*QuantumScale*pixel.green;
958 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
959 if (cube_info->associate_alpha != MagickFalse)
960 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
963 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
965 if (proceed == MagickFalse)
968 image_view=DestroyCacheView(image_view);
969 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
970 (cube_info->quantize_info->colorspace != CMYKColorspace))
971 (void) TransformImageColorspace((Image *) image,RGBColorspace);
976 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
980 % C l o n e Q u a n t i z e I n f o %
984 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
986 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
987 % or if quantize info is NULL, a new one.
989 % The format of the CloneQuantizeInfo method is:
991 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
993 % A description of each parameter follows:
995 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
996 % quantize info, or if image info is NULL a new one.
998 % o quantize_info: a structure of type info.
1001 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1006 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1007 if (clone_info == (QuantizeInfo *) NULL)
1008 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1009 GetQuantizeInfo(clone_info);
1010 if (quantize_info == (QuantizeInfo *) NULL)
1012 clone_info->number_colors=quantize_info->number_colors;
1013 clone_info->tree_depth=quantize_info->tree_depth;
1014 clone_info->dither=quantize_info->dither;
1015 clone_info->dither_method=quantize_info->dither_method;
1016 clone_info->colorspace=quantize_info->colorspace;
1017 clone_info->measure_error=quantize_info->measure_error;
1022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1026 + C l o s e s t C o l o r %
1030 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032 % ClosestColor() traverses the color cube tree at a particular node and
1033 % determines which colormap entry best represents the input color.
1035 % The format of the ClosestColor method is:
1037 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1038 % const NodeInfo *node_info)
1040 % A description of each parameter follows.
1042 % o image: the image.
1044 % o cube_info: A pointer to the Cube structure.
1046 % o node_info: the address of a structure of type NodeInfo which points to a
1047 % node in the color cube tree that is to be pruned.
1050 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1051 const NodeInfo *node_info)
1060 Traverse any children.
1062 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1063 for (i=0; i < (ssize_t) number_children; i++)
1064 if (node_info->child[i] != (NodeInfo *) NULL)
1065 ClosestColor(image,cube_info,node_info->child[i]);
1066 if (node_info->number_unique != 0)
1071 register MagickRealType
1076 register PixelPacket
1079 register RealPixelPacket
1083 Determine if this color is "closest".
1085 p=image->colormap+node_info->color_number;
1086 q=(&cube_info->target);
1089 if (cube_info->associate_alpha != MagickFalse)
1091 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1092 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1094 pixel=alpha*GetRedPixelComponent(p)-beta*q->red;
1095 distance=pixel*pixel;
1096 if (distance <= cube_info->distance)
1098 pixel=alpha*GetGreenPixelComponent(p)-beta*q->green;
1099 distance+=pixel*pixel;
1100 if (distance <= cube_info->distance)
1102 pixel=alpha*GetBluePixelComponent(p)-beta*q->blue;
1103 distance+=pixel*pixel;
1104 if (distance <= cube_info->distance)
1107 distance+=pixel*pixel;
1108 if (distance <= cube_info->distance)
1110 cube_info->distance=distance;
1111 cube_info->color_number=node_info->color_number;
1120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1124 % C o m p r e s s I m a g e C o l o r m a p %
1128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1130 % CompressImageColormap() compresses an image colormap by removing any
1131 % duplicate or unused color entries.
1133 % The format of the CompressImageColormap method is:
1135 % MagickBooleanType CompressImageColormap(Image *image)
1137 % A description of each parameter follows:
1139 % o image: the image.
1142 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1147 assert(image != (Image *) NULL);
1148 assert(image->signature == MagickSignature);
1149 if (image->debug != MagickFalse)
1150 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1151 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1152 return(MagickFalse);
1153 GetQuantizeInfo(&quantize_info);
1154 quantize_info.number_colors=image->colors;
1155 quantize_info.tree_depth=MaxTreeDepth;
1156 return(QuantizeImage(&quantize_info,image));
1160 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1164 + D e f i n e I m a g e C o l o r m a p %
1168 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1170 % DefineImageColormap() traverses the color cube tree and notes each colormap
1171 % entry. A colormap entry is any node in the color cube tree where the
1172 % of unique colors is not zero. DefineImageColormap() returns the number of
1173 % colors in the image colormap.
1175 % The format of the DefineImageColormap method is:
1177 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1178 % NodeInfo *node_info)
1180 % A description of each parameter follows.
1182 % o image: the image.
1184 % o cube_info: A pointer to the Cube structure.
1186 % o node_info: the address of a structure of type NodeInfo which points to a
1187 % node in the color cube tree that is to be pruned.
1190 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1191 NodeInfo *node_info)
1200 Traverse any children.
1202 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1203 for (i=0; i < (ssize_t) number_children; i++)
1204 if (node_info->child[i] != (NodeInfo *) NULL)
1205 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1206 if (node_info->number_unique != 0)
1208 register MagickRealType
1211 register PixelPacket
1215 Colormap entry is defined by the mean color in this cube.
1217 q=image->colormap+image->colors;
1218 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1219 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1220 if (cube_info->associate_alpha == MagickFalse)
1222 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1223 node_info->total_color.red));
1224 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1225 node_info->total_color.green));
1226 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1227 node_info->total_color.blue));
1228 SetOpacityPixelComponent(q,OpaqueOpacity);
1235 opacity=(MagickRealType) (alpha*QuantumRange*
1236 node_info->total_color.opacity);
1237 q->opacity=ClampToQuantum(opacity);
1238 if (q->opacity == OpaqueOpacity)
1240 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1241 node_info->total_color.red));
1242 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1243 node_info->total_color.green));
1244 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
1245 node_info->total_color.blue));
1252 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1253 (MagickRealType) q->opacity));
1254 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1255 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1256 node_info->total_color.red));
1257 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
1258 QuantumRange*node_info->total_color.green));
1259 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
1260 node_info->total_color.blue));
1261 if (node_info->number_unique > cube_info->transparent_pixels)
1263 cube_info->transparent_pixels=node_info->number_unique;
1264 cube_info->transparent_index=(ssize_t) image->colors;
1268 node_info->color_number=image->colors++;
1270 return(image->colors);
1274 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1278 + D e s t r o y C u b e I n f o %
1282 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1284 % DestroyCubeInfo() deallocates memory associated with an image.
1286 % The format of the DestroyCubeInfo method is:
1288 % DestroyCubeInfo(CubeInfo *cube_info)
1290 % A description of each parameter follows:
1292 % o cube_info: the address of a structure of type CubeInfo.
1295 static void DestroyCubeInfo(CubeInfo *cube_info)
1301 Release color cube tree storage.
1305 nodes=cube_info->node_queue->next;
1306 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1307 cube_info->node_queue->nodes);
1308 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1309 cube_info->node_queue);
1310 cube_info->node_queue=nodes;
1311 } while (cube_info->node_queue != (Nodes *) NULL);
1312 if (cube_info->cache != (ssize_t *) NULL)
1313 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1314 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1315 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1319 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1323 % D e s t r o y Q u a n t i z e I n f o %
1327 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1329 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1332 % The format of the DestroyQuantizeInfo method is:
1334 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1336 % A description of each parameter follows:
1338 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1341 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1343 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1344 assert(quantize_info != (QuantizeInfo *) NULL);
1345 assert(quantize_info->signature == MagickSignature);
1346 quantize_info->signature=(~MagickSignature);
1347 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1348 return(quantize_info);
1352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1356 + D i t h e r I m a g e %
1360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1362 % DitherImage() distributes the difference between an original image and
1363 % the corresponding color reduced algorithm to neighboring pixels using
1364 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1365 % MagickTrue if the image is dithered otherwise MagickFalse.
1367 % The format of the DitherImage method is:
1369 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1371 % A description of each parameter follows.
1373 % o image: the image.
1375 % o cube_info: A pointer to the Cube structure.
1379 static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1384 assert(pixels != (RealPixelPacket **) NULL);
1385 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1386 if (pixels[i] != (RealPixelPacket *) NULL)
1387 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1388 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1392 static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1403 number_threads=GetOpenMPMaximumThreads();
1404 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1406 if (pixels == (RealPixelPacket **) NULL)
1407 return((RealPixelPacket **) NULL);
1408 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1409 for (i=0; i < (ssize_t) number_threads; i++)
1411 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1412 2*sizeof(**pixels));
1413 if (pixels[i] == (RealPixelPacket *) NULL)
1414 return(DestroyPixelThreadSet(pixels));
1419 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1420 const RealPixelPacket *pixel)
1422 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1423 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1424 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1425 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1431 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1432 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1433 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1434 if (cube_info->associate_alpha != MagickFalse)
1435 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1440 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1442 #define DitherImageTag "Dither/Image"
1460 Distribute quantization error using Floyd-Steinberg.
1462 pixels=AcquirePixelThreadSet(image->columns);
1463 if (pixels == (RealPixelPacket **) NULL)
1464 return(MagickFalse);
1465 exception=(&image->exception);
1467 image_view=AcquireCacheView(image);
1468 for (y=0; y < (ssize_t) image->rows; y++)
1471 id = GetOpenMPThreadId();
1480 register IndexPacket
1483 register PixelPacket
1495 if (status == MagickFalse)
1497 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1498 if (q == (PixelPacket *) NULL)
1503 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1505 current=pixels[id]+(y & 0x01)*image->columns;
1506 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1507 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1508 for (x=0; x < (ssize_t) image->columns; x++)
1520 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1521 AssociateAlphaPixel(&cube,q+u,&pixel);
1524 pixel.red+=7*current[u-v].red/16;
1525 pixel.green+=7*current[u-v].green/16;
1526 pixel.blue+=7*current[u-v].blue/16;
1527 if (cube.associate_alpha != MagickFalse)
1528 pixel.opacity+=7*current[u-v].opacity/16;
1532 if (x < (ssize_t) (image->columns-1))
1534 pixel.red+=previous[u+v].red/16;
1535 pixel.green+=previous[u+v].green/16;
1536 pixel.blue+=previous[u+v].blue/16;
1537 if (cube.associate_alpha != MagickFalse)
1538 pixel.opacity+=previous[u+v].opacity/16;
1540 pixel.red+=5*previous[u].red/16;
1541 pixel.green+=5*previous[u].green/16;
1542 pixel.blue+=5*previous[u].blue/16;
1543 if (cube.associate_alpha != MagickFalse)
1544 pixel.opacity+=5*previous[u].opacity/16;
1547 pixel.red+=3*previous[u-v].red/16;
1548 pixel.green+=3*previous[u-v].green/16;
1549 pixel.blue+=3*previous[u-v].blue/16;
1550 if (cube.associate_alpha != MagickFalse)
1551 pixel.opacity+=3*previous[u-v].opacity/16;
1554 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1555 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1556 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1557 if (cube.associate_alpha != MagickFalse)
1558 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1559 i=CacheOffset(&cube,&pixel);
1560 if (cube.cache[i] < 0)
1569 Identify the deepest node containing the pixel's color.
1571 node_info=cube.root;
1572 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1574 id=ColorToNodeId(&cube,&pixel,index);
1575 if (node_info->child[id] == (NodeInfo *) NULL)
1577 node_info=node_info->child[id];
1580 Find closest color among siblings and their children.
1583 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1585 ClosestColor(image,&cube,node_info->parent);
1586 cube.cache[i]=(ssize_t) cube.color_number;
1589 Assign pixel to closest colormap entry.
1591 index=(size_t) cube.cache[i];
1592 if (image->storage_class == PseudoClass)
1593 indexes[u]=(IndexPacket) index;
1594 if (cube.quantize_info->measure_error == MagickFalse)
1596 (q+u)->red=image->colormap[index].red;
1597 (q+u)->green=image->colormap[index].green;
1598 (q+u)->blue=image->colormap[index].blue;
1599 if (cube.associate_alpha != MagickFalse)
1600 (q+u)->opacity=image->colormap[index].opacity;
1602 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1607 AssociateAlphaPixel(&cube,image->colormap+index,&color);
1608 current[u].red=pixel.red-color.red;
1609 current[u].green=pixel.green-color.green;
1610 current[u].blue=pixel.blue-color.blue;
1611 if (cube.associate_alpha != MagickFalse)
1612 current[u].opacity=pixel.opacity-color.opacity;
1613 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1618 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1619 #pragma omp critical (MagickCore_FloydSteinbergDither)
1621 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1623 if (proceed == MagickFalse)
1628 image_view=DestroyCacheView(image_view);
1629 pixels=DestroyPixelThreadSet(pixels);
1633 static MagickBooleanType
1634 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1636 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1637 const size_t level,const unsigned int direction)
1644 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1645 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1646 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1651 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1652 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1653 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1658 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1659 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1660 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1665 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1666 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1667 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1678 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1679 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1680 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1681 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1682 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1683 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1684 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1689 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1690 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1691 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1692 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1693 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1694 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1695 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1700 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1701 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1702 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1703 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1704 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1705 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1706 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1711 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1712 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1713 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1714 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1715 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1716 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1717 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1725 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1726 CubeInfo *cube_info,const unsigned int direction)
1728 #define DitherImageTag "Dither/Image"
1744 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1745 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1750 register IndexPacket
1753 register PixelPacket
1762 exception=(&image->exception);
1763 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1764 if (q == (PixelPacket *) NULL)
1765 return(MagickFalse);
1766 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1767 AssociateAlphaPixel(cube_info,q,&pixel);
1768 for (i=0; i < ErrorQueueLength; i++)
1770 pixel.red+=p->weights[i]*p->error[i].red;
1771 pixel.green+=p->weights[i]*p->error[i].green;
1772 pixel.blue+=p->weights[i]*p->error[i].blue;
1773 if (cube_info->associate_alpha != MagickFalse)
1774 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1776 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1777 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1778 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1779 if (cube_info->associate_alpha != MagickFalse)
1780 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1781 i=CacheOffset(cube_info,&pixel);
1782 if (p->cache[i] < 0)
1791 Identify the deepest node containing the pixel's color.
1794 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1796 id=ColorToNodeId(cube_info,&pixel,index);
1797 if (node_info->child[id] == (NodeInfo *) NULL)
1799 node_info=node_info->child[id];
1801 node_info=node_info->parent;
1803 Find closest color among siblings and their children.
1806 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1807 QuantumRange+1.0)+1.0);
1808 ClosestColor(image,p,node_info->parent);
1809 p->cache[i]=(ssize_t) p->color_number;
1812 Assign pixel to closest colormap entry.
1814 index=(size_t) (1*p->cache[i]);
1815 if (image->storage_class == PseudoClass)
1816 *indexes=(IndexPacket) index;
1817 if (cube_info->quantize_info->measure_error == MagickFalse)
1819 q->red=image->colormap[index].red;
1820 q->green=image->colormap[index].green;
1821 q->blue=image->colormap[index].blue;
1822 if (cube_info->associate_alpha != MagickFalse)
1823 q->opacity=image->colormap[index].opacity;
1825 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1826 return(MagickFalse);
1828 Propagate the error as the last entry of the error queue.
1830 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1831 sizeof(p->error[0]));
1832 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1833 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1834 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1835 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1836 if (cube_info->associate_alpha != MagickFalse)
1837 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1838 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1839 if (proceed == MagickFalse)
1840 return(MagickFalse);
1845 case WestGravity: p->x--; break;
1846 case EastGravity: p->x++; break;
1847 case NorthGravity: p->y--; break;
1848 case SouthGravity: p->y++; break;
1853 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1860 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1867 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1881 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1882 return(FloydSteinbergDither(image,cube_info));
1884 Distribute quantization error along a Hilbert curve.
1886 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1887 sizeof(*cube_info->error));
1890 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1891 for (depth=1; i != 0; depth++)
1893 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1895 cube_info->offset=0;
1896 cube_info->span=(MagickSizeType) image->columns*image->rows;
1897 image_view=AcquireCacheView(image);
1899 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1900 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1901 image_view=DestroyCacheView(image_view);
1906 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1910 + G e t C u b e I n f o %
1914 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1916 % GetCubeInfo() initialize the Cube data structure.
1918 % The format of the GetCubeInfo method is:
1920 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1921 % const size_t depth,const size_t maximum_colors)
1923 % A description of each parameter follows.
1925 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1927 % o depth: Normally, this integer value is zero or one. A zero or
1928 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1929 % A tree of this depth generally allows the best representation of the
1930 % reference image with the least amount of memory and the fastest
1931 % computational speed. In some cases, such as an image with low color
1932 % dispersion (a few number of colors), a value other than
1933 % Log4(number_colors) is required. To expand the color tree completely,
1936 % o maximum_colors: maximum colors.
1939 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1940 const size_t depth,const size_t maximum_colors)
1956 Initialize tree to describe color cube_info.
1958 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1959 if (cube_info == (CubeInfo *) NULL)
1960 return((CubeInfo *) NULL);
1961 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1962 cube_info->depth=depth;
1963 if (cube_info->depth > MaxTreeDepth)
1964 cube_info->depth=MaxTreeDepth;
1965 if (cube_info->depth < 2)
1967 cube_info->maximum_colors=maximum_colors;
1969 Initialize root node.
1971 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1972 if (cube_info->root == (NodeInfo *) NULL)
1973 return((CubeInfo *) NULL);
1974 cube_info->root->parent=cube_info->root;
1975 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1976 if (cube_info->quantize_info->dither == MagickFalse)
1979 Initialize dither resources.
1981 length=(size_t) (1UL << (4*(8-CacheShift)));
1982 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1983 sizeof(*cube_info->cache));
1984 if (cube_info->cache == (ssize_t *) NULL)
1985 return((CubeInfo *) NULL);
1987 Initialize color cache.
1989 for (i=0; i < (ssize_t) length; i++)
1990 cube_info->cache[i]=(-1);
1992 Distribute weights along a curve of exponential decay.
1995 for (i=0; i < ErrorQueueLength; i++)
1997 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1998 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2001 Normalize the weighting factors.
2004 for (i=0; i < ErrorQueueLength; i++)
2005 weight+=cube_info->weights[i];
2007 for (i=0; i < ErrorQueueLength; i++)
2009 cube_info->weights[i]/=weight;
2010 sum+=cube_info->weights[i];
2012 cube_info->weights[0]+=1.0-sum;
2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2021 + G e t N o d e I n f o %
2025 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2027 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2028 % presets all fields to zero.
2030 % The format of the GetNodeInfo method is:
2032 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2033 % const size_t level,NodeInfo *parent)
2035 % A description of each parameter follows.
2037 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2039 % o id: Specifies the child number of the node.
2041 % o level: Specifies the level in the storage_class the node resides.
2044 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2045 const size_t level,NodeInfo *parent)
2050 if (cube_info->free_nodes == 0)
2056 Allocate a new queue of nodes.
2058 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2059 if (nodes == (Nodes *) NULL)
2060 return((NodeInfo *) NULL);
2061 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2062 sizeof(*nodes->nodes));
2063 if (nodes->nodes == (NodeInfo *) NULL)
2064 return((NodeInfo *) NULL);
2065 nodes->next=cube_info->node_queue;
2066 cube_info->node_queue=nodes;
2067 cube_info->next_node=nodes->nodes;
2068 cube_info->free_nodes=NodesInAList;
2071 cube_info->free_nodes--;
2072 node_info=cube_info->next_node++;
2073 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2074 node_info->parent=parent;
2076 node_info->level=level;
2081 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2085 % G e t I m a g e Q u a n t i z e E r r o r %
2089 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2091 % GetImageQuantizeError() measures the difference between the original
2092 % and quantized images. This difference is the total quantization error.
2093 % The error is computed by summing over all pixels in an image the distance
2094 % squared in RGB space between each reference pixel value and its quantized
2095 % value. These values are computed:
2097 % o mean_error_per_pixel: This value is the mean error for any single
2098 % pixel in the image.
2100 % o normalized_mean_square_error: This value is the normalized mean
2101 % quantization error for any single pixel in the image. This distance
2102 % measure is normalized to a range between 0 and 1. It is independent
2103 % of the range of red, green, and blue values in the image.
2105 % o normalized_maximum_square_error: Thsi value is the normalized
2106 % maximum quantization error for any single pixel in the image. This
2107 % distance measure is normalized to a range between 0 and 1. It is
2108 % independent of the range of red, green, and blue values in your image.
2110 % The format of the GetImageQuantizeError method is:
2112 % MagickBooleanType GetImageQuantizeError(Image *image)
2114 % A description of each parameter follows.
2116 % o image: the image.
2119 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2137 mean_error_per_pixel;
2145 assert(image != (Image *) NULL);
2146 assert(image->signature == MagickSignature);
2147 if (image->debug != MagickFalse)
2148 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2149 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2150 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2151 if (image->storage_class == DirectClass)
2155 area=3.0*image->columns*image->rows;
2157 mean_error_per_pixel=0.0;
2159 exception=(&image->exception);
2160 image_view=AcquireCacheView(image);
2161 for (y=0; y < (ssize_t) image->rows; y++)
2163 register const PixelPacket
2169 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2170 if (p == (const PixelPacket *) NULL)
2172 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2173 for (x=0; x < (ssize_t) image->columns; x++)
2175 index=1UL*indexes[x];
2176 if (image->matte != MagickFalse)
2178 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2179 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2180 image->colormap[index].opacity));
2182 distance=fabs(alpha*GetRedPixelComponent(p)-beta*image->colormap[index].red);
2183 mean_error_per_pixel+=distance;
2184 mean_error+=distance*distance;
2185 if (distance > maximum_error)
2186 maximum_error=distance;
2187 distance=fabs(alpha*GetGreenPixelComponent(p)-beta*image->colormap[index].green);
2188 mean_error_per_pixel+=distance;
2189 mean_error+=distance*distance;
2190 if (distance > maximum_error)
2191 maximum_error=distance;
2192 distance=fabs(alpha*GetBluePixelComponent(p)-beta*image->colormap[index].blue);
2193 mean_error_per_pixel+=distance;
2194 mean_error+=distance*distance;
2195 if (distance > maximum_error)
2196 maximum_error=distance;
2200 image_view=DestroyCacheView(image_view);
2201 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2202 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2204 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2209 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2213 % G e t Q u a n t i z e I n f o %
2217 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2219 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2221 % The format of the GetQuantizeInfo method is:
2223 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2225 % A description of each parameter follows:
2227 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2230 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2232 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2233 assert(quantize_info != (QuantizeInfo *) NULL);
2234 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2235 quantize_info->number_colors=256;
2236 quantize_info->dither=MagickTrue;
2237 quantize_info->dither_method=RiemersmaDitherMethod;
2238 quantize_info->colorspace=UndefinedColorspace;
2239 quantize_info->measure_error=MagickFalse;
2240 quantize_info->signature=MagickSignature;
2244 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2248 % P o s t e r i z e I m a g e C h a n n e l %
2252 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2254 % PosterizeImage() reduces the image to a limited number of colors for a
2257 % The format of the PosterizeImage method is:
2259 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2260 % const MagickBooleanType dither)
2261 % MagickBooleanType PosterizeImageChannel(Image *image,
2262 % const ChannelType channel,const size_t levels,
2263 % const MagickBooleanType dither)
2265 % A description of each parameter follows:
2267 % o image: Specifies a pointer to an Image structure.
2269 % o levels: Number of color levels allowed in each channel. Very low values
2270 % (2, 3, or 4) have the most visible effect.
2272 % o dither: Set this integer value to something other than zero to dither
2277 static inline ssize_t MagickRound(MagickRealType x)
2280 Round the fraction to nearest integer.
2283 return((ssize_t) (x+0.5));
2284 return((ssize_t) (x-0.5));
2287 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2288 const MagickBooleanType dither)
2293 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2297 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2298 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2300 #define PosterizeImageTag "Posterize/Image"
2301 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2302 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2325 assert(image != (Image *) NULL);
2326 assert(image->signature == MagickSignature);
2327 if (image->debug != MagickFalse)
2328 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2329 if (image->storage_class == PseudoClass)
2330 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2331 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2333 for (i=0; i < (ssize_t) image->colors; i++)
2338 if ((channel & RedChannel) != 0)
2339 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2340 if ((channel & GreenChannel) != 0)
2341 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2342 if ((channel & BlueChannel) != 0)
2343 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2344 if ((channel & OpacityChannel) != 0)
2345 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2352 exception=(&image->exception);
2353 image_view=AcquireCacheView(image);
2354 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2355 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2357 for (y=0; y < (ssize_t) image->rows; y++)
2359 register IndexPacket
2362 register PixelPacket
2368 if (status == MagickFalse)
2370 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2371 if (q == (PixelPacket *) NULL)
2376 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2377 for (x=0; x < (ssize_t) image->columns; x++)
2379 if ((channel & RedChannel) != 0)
2380 q->red=PosterizePixel(q->red);
2381 if ((channel & GreenChannel) != 0)
2382 q->green=PosterizePixel(q->green);
2383 if ((channel & BlueChannel) != 0)
2384 q->blue=PosterizePixel(q->blue);
2385 if (((channel & OpacityChannel) != 0) &&
2386 (image->matte == MagickTrue))
2387 q->opacity=PosterizePixel(q->opacity);
2388 if (((channel & IndexChannel) != 0) &&
2389 (image->colorspace == CMYKColorspace))
2390 indexes[x]=PosterizePixel(indexes[x]);
2393 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2395 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2400 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2401 #pragma omp critical (MagickCore_PosterizeImageChannel)
2403 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2405 if (proceed == MagickFalse)
2409 image_view=DestroyCacheView(image_view);
2410 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2411 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2412 levels,MaxColormapSize+1);
2413 quantize_info->dither=dither;
2414 quantize_info->tree_depth=MaxTreeDepth;
2415 status=QuantizeImage(quantize_info,image);
2416 quantize_info=DestroyQuantizeInfo(quantize_info);
2421 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2425 + P r u n e C h i l d %
2429 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2431 % PruneChild() deletes the given node and merges its statistics into its
2434 % The format of the PruneSubtree method is:
2436 % PruneChild(const Image *image,CubeInfo *cube_info,
2437 % const NodeInfo *node_info)
2439 % A description of each parameter follows.
2441 % o image: the image.
2443 % o cube_info: A pointer to the Cube structure.
2445 % o node_info: pointer to node in color cube tree that is to be pruned.
2448 static void PruneChild(const Image *image,CubeInfo *cube_info,
2449 const NodeInfo *node_info)
2461 Traverse any children.
2463 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2464 for (i=0; i < (ssize_t) number_children; i++)
2465 if (node_info->child[i] != (NodeInfo *) NULL)
2466 PruneChild(image,cube_info,node_info->child[i]);
2468 Merge color statistics into parent.
2470 parent=node_info->parent;
2471 parent->number_unique+=node_info->number_unique;
2472 parent->total_color.red+=node_info->total_color.red;
2473 parent->total_color.green+=node_info->total_color.green;
2474 parent->total_color.blue+=node_info->total_color.blue;
2475 parent->total_color.opacity+=node_info->total_color.opacity;
2476 parent->child[node_info->id]=(NodeInfo *) NULL;
2481 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2485 + P r u n e L e v e l %
2489 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2491 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2492 % their color statistics into their parent node.
2494 % The format of the PruneLevel method is:
2496 % PruneLevel(const Image *image,CubeInfo *cube_info,
2497 % const NodeInfo *node_info)
2499 % A description of each parameter follows.
2501 % o image: the image.
2503 % o cube_info: A pointer to the Cube structure.
2505 % o node_info: pointer to node in color cube tree that is to be pruned.
2508 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2509 const NodeInfo *node_info)
2518 Traverse any children.
2520 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2521 for (i=0; i < (ssize_t) number_children; i++)
2522 if (node_info->child[i] != (NodeInfo *) NULL)
2523 PruneLevel(image,cube_info,node_info->child[i]);
2524 if (node_info->level == cube_info->depth)
2525 PruneChild(image,cube_info,node_info);
2529 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2533 + P r u n e T o C u b e D e p t h %
2537 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2539 % PruneToCubeDepth() deletes any nodes at a depth greater than
2540 % cube_info->depth while merging their color statistics into their parent
2543 % The format of the PruneToCubeDepth method is:
2545 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2546 % const NodeInfo *node_info)
2548 % A description of each parameter follows.
2550 % o cube_info: A pointer to the Cube structure.
2552 % o node_info: pointer to node in color cube tree that is to be pruned.
2555 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2556 const NodeInfo *node_info)
2565 Traverse any children.
2567 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2568 for (i=0; i < (ssize_t) number_children; i++)
2569 if (node_info->child[i] != (NodeInfo *) NULL)
2570 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2571 if (node_info->level > cube_info->depth)
2572 PruneChild(image,cube_info,node_info);
2576 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2580 % Q u a n t i z e I m a g e %
2584 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2586 % QuantizeImage() analyzes the colors within a reference image and chooses a
2587 % fixed number of colors to represent the image. The goal of the algorithm
2588 % is to minimize the color difference between the input and output image while
2589 % minimizing the processing time.
2591 % The format of the QuantizeImage method is:
2593 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2596 % A description of each parameter follows:
2598 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2600 % o image: the image.
2603 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2616 assert(quantize_info != (const QuantizeInfo *) NULL);
2617 assert(quantize_info->signature == MagickSignature);
2618 assert(image != (Image *) NULL);
2619 assert(image->signature == MagickSignature);
2620 if (image->debug != MagickFalse)
2621 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2622 maximum_colors=quantize_info->number_colors;
2623 if (maximum_colors == 0)
2624 maximum_colors=MaxColormapSize;
2625 if (maximum_colors > MaxColormapSize)
2626 maximum_colors=MaxColormapSize;
2627 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2628 (image->matte == MagickFalse))
2629 (void) SetGrayscaleImage(image);
2630 if ((image->storage_class == PseudoClass) &&
2631 (image->colors <= maximum_colors))
2633 depth=quantize_info->tree_depth;
2640 Depth of color tree is: Log4(colormap size)+2.
2642 colors=maximum_colors;
2643 for (depth=1; colors != 0; depth++)
2645 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2647 if ((image->matte != MagickFalse) && (depth > 5))
2651 Initialize color cube.
2653 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2654 if (cube_info == (CubeInfo *) NULL)
2655 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2657 status=ClassifyImageColors(cube_info,image,&image->exception);
2658 if (status != MagickFalse)
2661 Reduce the number of colors in the image.
2663 ReduceImageColors(image,cube_info);
2664 status=AssignImageColors(image,cube_info);
2666 DestroyCubeInfo(cube_info);
2671 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2675 % Q u a n t i z e I m a g e s %
2679 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2681 % QuantizeImages() analyzes the colors within a set of reference images and
2682 % chooses a fixed number of colors to represent the set. The goal of the
2683 % algorithm is to minimize the color difference between the input and output
2684 % images while minimizing the processing time.
2686 % The format of the QuantizeImages method is:
2688 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2691 % A description of each parameter follows:
2693 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2695 % o images: Specifies a pointer to a list of Image structures.
2698 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2711 MagickProgressMonitor
2722 assert(quantize_info != (const QuantizeInfo *) NULL);
2723 assert(quantize_info->signature == MagickSignature);
2724 assert(images != (Image *) NULL);
2725 assert(images->signature == MagickSignature);
2726 if (images->debug != MagickFalse)
2727 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2728 if (GetNextImageInList(images) == (Image *) NULL)
2731 Handle a single image with QuantizeImage.
2733 status=QuantizeImage(quantize_info,images);
2737 maximum_colors=quantize_info->number_colors;
2738 if (maximum_colors == 0)
2739 maximum_colors=MaxColormapSize;
2740 if (maximum_colors > MaxColormapSize)
2741 maximum_colors=MaxColormapSize;
2742 depth=quantize_info->tree_depth;
2749 Depth of color tree is: Log4(colormap size)+2.
2751 colors=maximum_colors;
2752 for (depth=1; colors != 0; depth++)
2754 if (quantize_info->dither != MagickFalse)
2758 Initialize color cube.
2760 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2761 if (cube_info == (CubeInfo *) NULL)
2763 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2764 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2765 return(MagickFalse);
2767 number_images=GetImageListLength(images);
2769 for (i=0; image != (Image *) NULL; i++)
2771 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2772 image->client_data);
2773 status=ClassifyImageColors(cube_info,image,&image->exception);
2774 if (status == MagickFalse)
2776 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2777 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2779 if (proceed == MagickFalse)
2781 image=GetNextImageInList(image);
2783 if (status != MagickFalse)
2786 Reduce the number of colors in an image sequence.
2788 ReduceImageColors(images,cube_info);
2790 for (i=0; image != (Image *) NULL; i++)
2792 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2793 NULL,image->client_data);
2794 status=AssignImageColors(image,cube_info);
2795 if (status == MagickFalse)
2797 (void) SetImageProgressMonitor(image,progress_monitor,
2798 image->client_data);
2799 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2801 if (proceed == MagickFalse)
2803 image=GetNextImageInList(image);
2806 DestroyCubeInfo(cube_info);
2811 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2819 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2821 % Reduce() traverses the color cube tree and prunes any node whose
2822 % quantization error falls below a particular threshold.
2824 % The format of the Reduce method is:
2826 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2828 % A description of each parameter follows.
2830 % o image: the image.
2832 % o cube_info: A pointer to the Cube structure.
2834 % o node_info: pointer to node in color cube tree that is to be pruned.
2837 static void Reduce(const Image *image,CubeInfo *cube_info,
2838 const NodeInfo *node_info)
2847 Traverse any children.
2849 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2850 for (i=0; i < (ssize_t) number_children; i++)
2851 if (node_info->child[i] != (NodeInfo *) NULL)
2852 Reduce(image,cube_info,node_info->child[i]);
2853 if (node_info->quantize_error <= cube_info->pruning_threshold)
2854 PruneChild(image,cube_info,node_info);
2858 Find minimum pruning threshold.
2860 if (node_info->number_unique > 0)
2861 cube_info->colors++;
2862 if (node_info->quantize_error < cube_info->next_threshold)
2863 cube_info->next_threshold=node_info->quantize_error;
2868 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2872 + R e d u c e I m a g e C o l o r s %
2876 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2878 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2879 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2880 % in the output image. On any given iteration over the tree, it selects
2881 % those nodes whose E value is minimal for pruning and merges their
2882 % color statistics upward. It uses a pruning threshold, Ep, to govern
2883 % node selection as follows:
2886 % while number of nodes with (n2 > 0) > required maximum number of colors
2887 % prune all nodes such that E <= Ep
2888 % Set Ep to minimum E in remaining nodes
2890 % This has the effect of minimizing any quantization error when merging
2891 % two nodes together.
2893 % When a node to be pruned has offspring, the pruning procedure invokes
2894 % itself recursively in order to prune the tree from the leaves upward.
2895 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2896 % corresponding data in that node's parent. This retains the pruned
2897 % node's color characteristics for later averaging.
2899 % For each node, n2 pixels exist for which that node represents the
2900 % smallest volume in RGB space containing those pixel's colors. When n2
2901 % > 0 the node will uniquely define a color in the output image. At the
2902 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2903 % the tree which represent colors present in the input image.
2905 % The other pixel count, n1, indicates the total number of colors
2906 % within the cubic volume which the node represents. This includes n1 -
2907 % n2 pixels whose colors should be defined by nodes at a lower level in
2910 % The format of the ReduceImageColors method is:
2912 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2914 % A description of each parameter follows.
2916 % o image: the image.
2918 % o cube_info: A pointer to the Cube structure.
2921 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2923 #define ReduceImageTag "Reduce/Image"
2934 cube_info->next_threshold=0.0;
2935 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2937 cube_info->pruning_threshold=cube_info->next_threshold;
2938 cube_info->next_threshold=cube_info->root->quantize_error-1;
2939 cube_info->colors=0;
2940 Reduce(image,cube_info,cube_info->root);
2941 offset=(MagickOffsetType) span-cube_info->colors;
2942 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2943 cube_info->maximum_colors+1);
2944 if (proceed == MagickFalse)
2950 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2954 % R e m a p I m a g e %
2958 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2960 % RemapImage() replaces the colors of an image with the closest color from
2961 % a reference image.
2963 % The format of the RemapImage method is:
2965 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2966 % Image *image,const Image *remap_image)
2968 % A description of each parameter follows:
2970 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2972 % o image: the image.
2974 % o remap_image: the reference image.
2977 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2978 Image *image,const Image *remap_image)
2987 Initialize color cube.
2989 assert(image != (Image *) NULL);
2990 assert(image->signature == MagickSignature);
2991 if (image->debug != MagickFalse)
2992 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2993 assert(remap_image != (Image *) NULL);
2994 assert(remap_image->signature == MagickSignature);
2995 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2996 quantize_info->number_colors);
2997 if (cube_info == (CubeInfo *) NULL)
2998 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3000 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3001 if (status != MagickFalse)
3004 Classify image colors from the reference image.
3006 cube_info->quantize_info->number_colors=cube_info->colors;
3007 status=AssignImageColors(image,cube_info);
3009 DestroyCubeInfo(cube_info);
3014 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3018 % R e m a p I m a g e s %
3022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3024 % RemapImages() replaces the colors of a sequence of images with the
3025 % closest color from a reference image.
3027 % The format of the RemapImage method is:
3029 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3030 % Image *images,Image *remap_image)
3032 % A description of each parameter follows:
3034 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3036 % o images: the image sequence.
3038 % o remap_image: the reference image.
3041 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3042 Image *images,const Image *remap_image)
3053 assert(images != (Image *) NULL);
3054 assert(images->signature == MagickSignature);
3055 if (images->debug != MagickFalse)
3056 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3058 if (remap_image == (Image *) NULL)
3061 Create a global colormap for an image sequence.
3063 status=QuantizeImages(quantize_info,images);
3067 Classify image colors from the reference image.
3069 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3070 quantize_info->number_colors);
3071 if (cube_info == (CubeInfo *) NULL)
3072 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3074 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3075 if (status != MagickFalse)
3078 Classify image colors from the reference image.
3080 cube_info->quantize_info->number_colors=cube_info->colors;
3082 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3084 status=AssignImageColors(image,cube_info);
3085 if (status == MagickFalse)
3089 DestroyCubeInfo(cube_info);
3094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3098 % S e t G r a y s c a l e I m a g e %
3102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3104 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3106 % The format of the SetGrayscaleImage method is:
3108 % MagickBooleanType SetGrayscaleImage(Image *image)
3110 % A description of each parameter follows:
3112 % o image: The image.
3116 #if defined(__cplusplus) || defined(c_plusplus)
3120 static int IntensityCompare(const void *x,const void *y)
3129 color_1=(PixelPacket *) x;
3130 color_2=(PixelPacket *) y;
3131 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3132 PixelIntensityToQuantum(color_2);
3133 return((int) intensity);
3136 #if defined(__cplusplus) || defined(c_plusplus)
3140 static MagickBooleanType SetGrayscaleImage(Image *image)
3162 assert(image != (Image *) NULL);
3163 assert(image->signature == MagickSignature);
3164 if (image->type != GrayscaleType)
3165 (void) TransformImageColorspace(image,GRAYColorspace);
3166 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3167 sizeof(*colormap_index));
3168 if (colormap_index == (ssize_t *) NULL)
3169 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3171 if (image->storage_class != PseudoClass)
3176 for (i=0; i <= (ssize_t) MaxMap; i++)
3177 colormap_index[i]=(-1);
3178 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3179 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3183 exception=(&image->exception);
3184 image_view=AcquireCacheView(image);
3185 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3186 #pragma omp parallel for schedule(dynamic,4) shared(status)
3188 for (y=0; y < (ssize_t) image->rows; y++)
3190 register IndexPacket
3193 register const PixelPacket
3199 if (status == MagickFalse)
3201 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3203 if (q == (PixelPacket *) NULL)
3208 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3209 for (x=0; x < (ssize_t) image->columns; x++)
3214 intensity=ScaleQuantumToMap(q->red);
3215 if (colormap_index[intensity] < 0)
3217 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3218 #pragma omp critical (MagickCore_SetGrayscaleImage)
3220 if (colormap_index[intensity] < 0)
3222 colormap_index[intensity]=(ssize_t) image->colors;
3223 image->colormap[image->colors]=(*q);
3227 indexes[x]=(IndexPacket) colormap_index[intensity];
3230 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3233 image_view=DestroyCacheView(image_view);
3235 for (i=0; i < (ssize_t) image->colors; i++)
3236 image->colormap[i].opacity=(unsigned short) i;
3237 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3239 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3241 if (colormap == (PixelPacket *) NULL)
3242 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3245 colormap[j]=image->colormap[0];
3246 for (i=0; i < (ssize_t) image->colors; i++)
3248 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3251 colormap[j]=image->colormap[i];
3253 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3255 image->colors=(size_t) (j+1);
3256 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3257 image->colormap=colormap;
3259 exception=(&image->exception);
3260 image_view=AcquireCacheView(image);
3261 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3262 #pragma omp parallel for schedule(dynamic,4) shared(status)
3264 for (y=0; y < (ssize_t) image->rows; y++)
3266 register IndexPacket
3269 register const PixelPacket
3275 if (status == MagickFalse)
3277 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3278 if (q == (PixelPacket *) NULL)
3283 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3284 for (x=0; x < (ssize_t) image->columns; x++)
3285 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3286 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3289 image_view=DestroyCacheView(image_view);
3290 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3291 image->type=GrayscaleType;
3292 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3293 image->type=BilevelType;