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 SetRedPixelComponent(q,image->colormap[index].red);
614 SetGreenPixelComponent(q,image->colormap[index].green);
615 SetBluePixelComponent(q,image->colormap[index].blue);
616 if (cube.associate_alpha != MagickFalse)
617 SetOpacityPixelComponent(q,image->colormap[index].opacity);
622 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
624 if (image->progress_monitor != (MagickProgressMonitor) NULL)
629 #if defined(MAGICKCORE_OPENMP_SUPPORT)
630 #pragma omp critical (MagickCore_AssignImageColors)
632 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
634 if (proceed == MagickFalse)
638 image_view=DestroyCacheView(image_view);
640 if (cube_info->quantize_info->measure_error != MagickFalse)
641 (void) GetImageQuantizeError(image);
642 if ((cube_info->quantize_info->number_colors == 2) &&
643 (cube_info->quantize_info->colorspace == GRAYColorspace))
658 for (i=0; i < (ssize_t) image->colors; i++)
660 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
661 QuantumRange/2.0) ? 0 : QuantumRange);
662 SetRedPixelComponent(q,intensity);
663 SetGreenPixelComponent(q,intensity);
664 SetBluePixelComponent(q,intensity);
668 (void) SyncImage(image);
669 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
670 (cube_info->quantize_info->colorspace != CMYKColorspace))
671 (void) TransformImageColorspace((Image *) image,RGBColorspace);
676 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
680 + C l a s s i f y I m a g e C o l o r s %
684 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
686 % ClassifyImageColors() begins by initializing a color description tree
687 % of sufficient depth to represent each possible input color in a leaf.
688 % However, it is impractical to generate a fully-formed color
689 % description tree in the storage_class phase for realistic values of
690 % Cmax. If colors components in the input image are quantized to k-bit
691 % precision, so that Cmax= 2k-1, the tree would need k levels below the
692 % root node to allow representing each possible input color in a leaf.
693 % This becomes prohibitive because the tree's total number of nodes is
696 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
697 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
698 % Initializes data structures for nodes only as they are needed; (2)
699 % Chooses a maximum depth for the tree as a function of the desired
700 % number of colors in the output image (currently log2(colormap size)).
702 % For each pixel in the input image, storage_class scans downward from
703 % the root of the color description tree. At each level of the tree it
704 % identifies the single node which represents a cube in RGB space
705 % containing It updates the following data for each such node:
707 % n1 : Number of pixels whose color is contained in the RGB cube
708 % which this node represents;
710 % n2 : Number of pixels whose color is not represented in a node at
711 % lower depth in the tree; initially, n2 = 0 for all nodes except
712 % leaves of the tree.
714 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
715 % all pixels not classified at a lower depth. The combination of
716 % these sums and n2 will ultimately characterize the mean color of a
717 % set of pixels represented by this node.
719 % E: the distance squared in RGB space between each pixel contained
720 % within a node and the nodes' center. This represents the quantization
723 % The format of the ClassifyImageColors() method is:
725 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
726 % const Image *image,ExceptionInfo *exception)
728 % A description of each parameter follows.
730 % o cube_info: A pointer to the Cube structure.
732 % o image: the image.
736 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
741 associate_alpha=image->matte;
742 if (cube_info->quantize_info->colorspace == TransparentColorspace)
743 associate_alpha=MagickFalse;
744 if ((cube_info->quantize_info->number_colors == 2) &&
745 (cube_info->quantize_info->colorspace == GRAYColorspace))
746 associate_alpha=MagickFalse;
747 cube_info->associate_alpha=associate_alpha;
750 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
751 const Image *image,ExceptionInfo *exception)
753 #define ClassifyImageTag "Classify/Image"
783 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
785 SetAssociatedAlpha(image,cube_info);
786 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
787 (cube_info->quantize_info->colorspace != CMYKColorspace))
788 (void) TransformImageColorspace((Image *) image,
789 cube_info->quantize_info->colorspace);
791 if ((image->colorspace != GRAYColorspace) &&
792 (image->colorspace != CMYColorspace) &&
793 (image->colorspace != RGBColorspace))
794 (void) TransformImageColorspace((Image *) image,RGBColorspace);
795 midpoint.red=(MagickRealType) QuantumRange/2.0;
796 midpoint.green=(MagickRealType) QuantumRange/2.0;
797 midpoint.blue=(MagickRealType) QuantumRange/2.0;
798 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
800 image_view=AcquireCacheView(image);
801 for (y=0; y < (ssize_t) image->rows; y++)
803 register const PixelPacket
809 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
810 if (p == (const PixelPacket *) NULL)
812 if (cube_info->nodes > MaxNodes)
815 Prune one level if the color tree is too large.
817 PruneLevel(image,cube_info,cube_info->root);
820 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
823 Start at the root and descend the color cube tree.
825 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
826 if (IsSameColor(image,p,p+count) == MagickFalse)
828 AssociateAlphaPixel(cube_info,p,&pixel);
829 index=MaxTreeDepth-1;
830 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
832 node_info=cube_info->root;
833 for (level=1; level <= MaxTreeDepth; level++)
836 id=ColorToNodeId(cube_info,&pixel,index);
837 mid.red+=(id & 1) != 0 ? bisect : -bisect;
838 mid.green+=(id & 2) != 0 ? bisect : -bisect;
839 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
840 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
841 if (node_info->child[id] == (NodeInfo *) NULL)
844 Set colors of new node to contain pixel.
846 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
847 if (node_info->child[id] == (NodeInfo *) NULL)
848 (void) ThrowMagickException(exception,GetMagickModule(),
849 ResourceLimitError,"MemoryAllocationFailed","`%s'",
851 if (level == MaxTreeDepth)
855 Approximate the quantization error represented by this node.
857 node_info=node_info->child[id];
858 error.red=QuantumScale*(pixel.red-mid.red);
859 error.green=QuantumScale*(pixel.green-mid.green);
860 error.blue=QuantumScale*(pixel.blue-mid.blue);
861 if (cube_info->associate_alpha != MagickFalse)
862 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
863 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
864 count*error.green*error.green+count*error.blue*error.blue+
865 count*error.opacity*error.opacity));
866 cube_info->root->quantize_error+=node_info->quantize_error;
870 Sum RGB for this leaf for later derivation of the mean cube color.
872 node_info->number_unique+=count;
873 node_info->total_color.red+=count*QuantumScale*pixel.red;
874 node_info->total_color.green+=count*QuantumScale*pixel.green;
875 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
876 if (cube_info->associate_alpha != MagickFalse)
877 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
880 if (cube_info->colors > cube_info->maximum_colors)
882 PruneToCubeDepth(image,cube_info,cube_info->root);
885 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
887 if (proceed == MagickFalse)
890 for (y++; y < (ssize_t) image->rows; y++)
892 register const PixelPacket
898 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
899 if (p == (const PixelPacket *) NULL)
901 if (cube_info->nodes > MaxNodes)
904 Prune one level if the color tree is too large.
906 PruneLevel(image,cube_info,cube_info->root);
909 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
912 Start at the root and descend the color cube tree.
914 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
915 if (IsSameColor(image,p,p+count) == MagickFalse)
917 AssociateAlphaPixel(cube_info,p,&pixel);
918 index=MaxTreeDepth-1;
919 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
921 node_info=cube_info->root;
922 for (level=1; level <= cube_info->depth; level++)
925 id=ColorToNodeId(cube_info,&pixel,index);
926 mid.red+=(id & 1) != 0 ? bisect : -bisect;
927 mid.green+=(id & 2) != 0 ? bisect : -bisect;
928 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
929 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
930 if (node_info->child[id] == (NodeInfo *) NULL)
933 Set colors of new node to contain pixel.
935 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
936 if (node_info->child[id] == (NodeInfo *) NULL)
937 (void) ThrowMagickException(exception,GetMagickModule(),
938 ResourceLimitError,"MemoryAllocationFailed","%s",
940 if (level == cube_info->depth)
944 Approximate the quantization error represented by this node.
946 node_info=node_info->child[id];
947 error.red=QuantumScale*(pixel.red-mid.red);
948 error.green=QuantumScale*(pixel.green-mid.green);
949 error.blue=QuantumScale*(pixel.blue-mid.blue);
950 if (cube_info->associate_alpha != MagickFalse)
951 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
952 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
953 count*error.green*error.green+count*error.blue*error.blue+
954 count*error.opacity*error.opacity));
955 cube_info->root->quantize_error+=node_info->quantize_error;
959 Sum RGB for this leaf for later derivation of the mean cube color.
961 node_info->number_unique+=count;
962 node_info->total_color.red+=count*QuantumScale*pixel.red;
963 node_info->total_color.green+=count*QuantumScale*pixel.green;
964 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
965 if (cube_info->associate_alpha != MagickFalse)
966 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
969 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
971 if (proceed == MagickFalse)
974 image_view=DestroyCacheView(image_view);
975 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
976 (cube_info->quantize_info->colorspace != CMYKColorspace))
977 (void) TransformImageColorspace((Image *) image,RGBColorspace);
982 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
986 % C l o n e Q u a n t i z e I n f o %
990 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
992 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
993 % or if quantize info is NULL, a new one.
995 % The format of the CloneQuantizeInfo method is:
997 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
999 % A description of each parameter follows:
1001 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1002 % quantize info, or if image info is NULL a new one.
1004 % o quantize_info: a structure of type info.
1007 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1012 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1013 if (clone_info == (QuantizeInfo *) NULL)
1014 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1015 GetQuantizeInfo(clone_info);
1016 if (quantize_info == (QuantizeInfo *) NULL)
1018 clone_info->number_colors=quantize_info->number_colors;
1019 clone_info->tree_depth=quantize_info->tree_depth;
1020 clone_info->dither=quantize_info->dither;
1021 clone_info->dither_method=quantize_info->dither_method;
1022 clone_info->colorspace=quantize_info->colorspace;
1023 clone_info->measure_error=quantize_info->measure_error;
1028 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032 + C l o s e s t C o l o r %
1036 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1038 % ClosestColor() traverses the color cube tree at a particular node and
1039 % determines which colormap entry best represents the input color.
1041 % The format of the ClosestColor method is:
1043 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1044 % const NodeInfo *node_info)
1046 % A description of each parameter follows.
1048 % o image: the image.
1050 % o cube_info: A pointer to the Cube structure.
1052 % o node_info: the address of a structure of type NodeInfo which points to a
1053 % node in the color cube tree that is to be pruned.
1056 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1057 const NodeInfo *node_info)
1066 Traverse any children.
1068 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1069 for (i=0; i < (ssize_t) number_children; i++)
1070 if (node_info->child[i] != (NodeInfo *) NULL)
1071 ClosestColor(image,cube_info,node_info->child[i]);
1072 if (node_info->number_unique != 0)
1077 register MagickRealType
1082 register PixelPacket
1085 register RealPixelPacket
1089 Determine if this color is "closest".
1091 p=image->colormap+node_info->color_number;
1092 q=(&cube_info->target);
1095 if (cube_info->associate_alpha != MagickFalse)
1097 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1098 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
1100 pixel=alpha*GetRedPixelComponent(p)-beta*GetRedPixelComponent(q);
1101 distance=pixel*pixel;
1102 if (distance <= cube_info->distance)
1104 pixel=alpha*GetGreenPixelComponent(p)-beta*GetGreenPixelComponent(q);
1105 distance+=pixel*pixel;
1106 if (distance <= cube_info->distance)
1108 pixel=alpha*GetBluePixelComponent(p)-beta*
1109 GetBluePixelComponent(q);
1110 distance+=pixel*pixel;
1111 if (distance <= cube_info->distance)
1114 distance+=pixel*pixel;
1115 if (distance <= cube_info->distance)
1117 cube_info->distance=distance;
1118 cube_info->color_number=node_info->color_number;
1127 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1131 % C o m p r e s s I m a g e C o l o r m a p %
1135 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1137 % CompressImageColormap() compresses an image colormap by removing any
1138 % duplicate or unused color entries.
1140 % The format of the CompressImageColormap method is:
1142 % MagickBooleanType CompressImageColormap(Image *image)
1144 % A description of each parameter follows:
1146 % o image: the image.
1149 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1154 assert(image != (Image *) NULL);
1155 assert(image->signature == MagickSignature);
1156 if (image->debug != MagickFalse)
1157 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1158 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1159 return(MagickFalse);
1160 GetQuantizeInfo(&quantize_info);
1161 quantize_info.number_colors=image->colors;
1162 quantize_info.tree_depth=MaxTreeDepth;
1163 return(QuantizeImage(&quantize_info,image));
1167 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1171 + D e f i n e I m a g e C o l o r m a p %
1175 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1177 % DefineImageColormap() traverses the color cube tree and notes each colormap
1178 % entry. A colormap entry is any node in the color cube tree where the
1179 % of unique colors is not zero. DefineImageColormap() returns the number of
1180 % colors in the image colormap.
1182 % The format of the DefineImageColormap method is:
1184 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1185 % NodeInfo *node_info)
1187 % A description of each parameter follows.
1189 % o image: the image.
1191 % o cube_info: A pointer to the Cube structure.
1193 % o node_info: the address of a structure of type NodeInfo which points to a
1194 % node in the color cube tree that is to be pruned.
1197 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1198 NodeInfo *node_info)
1207 Traverse any children.
1209 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1210 for (i=0; i < (ssize_t) number_children; i++)
1211 if (node_info->child[i] != (NodeInfo *) NULL)
1212 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1213 if (node_info->number_unique != 0)
1215 register MagickRealType
1218 register PixelPacket
1222 Colormap entry is defined by the mean color in this cube.
1224 q=image->colormap+image->colors;
1225 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1226 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1227 if (cube_info->associate_alpha == MagickFalse)
1229 SetRedPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1230 QuantumRange*node_info->total_color.red)));
1231 SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1232 QuantumRange*node_info->total_color.green)));
1233 SetBluePixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1234 QuantumRange*node_info->total_color.blue)));
1235 SetOpacityPixelComponent(q,OpaqueOpacity);
1242 opacity=(MagickRealType) (alpha*QuantumRange*
1243 node_info->total_color.opacity);
1244 SetOpacityPixelComponent(q,ClampToQuantum(opacity));
1245 if (q->opacity == OpaqueOpacity)
1247 SetRedPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1248 QuantumRange*node_info->total_color.red)));
1249 SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1250 QuantumRange*node_info->total_color.green)));
1251 SetBluePixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1252 QuantumRange*node_info->total_color.blue)));
1259 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1260 (MagickRealType) q->opacity));
1261 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1262 SetRedPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1263 gamma*QuantumRange*node_info->total_color.red)));
1264 SetGreenPixelComponent(q,ClampToQuantum((MagickRealType) (alpha*
1265 gamma*QuantumRange*node_info->total_color.green)));
1266 SetBluePixelComponent(q,ClampToQuantum((MagickRealType) (
1267 alpha*gamma*QuantumRange*node_info->total_color.blue)));
1268 if (node_info->number_unique > cube_info->transparent_pixels)
1270 cube_info->transparent_pixels=node_info->number_unique;
1271 cube_info->transparent_index=(ssize_t) image->colors;
1275 node_info->color_number=image->colors++;
1277 return(image->colors);
1281 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1285 + D e s t r o y C u b e I n f o %
1289 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1291 % DestroyCubeInfo() deallocates memory associated with an image.
1293 % The format of the DestroyCubeInfo method is:
1295 % DestroyCubeInfo(CubeInfo *cube_info)
1297 % A description of each parameter follows:
1299 % o cube_info: the address of a structure of type CubeInfo.
1302 static void DestroyCubeInfo(CubeInfo *cube_info)
1308 Release color cube tree storage.
1312 nodes=cube_info->node_queue->next;
1313 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1314 cube_info->node_queue->nodes);
1315 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1316 cube_info->node_queue);
1317 cube_info->node_queue=nodes;
1318 } while (cube_info->node_queue != (Nodes *) NULL);
1319 if (cube_info->cache != (ssize_t *) NULL)
1320 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1321 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1322 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1330 % D e s t r o y Q u a n t i z e I n f o %
1334 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1336 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1339 % The format of the DestroyQuantizeInfo method is:
1341 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1343 % A description of each parameter follows:
1345 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1348 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1350 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1351 assert(quantize_info != (QuantizeInfo *) NULL);
1352 assert(quantize_info->signature == MagickSignature);
1353 quantize_info->signature=(~MagickSignature);
1354 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1355 return(quantize_info);
1359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1363 + D i t h e r I m a g e %
1367 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1369 % DitherImage() distributes the difference between an original image and
1370 % the corresponding color reduced algorithm to neighboring pixels using
1371 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1372 % MagickTrue if the image is dithered otherwise MagickFalse.
1374 % The format of the DitherImage method is:
1376 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1378 % A description of each parameter follows.
1380 % o image: the image.
1382 % o cube_info: A pointer to the Cube structure.
1386 static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1391 assert(pixels != (RealPixelPacket **) NULL);
1392 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1393 if (pixels[i] != (RealPixelPacket *) NULL)
1394 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1395 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1399 static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1410 number_threads=GetOpenMPMaximumThreads();
1411 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1413 if (pixels == (RealPixelPacket **) NULL)
1414 return((RealPixelPacket **) NULL);
1415 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1416 for (i=0; i < (ssize_t) number_threads; i++)
1418 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1419 2*sizeof(**pixels));
1420 if (pixels[i] == (RealPixelPacket *) NULL)
1421 return(DestroyPixelThreadSet(pixels));
1426 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1427 const RealPixelPacket *pixel)
1429 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1430 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1431 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1432 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1438 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1439 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1440 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1441 if (cube_info->associate_alpha != MagickFalse)
1442 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1447 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1449 #define DitherImageTag "Dither/Image"
1467 Distribute quantization error using Floyd-Steinberg.
1469 pixels=AcquirePixelThreadSet(image->columns);
1470 if (pixels == (RealPixelPacket **) NULL)
1471 return(MagickFalse);
1472 exception=(&image->exception);
1474 image_view=AcquireCacheView(image);
1475 for (y=0; y < (ssize_t) image->rows; y++)
1478 id = GetOpenMPThreadId();
1487 register IndexPacket
1490 register PixelPacket
1502 if (status == MagickFalse)
1504 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1505 if (q == (PixelPacket *) NULL)
1510 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1512 current=pixels[id]+(y & 0x01)*image->columns;
1513 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1514 v=(ssize_t) ((y & 0x01) ? -1 : 1);
1515 for (x=0; x < (ssize_t) image->columns; x++)
1527 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1528 AssociateAlphaPixel(&cube,q+u,&pixel);
1531 pixel.red+=7*current[u-v].red/16;
1532 pixel.green+=7*current[u-v].green/16;
1533 pixel.blue+=7*current[u-v].blue/16;
1534 if (cube.associate_alpha != MagickFalse)
1535 pixel.opacity+=7*current[u-v].opacity/16;
1539 if (x < (ssize_t) (image->columns-1))
1541 pixel.red+=previous[u+v].red/16;
1542 pixel.green+=previous[u+v].green/16;
1543 pixel.blue+=previous[u+v].blue/16;
1544 if (cube.associate_alpha != MagickFalse)
1545 pixel.opacity+=previous[u+v].opacity/16;
1547 pixel.red+=5*previous[u].red/16;
1548 pixel.green+=5*previous[u].green/16;
1549 pixel.blue+=5*previous[u].blue/16;
1550 if (cube.associate_alpha != MagickFalse)
1551 pixel.opacity+=5*previous[u].opacity/16;
1554 pixel.red+=3*previous[u-v].red/16;
1555 pixel.green+=3*previous[u-v].green/16;
1556 pixel.blue+=3*previous[u-v].blue/16;
1557 if (cube.associate_alpha != MagickFalse)
1558 pixel.opacity+=3*previous[u-v].opacity/16;
1561 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1562 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1563 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1564 if (cube.associate_alpha != MagickFalse)
1565 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1566 i=CacheOffset(&cube,&pixel);
1567 if (cube.cache[i] < 0)
1576 Identify the deepest node containing the pixel's color.
1578 node_info=cube.root;
1579 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1581 id=ColorToNodeId(&cube,&pixel,index);
1582 if (node_info->child[id] == (NodeInfo *) NULL)
1584 node_info=node_info->child[id];
1587 Find closest color among siblings and their children.
1590 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1592 ClosestColor(image,&cube,node_info->parent);
1593 cube.cache[i]=(ssize_t) cube.color_number;
1596 Assign pixel to closest colormap entry.
1598 index=(size_t) cube.cache[i];
1599 if (image->storage_class == PseudoClass)
1600 SetIndexPixelComponent(indexes+u,index);
1601 if (cube.quantize_info->measure_error == MagickFalse)
1603 SetRedPixelComponent(q+u,image->colormap[index].red);
1604 SetGreenPixelComponent(q+u,image->colormap[index].green);
1605 SetBluePixelComponent(q+u,image->colormap[index].blue);
1606 if (cube.associate_alpha != MagickFalse)
1607 SetOpacityPixelComponent(q+u,image->colormap[index].opacity);
1609 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1614 AssociateAlphaPixel(&cube,image->colormap+index,&color);
1615 current[u].red=pixel.red-color.red;
1616 current[u].green=pixel.green-color.green;
1617 current[u].blue=pixel.blue-color.blue;
1618 if (cube.associate_alpha != MagickFalse)
1619 current[u].opacity=pixel.opacity-color.opacity;
1620 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1625 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1626 #pragma omp critical (MagickCore_FloydSteinbergDither)
1628 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1630 if (proceed == MagickFalse)
1635 image_view=DestroyCacheView(image_view);
1636 pixels=DestroyPixelThreadSet(pixels);
1640 static MagickBooleanType
1641 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1643 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1644 const size_t level,const unsigned int direction)
1651 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1652 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1653 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1658 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1659 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1660 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1665 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1666 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1667 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1672 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1673 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1674 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1685 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1686 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1687 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1688 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1689 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1690 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1691 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1696 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1697 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1698 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1699 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1700 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1701 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1702 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1707 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1708 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1709 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1710 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1711 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1712 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1713 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1718 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1719 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1720 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1721 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1722 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1723 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1724 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1732 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1733 CubeInfo *cube_info,const unsigned int direction)
1735 #define DitherImageTag "Dither/Image"
1751 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1752 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1757 register IndexPacket
1760 register PixelPacket
1769 exception=(&image->exception);
1770 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1771 if (q == (PixelPacket *) NULL)
1772 return(MagickFalse);
1773 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1774 AssociateAlphaPixel(cube_info,q,&pixel);
1775 for (i=0; i < ErrorQueueLength; i++)
1777 pixel.red+=p->weights[i]*p->error[i].red;
1778 pixel.green+=p->weights[i]*p->error[i].green;
1779 pixel.blue+=p->weights[i]*p->error[i].blue;
1780 if (cube_info->associate_alpha != MagickFalse)
1781 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1783 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1784 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1785 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1786 if (cube_info->associate_alpha != MagickFalse)
1787 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1788 i=CacheOffset(cube_info,&pixel);
1789 if (p->cache[i] < 0)
1798 Identify the deepest node containing the pixel's color.
1801 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1803 id=ColorToNodeId(cube_info,&pixel,index);
1804 if (node_info->child[id] == (NodeInfo *) NULL)
1806 node_info=node_info->child[id];
1808 node_info=node_info->parent;
1810 Find closest color among siblings and their children.
1813 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1814 QuantumRange+1.0)+1.0);
1815 ClosestColor(image,p,node_info->parent);
1816 p->cache[i]=(ssize_t) p->color_number;
1819 Assign pixel to closest colormap entry.
1821 index=(size_t) (1*p->cache[i]);
1822 if (image->storage_class == PseudoClass)
1823 *indexes=(IndexPacket) index;
1824 if (cube_info->quantize_info->measure_error == MagickFalse)
1826 SetRedPixelComponent(q,image->colormap[index].red);
1827 SetGreenPixelComponent(q,image->colormap[index].green);
1828 SetBluePixelComponent(q,image->colormap[index].blue);
1829 if (cube_info->associate_alpha != MagickFalse)
1830 SetOpacityPixelComponent(q,image->colormap[index].opacity);
1832 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1833 return(MagickFalse);
1835 Propagate the error as the last entry of the error queue.
1837 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1838 sizeof(p->error[0]));
1839 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1840 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1841 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1842 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1843 if (cube_info->associate_alpha != MagickFalse)
1844 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1845 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1846 if (proceed == MagickFalse)
1847 return(MagickFalse);
1852 case WestGravity: p->x--; break;
1853 case EastGravity: p->x++; break;
1854 case NorthGravity: p->y--; break;
1855 case SouthGravity: p->y++; break;
1860 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1867 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1874 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1888 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1889 return(FloydSteinbergDither(image,cube_info));
1891 Distribute quantization error along a Hilbert curve.
1893 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1894 sizeof(*cube_info->error));
1897 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1898 for (depth=1; i != 0; depth++)
1900 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1902 cube_info->offset=0;
1903 cube_info->span=(MagickSizeType) image->columns*image->rows;
1904 image_view=AcquireCacheView(image);
1906 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1907 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1908 image_view=DestroyCacheView(image_view);
1913 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1917 + G e t C u b e I n f o %
1921 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1923 % GetCubeInfo() initialize the Cube data structure.
1925 % The format of the GetCubeInfo method is:
1927 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1928 % const size_t depth,const size_t maximum_colors)
1930 % A description of each parameter follows.
1932 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1934 % o depth: Normally, this integer value is zero or one. A zero or
1935 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1936 % A tree of this depth generally allows the best representation of the
1937 % reference image with the least amount of memory and the fastest
1938 % computational speed. In some cases, such as an image with low color
1939 % dispersion (a few number of colors), a value other than
1940 % Log4(number_colors) is required. To expand the color tree completely,
1943 % o maximum_colors: maximum colors.
1946 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1947 const size_t depth,const size_t maximum_colors)
1963 Initialize tree to describe color cube_info.
1965 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1966 if (cube_info == (CubeInfo *) NULL)
1967 return((CubeInfo *) NULL);
1968 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1969 cube_info->depth=depth;
1970 if (cube_info->depth > MaxTreeDepth)
1971 cube_info->depth=MaxTreeDepth;
1972 if (cube_info->depth < 2)
1974 cube_info->maximum_colors=maximum_colors;
1976 Initialize root node.
1978 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1979 if (cube_info->root == (NodeInfo *) NULL)
1980 return((CubeInfo *) NULL);
1981 cube_info->root->parent=cube_info->root;
1982 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1983 if (cube_info->quantize_info->dither == MagickFalse)
1986 Initialize dither resources.
1988 length=(size_t) (1UL << (4*(8-CacheShift)));
1989 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1990 sizeof(*cube_info->cache));
1991 if (cube_info->cache == (ssize_t *) NULL)
1992 return((CubeInfo *) NULL);
1994 Initialize color cache.
1996 for (i=0; i < (ssize_t) length; i++)
1997 cube_info->cache[i]=(-1);
1999 Distribute weights along a curve of exponential decay.
2002 for (i=0; i < ErrorQueueLength; i++)
2004 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2005 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2008 Normalize the weighting factors.
2011 for (i=0; i < ErrorQueueLength; i++)
2012 weight+=cube_info->weights[i];
2014 for (i=0; i < ErrorQueueLength; i++)
2016 cube_info->weights[i]/=weight;
2017 sum+=cube_info->weights[i];
2019 cube_info->weights[0]+=1.0-sum;
2024 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2028 + G e t N o d e I n f o %
2032 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2034 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2035 % presets all fields to zero.
2037 % The format of the GetNodeInfo method is:
2039 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2040 % const size_t level,NodeInfo *parent)
2042 % A description of each parameter follows.
2044 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2046 % o id: Specifies the child number of the node.
2048 % o level: Specifies the level in the storage_class the node resides.
2051 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2052 const size_t level,NodeInfo *parent)
2057 if (cube_info->free_nodes == 0)
2063 Allocate a new queue of nodes.
2065 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2066 if (nodes == (Nodes *) NULL)
2067 return((NodeInfo *) NULL);
2068 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2069 sizeof(*nodes->nodes));
2070 if (nodes->nodes == (NodeInfo *) NULL)
2071 return((NodeInfo *) NULL);
2072 nodes->next=cube_info->node_queue;
2073 cube_info->node_queue=nodes;
2074 cube_info->next_node=nodes->nodes;
2075 cube_info->free_nodes=NodesInAList;
2078 cube_info->free_nodes--;
2079 node_info=cube_info->next_node++;
2080 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2081 node_info->parent=parent;
2083 node_info->level=level;
2088 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2092 % G e t I m a g e Q u a n t i z e E r r o r %
2096 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2098 % GetImageQuantizeError() measures the difference between the original
2099 % and quantized images. This difference is the total quantization error.
2100 % The error is computed by summing over all pixels in an image the distance
2101 % squared in RGB space between each reference pixel value and its quantized
2102 % value. These values are computed:
2104 % o mean_error_per_pixel: This value is the mean error for any single
2105 % pixel in the image.
2107 % o normalized_mean_square_error: This value is the normalized mean
2108 % quantization error for any single pixel in the image. This distance
2109 % measure is normalized to a range between 0 and 1. It is independent
2110 % of the range of red, green, and blue values in the image.
2112 % o normalized_maximum_square_error: Thsi value is the normalized
2113 % maximum quantization error for any single pixel in the image. This
2114 % distance measure is normalized to a range between 0 and 1. It is
2115 % independent of the range of red, green, and blue values in your image.
2117 % The format of the GetImageQuantizeError method is:
2119 % MagickBooleanType GetImageQuantizeError(Image *image)
2121 % A description of each parameter follows.
2123 % o image: the image.
2126 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2144 mean_error_per_pixel;
2152 assert(image != (Image *) NULL);
2153 assert(image->signature == MagickSignature);
2154 if (image->debug != MagickFalse)
2155 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2156 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2157 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2158 if (image->storage_class == DirectClass)
2162 area=3.0*image->columns*image->rows;
2164 mean_error_per_pixel=0.0;
2166 exception=(&image->exception);
2167 image_view=AcquireCacheView(image);
2168 for (y=0; y < (ssize_t) image->rows; y++)
2170 register const PixelPacket
2176 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2177 if (p == (const PixelPacket *) NULL)
2179 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2180 for (x=0; x < (ssize_t) image->columns; x++)
2182 index=1UL*GetIndexPixelComponent(indexes+x);
2183 if (image->matte != MagickFalse)
2185 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2186 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2187 image->colormap[index].opacity));
2189 distance=fabs(alpha*GetRedPixelComponent(p)-beta*
2190 image->colormap[index].red);
2191 mean_error_per_pixel+=distance;
2192 mean_error+=distance*distance;
2193 if (distance > maximum_error)
2194 maximum_error=distance;
2195 distance=fabs(alpha*GetGreenPixelComponent(p)-beta*
2196 image->colormap[index].green);
2197 mean_error_per_pixel+=distance;
2198 mean_error+=distance*distance;
2199 if (distance > maximum_error)
2200 maximum_error=distance;
2201 distance=fabs(alpha*GetBluePixelComponent(p)-beta*
2202 image->colormap[index].blue);
2203 mean_error_per_pixel+=distance;
2204 mean_error+=distance*distance;
2205 if (distance > maximum_error)
2206 maximum_error=distance;
2210 image_view=DestroyCacheView(image_view);
2211 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2212 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2214 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2219 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2223 % G e t Q u a n t i z e I n f o %
2227 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2229 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2231 % The format of the GetQuantizeInfo method is:
2233 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2235 % A description of each parameter follows:
2237 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2240 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2242 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2243 assert(quantize_info != (QuantizeInfo *) NULL);
2244 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2245 quantize_info->number_colors=256;
2246 quantize_info->dither=MagickTrue;
2247 quantize_info->dither_method=RiemersmaDitherMethod;
2248 quantize_info->colorspace=UndefinedColorspace;
2249 quantize_info->measure_error=MagickFalse;
2250 quantize_info->signature=MagickSignature;
2254 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2258 % P o s t e r i z e I m a g e C h a n n e l %
2262 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2264 % PosterizeImage() reduces the image to a limited number of colors for a
2267 % The format of the PosterizeImage method is:
2269 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2270 % const MagickBooleanType dither)
2271 % MagickBooleanType PosterizeImageChannel(Image *image,
2272 % const ChannelType channel,const size_t levels,
2273 % const MagickBooleanType dither)
2275 % A description of each parameter follows:
2277 % o image: Specifies a pointer to an Image structure.
2279 % o levels: Number of color levels allowed in each channel. Very low values
2280 % (2, 3, or 4) have the most visible effect.
2282 % o dither: Set this integer value to something other than zero to dither
2287 static inline ssize_t MagickRound(MagickRealType x)
2290 Round the fraction to nearest integer.
2293 return((ssize_t) (x+0.5));
2294 return((ssize_t) (x-0.5));
2297 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2298 const MagickBooleanType dither)
2303 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2307 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2308 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2310 #define PosterizeImageTag "Posterize/Image"
2311 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2312 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2335 assert(image != (Image *) NULL);
2336 assert(image->signature == MagickSignature);
2337 if (image->debug != MagickFalse)
2338 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2339 if (image->storage_class == PseudoClass)
2340 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2341 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2343 for (i=0; i < (ssize_t) image->colors; i++)
2348 if ((channel & RedChannel) != 0)
2349 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2350 if ((channel & GreenChannel) != 0)
2351 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2352 if ((channel & BlueChannel) != 0)
2353 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2354 if ((channel & OpacityChannel) != 0)
2355 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2362 exception=(&image->exception);
2363 image_view=AcquireCacheView(image);
2364 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2365 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2367 for (y=0; y < (ssize_t) image->rows; y++)
2369 register IndexPacket
2372 register PixelPacket
2378 if (status == MagickFalse)
2380 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2381 if (q == (PixelPacket *) NULL)
2386 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2387 for (x=0; x < (ssize_t) image->columns; x++)
2389 if ((channel & RedChannel) != 0)
2390 SetRedPixelComponent(q,PosterizePixel(GetRedPixelComponent(q)));
2391 if ((channel & GreenChannel) != 0)
2392 SetGreenPixelComponent(q,PosterizePixel(GetGreenPixelComponent(q)));
2393 if ((channel & BlueChannel) != 0)
2394 SetBluePixelComponent(q,PosterizePixel(GetBluePixelComponent(q)));
2395 if (((channel & OpacityChannel) != 0) &&
2396 (image->matte == MagickTrue))
2397 SetOpacityPixelComponent(q,PosterizePixel(GetOpacityPixelComponent(q)));
2398 if (((channel & IndexChannel) != 0) &&
2399 (image->colorspace == CMYKColorspace))
2400 SetIndexPixelComponent(indexes+x,PosterizePixel(
2401 GetIndexPixelComponent(indexes+x)));
2404 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2406 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2411 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2412 #pragma omp critical (MagickCore_PosterizeImageChannel)
2414 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2416 if (proceed == MagickFalse)
2420 image_view=DestroyCacheView(image_view);
2421 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2422 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2423 levels,MaxColormapSize+1);
2424 quantize_info->dither=dither;
2425 quantize_info->tree_depth=MaxTreeDepth;
2426 status=QuantizeImage(quantize_info,image);
2427 quantize_info=DestroyQuantizeInfo(quantize_info);
2432 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2436 + P r u n e C h i l d %
2440 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2442 % PruneChild() deletes the given node and merges its statistics into its
2445 % The format of the PruneSubtree method is:
2447 % PruneChild(const Image *image,CubeInfo *cube_info,
2448 % const NodeInfo *node_info)
2450 % A description of each parameter follows.
2452 % o image: the image.
2454 % o cube_info: A pointer to the Cube structure.
2456 % o node_info: pointer to node in color cube tree that is to be pruned.
2459 static void PruneChild(const Image *image,CubeInfo *cube_info,
2460 const NodeInfo *node_info)
2472 Traverse any children.
2474 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2475 for (i=0; i < (ssize_t) number_children; i++)
2476 if (node_info->child[i] != (NodeInfo *) NULL)
2477 PruneChild(image,cube_info,node_info->child[i]);
2479 Merge color statistics into parent.
2481 parent=node_info->parent;
2482 parent->number_unique+=node_info->number_unique;
2483 parent->total_color.red+=node_info->total_color.red;
2484 parent->total_color.green+=node_info->total_color.green;
2485 parent->total_color.blue+=node_info->total_color.blue;
2486 parent->total_color.opacity+=node_info->total_color.opacity;
2487 parent->child[node_info->id]=(NodeInfo *) NULL;
2492 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2496 + P r u n e L e v e l %
2500 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2502 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2503 % their color statistics into their parent node.
2505 % The format of the PruneLevel method is:
2507 % PruneLevel(const Image *image,CubeInfo *cube_info,
2508 % const NodeInfo *node_info)
2510 % A description of each parameter follows.
2512 % o image: the image.
2514 % o cube_info: A pointer to the Cube structure.
2516 % o node_info: pointer to node in color cube tree that is to be pruned.
2519 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2520 const NodeInfo *node_info)
2529 Traverse any children.
2531 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2532 for (i=0; i < (ssize_t) number_children; i++)
2533 if (node_info->child[i] != (NodeInfo *) NULL)
2534 PruneLevel(image,cube_info,node_info->child[i]);
2535 if (node_info->level == cube_info->depth)
2536 PruneChild(image,cube_info,node_info);
2540 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2544 + P r u n e T o C u b e D e p t h %
2548 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2550 % PruneToCubeDepth() deletes any nodes at a depth greater than
2551 % cube_info->depth while merging their color statistics into their parent
2554 % The format of the PruneToCubeDepth method is:
2556 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2557 % const NodeInfo *node_info)
2559 % A description of each parameter follows.
2561 % o cube_info: A pointer to the Cube structure.
2563 % o node_info: pointer to node in color cube tree that is to be pruned.
2566 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2567 const NodeInfo *node_info)
2576 Traverse any children.
2578 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2579 for (i=0; i < (ssize_t) number_children; i++)
2580 if (node_info->child[i] != (NodeInfo *) NULL)
2581 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2582 if (node_info->level > cube_info->depth)
2583 PruneChild(image,cube_info,node_info);
2587 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2591 % Q u a n t i z e I m a g e %
2595 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2597 % QuantizeImage() analyzes the colors within a reference image and chooses a
2598 % fixed number of colors to represent the image. The goal of the algorithm
2599 % is to minimize the color difference between the input and output image while
2600 % minimizing the processing time.
2602 % The format of the QuantizeImage method is:
2604 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2607 % A description of each parameter follows:
2609 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2611 % o image: the image.
2614 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2627 assert(quantize_info != (const QuantizeInfo *) NULL);
2628 assert(quantize_info->signature == MagickSignature);
2629 assert(image != (Image *) NULL);
2630 assert(image->signature == MagickSignature);
2631 if (image->debug != MagickFalse)
2632 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2633 maximum_colors=quantize_info->number_colors;
2634 if (maximum_colors == 0)
2635 maximum_colors=MaxColormapSize;
2636 if (maximum_colors > MaxColormapSize)
2637 maximum_colors=MaxColormapSize;
2638 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2639 (image->matte == MagickFalse))
2640 (void) SetGrayscaleImage(image);
2641 if ((image->storage_class == PseudoClass) &&
2642 (image->colors <= maximum_colors))
2644 depth=quantize_info->tree_depth;
2651 Depth of color tree is: Log4(colormap size)+2.
2653 colors=maximum_colors;
2654 for (depth=1; colors != 0; depth++)
2656 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2658 if ((image->matte != MagickFalse) && (depth > 5))
2662 Initialize color cube.
2664 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2665 if (cube_info == (CubeInfo *) NULL)
2666 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2668 status=ClassifyImageColors(cube_info,image,&image->exception);
2669 if (status != MagickFalse)
2672 Reduce the number of colors in the image.
2674 ReduceImageColors(image,cube_info);
2675 status=AssignImageColors(image,cube_info);
2677 DestroyCubeInfo(cube_info);
2682 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2686 % Q u a n t i z e I m a g e s %
2690 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2692 % QuantizeImages() analyzes the colors within a set of reference images and
2693 % chooses a fixed number of colors to represent the set. The goal of the
2694 % algorithm is to minimize the color difference between the input and output
2695 % images while minimizing the processing time.
2697 % The format of the QuantizeImages method is:
2699 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2702 % A description of each parameter follows:
2704 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2706 % o images: Specifies a pointer to a list of Image structures.
2709 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2722 MagickProgressMonitor
2733 assert(quantize_info != (const QuantizeInfo *) NULL);
2734 assert(quantize_info->signature == MagickSignature);
2735 assert(images != (Image *) NULL);
2736 assert(images->signature == MagickSignature);
2737 if (images->debug != MagickFalse)
2738 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2739 if (GetNextImageInList(images) == (Image *) NULL)
2742 Handle a single image with QuantizeImage.
2744 status=QuantizeImage(quantize_info,images);
2748 maximum_colors=quantize_info->number_colors;
2749 if (maximum_colors == 0)
2750 maximum_colors=MaxColormapSize;
2751 if (maximum_colors > MaxColormapSize)
2752 maximum_colors=MaxColormapSize;
2753 depth=quantize_info->tree_depth;
2760 Depth of color tree is: Log4(colormap size)+2.
2762 colors=maximum_colors;
2763 for (depth=1; colors != 0; depth++)
2765 if (quantize_info->dither != MagickFalse)
2769 Initialize color cube.
2771 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2772 if (cube_info == (CubeInfo *) NULL)
2774 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2775 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2776 return(MagickFalse);
2778 number_images=GetImageListLength(images);
2780 for (i=0; image != (Image *) NULL; i++)
2782 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2783 image->client_data);
2784 status=ClassifyImageColors(cube_info,image,&image->exception);
2785 if (status == MagickFalse)
2787 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2788 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2790 if (proceed == MagickFalse)
2792 image=GetNextImageInList(image);
2794 if (status != MagickFalse)
2797 Reduce the number of colors in an image sequence.
2799 ReduceImageColors(images,cube_info);
2801 for (i=0; image != (Image *) NULL; i++)
2803 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2804 NULL,image->client_data);
2805 status=AssignImageColors(image,cube_info);
2806 if (status == MagickFalse)
2808 (void) SetImageProgressMonitor(image,progress_monitor,
2809 image->client_data);
2810 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2812 if (proceed == MagickFalse)
2814 image=GetNextImageInList(image);
2817 DestroyCubeInfo(cube_info);
2822 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2830 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2832 % Reduce() traverses the color cube tree and prunes any node whose
2833 % quantization error falls below a particular threshold.
2835 % The format of the Reduce method is:
2837 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2839 % A description of each parameter follows.
2841 % o image: the image.
2843 % o cube_info: A pointer to the Cube structure.
2845 % o node_info: pointer to node in color cube tree that is to be pruned.
2848 static void Reduce(const Image *image,CubeInfo *cube_info,
2849 const NodeInfo *node_info)
2858 Traverse any children.
2860 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2861 for (i=0; i < (ssize_t) number_children; i++)
2862 if (node_info->child[i] != (NodeInfo *) NULL)
2863 Reduce(image,cube_info,node_info->child[i]);
2864 if (node_info->quantize_error <= cube_info->pruning_threshold)
2865 PruneChild(image,cube_info,node_info);
2869 Find minimum pruning threshold.
2871 if (node_info->number_unique > 0)
2872 cube_info->colors++;
2873 if (node_info->quantize_error < cube_info->next_threshold)
2874 cube_info->next_threshold=node_info->quantize_error;
2879 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2883 + R e d u c e I m a g e C o l o r s %
2887 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2889 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2890 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2891 % in the output image. On any given iteration over the tree, it selects
2892 % those nodes whose E value is minimal for pruning and merges their
2893 % color statistics upward. It uses a pruning threshold, Ep, to govern
2894 % node selection as follows:
2897 % while number of nodes with (n2 > 0) > required maximum number of colors
2898 % prune all nodes such that E <= Ep
2899 % Set Ep to minimum E in remaining nodes
2901 % This has the effect of minimizing any quantization error when merging
2902 % two nodes together.
2904 % When a node to be pruned has offspring, the pruning procedure invokes
2905 % itself recursively in order to prune the tree from the leaves upward.
2906 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2907 % corresponding data in that node's parent. This retains the pruned
2908 % node's color characteristics for later averaging.
2910 % For each node, n2 pixels exist for which that node represents the
2911 % smallest volume in RGB space containing those pixel's colors. When n2
2912 % > 0 the node will uniquely define a color in the output image. At the
2913 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2914 % the tree which represent colors present in the input image.
2916 % The other pixel count, n1, indicates the total number of colors
2917 % within the cubic volume which the node represents. This includes n1 -
2918 % n2 pixels whose colors should be defined by nodes at a lower level in
2921 % The format of the ReduceImageColors method is:
2923 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2925 % A description of each parameter follows.
2927 % o image: the image.
2929 % o cube_info: A pointer to the Cube structure.
2932 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2934 #define ReduceImageTag "Reduce/Image"
2945 cube_info->next_threshold=0.0;
2946 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2948 cube_info->pruning_threshold=cube_info->next_threshold;
2949 cube_info->next_threshold=cube_info->root->quantize_error-1;
2950 cube_info->colors=0;
2951 Reduce(image,cube_info,cube_info->root);
2952 offset=(MagickOffsetType) span-cube_info->colors;
2953 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2954 cube_info->maximum_colors+1);
2955 if (proceed == MagickFalse)
2961 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2965 % R e m a p I m a g e %
2969 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2971 % RemapImage() replaces the colors of an image with the closest color from
2972 % a reference image.
2974 % The format of the RemapImage method is:
2976 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2977 % Image *image,const Image *remap_image)
2979 % A description of each parameter follows:
2981 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2983 % o image: the image.
2985 % o remap_image: the reference image.
2988 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2989 Image *image,const Image *remap_image)
2998 Initialize color cube.
3000 assert(image != (Image *) NULL);
3001 assert(image->signature == MagickSignature);
3002 if (image->debug != MagickFalse)
3003 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3004 assert(remap_image != (Image *) NULL);
3005 assert(remap_image->signature == MagickSignature);
3006 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3007 quantize_info->number_colors);
3008 if (cube_info == (CubeInfo *) NULL)
3009 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3011 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3012 if (status != MagickFalse)
3015 Classify image colors from the reference image.
3017 cube_info->quantize_info->number_colors=cube_info->colors;
3018 status=AssignImageColors(image,cube_info);
3020 DestroyCubeInfo(cube_info);
3025 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3029 % R e m a p I m a g e s %
3033 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3035 % RemapImages() replaces the colors of a sequence of images with the
3036 % closest color from a reference image.
3038 % The format of the RemapImage method is:
3040 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3041 % Image *images,Image *remap_image)
3043 % A description of each parameter follows:
3045 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3047 % o images: the image sequence.
3049 % o remap_image: the reference image.
3052 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3053 Image *images,const Image *remap_image)
3064 assert(images != (Image *) NULL);
3065 assert(images->signature == MagickSignature);
3066 if (images->debug != MagickFalse)
3067 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3069 if (remap_image == (Image *) NULL)
3072 Create a global colormap for an image sequence.
3074 status=QuantizeImages(quantize_info,images);
3078 Classify image colors from the reference image.
3080 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3081 quantize_info->number_colors);
3082 if (cube_info == (CubeInfo *) NULL)
3083 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3085 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3086 if (status != MagickFalse)
3089 Classify image colors from the reference image.
3091 cube_info->quantize_info->number_colors=cube_info->colors;
3093 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3095 status=AssignImageColors(image,cube_info);
3096 if (status == MagickFalse)
3100 DestroyCubeInfo(cube_info);
3105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3109 % S e t G r a y s c a l e I m a g e %
3113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3115 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3117 % The format of the SetGrayscaleImage method is:
3119 % MagickBooleanType SetGrayscaleImage(Image *image)
3121 % A description of each parameter follows:
3123 % o image: The image.
3127 #if defined(__cplusplus) || defined(c_plusplus)
3131 static int IntensityCompare(const void *x,const void *y)
3140 color_1=(PixelPacket *) x;
3141 color_2=(PixelPacket *) y;
3142 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3143 PixelIntensityToQuantum(color_2);
3144 return((int) intensity);
3147 #if defined(__cplusplus) || defined(c_plusplus)
3151 static MagickBooleanType SetGrayscaleImage(Image *image)
3173 assert(image != (Image *) NULL);
3174 assert(image->signature == MagickSignature);
3175 if (image->type != GrayscaleType)
3176 (void) TransformImageColorspace(image,GRAYColorspace);
3177 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3178 sizeof(*colormap_index));
3179 if (colormap_index == (ssize_t *) NULL)
3180 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3182 if (image->storage_class != PseudoClass)
3187 for (i=0; i <= (ssize_t) MaxMap; i++)
3188 colormap_index[i]=(-1);
3189 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3190 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3194 exception=(&image->exception);
3195 image_view=AcquireCacheView(image);
3196 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3197 #pragma omp parallel for schedule(dynamic,4) shared(status)
3199 for (y=0; y < (ssize_t) image->rows; y++)
3201 register IndexPacket
3204 register const PixelPacket
3210 if (status == MagickFalse)
3212 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3214 if (q == (PixelPacket *) NULL)
3219 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3220 for (x=0; x < (ssize_t) image->columns; x++)
3225 intensity=ScaleQuantumToMap(GetRedPixelComponent(q));
3226 if (colormap_index[intensity] < 0)
3228 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3229 #pragma omp critical (MagickCore_SetGrayscaleImage)
3231 if (colormap_index[intensity] < 0)
3233 colormap_index[intensity]=(ssize_t) image->colors;
3234 image->colormap[image->colors].red=GetRedPixelComponent(q);
3235 image->colormap[image->colors].green=
3236 GetGreenPixelComponent(q);
3237 image->colormap[image->colors].blue=GetBluePixelComponent(q);
3241 SetIndexPixelComponent(indexes+x,colormap_index[intensity]);
3244 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3247 image_view=DestroyCacheView(image_view);
3249 for (i=0; i < (ssize_t) image->colors; i++)
3250 image->colormap[i].opacity=(unsigned short) i;
3251 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3253 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3255 if (colormap == (PixelPacket *) NULL)
3256 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3259 colormap[j]=image->colormap[0];
3260 for (i=0; i < (ssize_t) image->colors; i++)
3262 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3265 colormap[j]=image->colormap[i];
3267 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3269 image->colors=(size_t) (j+1);
3270 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3271 image->colormap=colormap;
3273 exception=(&image->exception);
3274 image_view=AcquireCacheView(image);
3275 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3276 #pragma omp parallel for schedule(dynamic,4) shared(status)
3278 for (y=0; y < (ssize_t) image->rows; y++)
3280 register IndexPacket
3283 register const PixelPacket
3289 if (status == MagickFalse)
3291 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3292 if (q == (PixelPacket *) NULL)
3297 indexes=GetCacheViewAuthenticIndexQueue(image_view);
3298 for (x=0; x < (ssize_t) image->columns; x++)
3299 SetIndexPixelComponent(indexes+x,colormap_index[ScaleQuantumToMap(
3300 GetIndexPixelComponent(indexes+x))]);
3301 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3304 image_view=DestroyCacheView(image_view);
3305 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3306 image->type=GrayscaleType;
3307 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3308 image->type=BilevelType;