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 "MagickCore/studio.h"
178 #include "MagickCore/attribute.h"
179 #include "MagickCore/cache-view.h"
180 #include "MagickCore/color.h"
181 #include "MagickCore/color-private.h"
182 #include "MagickCore/colormap.h"
183 #include "MagickCore/colorspace.h"
184 #include "MagickCore/colorspace-private.h"
185 #include "MagickCore/enhance.h"
186 #include "MagickCore/exception.h"
187 #include "MagickCore/exception-private.h"
188 #include "MagickCore/histogram.h"
189 #include "MagickCore/image.h"
190 #include "MagickCore/image-private.h"
191 #include "MagickCore/list.h"
192 #include "MagickCore/memory_.h"
193 #include "MagickCore/monitor.h"
194 #include "MagickCore/monitor-private.h"
195 #include "MagickCore/option.h"
196 #include "MagickCore/pixel-accessor.h"
197 #include "MagickCore/quantize.h"
198 #include "MagickCore/quantum.h"
199 #include "MagickCore/quantum-private.h"
200 #include "MagickCore/string_.h"
201 #include "MagickCore/thread-private.h"
206 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
211 #define ErrorQueueLength 16
212 #define MaxNodes 266817
213 #define MaxTreeDepth 8
214 #define NodesInAList 1920
219 typedef struct _RealPixelPacket
228 typedef struct _NodeInfo
249 typedef struct _Nodes
258 typedef struct _CubeInfo
296 error[ErrorQueueLength];
299 weights[ErrorQueueLength];
325 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
328 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
330 static MagickBooleanType
331 AssignImageColors(Image *,CubeInfo *),
332 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
333 DitherImage(Image *,CubeInfo *),
334 SetGrayscaleImage(Image *);
337 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
340 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
341 DestroyCubeInfo(CubeInfo *),
342 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
343 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
344 ReduceImageColors(const Image *,CubeInfo *);
347 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
351 % A c q u i r e Q u a n t i z e I n f o %
355 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
357 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
359 % The format of the AcquireQuantizeInfo method is:
361 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
363 % A description of each parameter follows:
365 % o image_info: the image info.
368 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
373 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
374 if (quantize_info == (QuantizeInfo *) NULL)
375 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
376 GetQuantizeInfo(quantize_info);
377 if (image_info != (ImageInfo *) NULL)
382 quantize_info->dither=image_info->dither;
383 option=GetImageOption(image_info,"dither");
384 if (option != (const char *) NULL)
385 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
386 MagickDitherOptions,MagickFalse,option);
387 quantize_info->measure_error=image_info->verbose;
389 return(quantize_info);
393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
397 + A s s i g n I m a g e C o l o r s %
401 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
403 % AssignImageColors() generates the output image from the pruned tree. The
404 % output image consists of two parts: (1) A color map, which is an array
405 % of color descriptions (RGB triples) for each color present in the
406 % output image; (2) A pixel array, which represents each pixel as an
407 % index into the color map array.
409 % First, the assignment phase makes one pass over the pruned color
410 % description tree to establish the image's color map. For each node
411 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
412 % color of all pixels that classify no lower than this node. Each of
413 % these colors becomes an entry in the color map.
415 % Finally, the assignment phase reclassifies each pixel in the pruned
416 % tree to identify the deepest node containing the pixel's color. The
417 % pixel's value in the pixel array becomes the index of this node's mean
418 % color in the color map.
420 % The format of the AssignImageColors() method is:
422 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
424 % A description of each parameter follows.
426 % o image: the image.
428 % o cube_info: A pointer to the Cube structure.
432 static inline void AssociateAlphaPixel(const Image *image,
433 const CubeInfo *cube_info,const Quantum *pixel,
434 RealPixelPacket *alpha_pixel)
439 if ((cube_info->associate_alpha == MagickFalse) ||
440 (GetPixelAlpha(image,pixel)== OpaqueAlpha))
442 alpha_pixel->red=(MagickRealType) GetPixelRed(image,pixel);
443 alpha_pixel->green=(MagickRealType) GetPixelGreen(image,pixel);
444 alpha_pixel->blue=(MagickRealType) GetPixelBlue(image,pixel);
445 alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
448 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,pixel));
449 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
450 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
451 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
452 alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
455 static inline void AssociateAlphaPixelPacket(const Image *image,
456 const CubeInfo *cube_info,const PixelPacket *pixel,
457 RealPixelPacket *alpha_pixel)
462 if ((cube_info->associate_alpha == MagickFalse) ||
463 (pixel->alpha == OpaqueAlpha))
465 alpha_pixel->red=(MagickRealType) pixel->red;
466 alpha_pixel->green=(MagickRealType) pixel->green;
467 alpha_pixel->blue=(MagickRealType) pixel->blue;
468 alpha_pixel->alpha=(MagickRealType) pixel->alpha;
471 alpha=(MagickRealType) (QuantumScale*pixel->alpha);
472 alpha_pixel->red=alpha*pixel->red;
473 alpha_pixel->green=alpha*pixel->green;
474 alpha_pixel->blue=alpha*pixel->blue;
475 alpha_pixel->alpha=(MagickRealType) pixel->alpha;
478 static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
482 if (value >= QuantumRange)
483 return((Quantum) QuantumRange);
484 return((Quantum) (value+0.5));
487 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
488 const RealPixelPacket *pixel,size_t index)
493 id=(size_t) (((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x01) |
494 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x01) << 1 |
495 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x01) << 2);
496 if (cube_info->associate_alpha != MagickFalse)
497 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->alpha)) >> index) & 0x1) << 3;
501 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
503 #define AssignImageTag "Assign/Image"
509 Allocate image colormap.
511 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
512 (cube_info->quantize_info->colorspace != CMYKColorspace))
513 (void) TransformImageColorspace((Image *) image,
514 cube_info->quantize_info->colorspace);
516 if ((image->colorspace != GRAYColorspace) &&
517 (IsRGBColorspace(image->colorspace) == MagickFalse) &&
518 (image->colorspace != CMYColorspace))
519 (void) TransformImageColorspace((Image *) image,RGBColorspace);
520 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
521 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
524 cube_info->transparent_pixels=0;
525 cube_info->transparent_index=(-1);
526 (void) DefineImageColormap(image,cube_info,cube_info->root);
528 Create a reduced color image.
530 if ((cube_info->quantize_info->dither != MagickFalse) &&
531 (cube_info->quantize_info->dither_method != NoDitherMethod))
532 (void) DitherImage(image,cube_info);
545 exception=(&image->exception);
546 image_view=AcquireCacheView(image);
547 #if defined(MAGICKCORE_OPENMP_SUPPORT)
548 #pragma omp parallel for schedule(dynamic,4) shared(status)
550 for (y=0; y < (ssize_t) image->rows; y++)
564 if (status == MagickFalse)
566 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
568 if (q == (const Quantum *) NULL)
574 for (x=0; x < (ssize_t) image->columns; x+=count)
579 register const NodeInfo
590 Identify the deepest node containing the pixel's color.
592 for (count=1; (x+count) < (ssize_t) image->columns; count++)
597 GetPixelPacket(image,q+count*GetPixelChannels(image),&packet);
598 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
601 AssociateAlphaPixel(image,&cube,q,&pixel);
603 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
605 id=ColorToNodeId(&cube,&pixel,index);
606 if (node_info->child[id] == (NodeInfo *) NULL)
608 node_info=node_info->child[id];
611 Find closest color among siblings and their children.
614 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
615 (QuantumRange+1.0)+1.0);
616 ClosestColor(image,&cube,node_info->parent);
617 index=cube.color_number;
618 for (i=0; i < (ssize_t) count; i++)
620 if (image->storage_class == PseudoClass)
621 SetPixelIndex(image,(Quantum) index,q);
622 if (cube.quantize_info->measure_error == MagickFalse)
624 SetPixelRed(image,image->colormap[index].red,q);
625 SetPixelGreen(image,image->colormap[index].green,q);
626 SetPixelBlue(image,image->colormap[index].blue,q);
627 if (cube.associate_alpha != MagickFalse)
628 SetPixelAlpha(image,image->colormap[index].alpha,q);
630 q+=GetPixelChannels(image);
633 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
635 if (image->progress_monitor != (MagickProgressMonitor) NULL)
640 #if defined(MAGICKCORE_OPENMP_SUPPORT)
641 #pragma omp critical (MagickCore_AssignImageColors)
643 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
645 if (proceed == MagickFalse)
649 image_view=DestroyCacheView(image_view);
651 if (cube_info->quantize_info->measure_error != MagickFalse)
652 (void) GetImageQuantizeError(image);
653 if ((cube_info->quantize_info->number_colors == 2) &&
654 (cube_info->quantize_info->colorspace == GRAYColorspace))
669 for (i=0; i < (ssize_t) image->colors; i++)
671 intensity=(Quantum) ((MagickRealType) GetPixelPacketIntensity(q) <
672 ((MagickRealType) QuantumRange/2.0) ? 0 : QuantumRange);
679 (void) SyncImage(image);
680 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
681 (cube_info->quantize_info->colorspace != CMYKColorspace))
682 (void) TransformImageColorspace((Image *) image,RGBColorspace);
687 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
691 + C l a s s i f y I m a g e C o l o r s %
695 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
697 % ClassifyImageColors() begins by initializing a color description tree
698 % of sufficient depth to represent each possible input color in a leaf.
699 % However, it is impractical to generate a fully-formed color
700 % description tree in the storage_class phase for realistic values of
701 % Cmax. If colors components in the input image are quantized to k-bit
702 % precision, so that Cmax= 2k-1, the tree would need k levels below the
703 % root node to allow representing each possible input color in a leaf.
704 % This becomes prohibitive because the tree's total number of nodes is
707 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
708 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
709 % Initializes data structures for nodes only as they are needed; (2)
710 % Chooses a maximum depth for the tree as a function of the desired
711 % number of colors in the output image (currently log2(colormap size)).
713 % For each pixel in the input image, storage_class scans downward from
714 % the root of the color description tree. At each level of the tree it
715 % identifies the single node which represents a cube in RGB space
716 % containing It updates the following data for each such node:
718 % n1 : Number of pixels whose color is contained in the RGB cube
719 % which this node represents;
721 % n2 : Number of pixels whose color is not represented in a node at
722 % lower depth in the tree; initially, n2 = 0 for all nodes except
723 % leaves of the tree.
725 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
726 % all pixels not classified at a lower depth. The combination of
727 % these sums and n2 will ultimately characterize the mean color of a
728 % set of pixels represented by this node.
730 % E: the distance squared in RGB space between each pixel contained
731 % within a node and the nodes' center. This represents the quantization
734 % The format of the ClassifyImageColors() method is:
736 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
737 % const Image *image,ExceptionInfo *exception)
739 % A description of each parameter follows.
741 % o cube_info: A pointer to the Cube structure.
743 % o image: the image.
747 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
752 associate_alpha=image->matte;
753 if (cube_info->quantize_info->colorspace == TransparentColorspace)
754 associate_alpha=MagickFalse;
755 if ((cube_info->quantize_info->number_colors == 2) &&
756 (cube_info->quantize_info->colorspace == GRAYColorspace))
757 associate_alpha=MagickFalse;
758 cube_info->associate_alpha=associate_alpha;
761 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
762 const Image *image,ExceptionInfo *exception)
764 #define ClassifyImageTag "Classify/Image"
794 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
796 SetAssociatedAlpha(image,cube_info);
797 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
798 (cube_info->quantize_info->colorspace != CMYKColorspace))
799 (void) TransformImageColorspace((Image *) image,
800 cube_info->quantize_info->colorspace);
802 if ((image->colorspace != GRAYColorspace) &&
803 (image->colorspace != CMYColorspace) &&
804 (IsRGBColorspace(image->colorspace) == MagickFalse))
805 (void) TransformImageColorspace((Image *) image,RGBColorspace);
806 midpoint.red=(MagickRealType) QuantumRange/2.0;
807 midpoint.green=(MagickRealType) QuantumRange/2.0;
808 midpoint.blue=(MagickRealType) QuantumRange/2.0;
809 midpoint.alpha=(MagickRealType) QuantumRange/2.0;
811 image_view=AcquireCacheView(image);
812 for (y=0; y < (ssize_t) image->rows; y++)
814 register const Quantum
820 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
821 if (p == (const Quantum *) NULL)
823 if (cube_info->nodes > MaxNodes)
826 Prune one level if the color tree is too large.
828 PruneLevel(image,cube_info,cube_info->root);
831 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
834 Start at the root and descend the color cube tree.
836 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
841 GetPixelPacket(image,p+count*GetPixelChannels(image),&packet);
842 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
845 AssociateAlphaPixel(image,cube_info,p,&pixel);
846 index=MaxTreeDepth-1;
847 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
849 node_info=cube_info->root;
850 for (level=1; level <= MaxTreeDepth; level++)
853 id=ColorToNodeId(cube_info,&pixel,index);
854 mid.red+=(id & 1) != 0 ? bisect : -bisect;
855 mid.green+=(id & 2) != 0 ? bisect : -bisect;
856 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
857 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
858 if (node_info->child[id] == (NodeInfo *) NULL)
861 Set colors of new node to contain pixel.
863 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
864 if (node_info->child[id] == (NodeInfo *) NULL)
865 (void) ThrowMagickException(exception,GetMagickModule(),
866 ResourceLimitError,"MemoryAllocationFailed","`%s'",
868 if (level == MaxTreeDepth)
872 Approximate the quantization error represented by this node.
874 node_info=node_info->child[id];
875 error.red=QuantumScale*(pixel.red-mid.red);
876 error.green=QuantumScale*(pixel.green-mid.green);
877 error.blue=QuantumScale*(pixel.blue-mid.blue);
878 if (cube_info->associate_alpha != MagickFalse)
879 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
880 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
881 count*error.green*error.green+count*error.blue*error.blue+
882 count*error.alpha*error.alpha));
883 cube_info->root->quantize_error+=node_info->quantize_error;
887 Sum RGB for this leaf for later derivation of the mean cube color.
889 node_info->number_unique+=count;
890 node_info->total_color.red+=count*QuantumScale*pixel.red;
891 node_info->total_color.green+=count*QuantumScale*pixel.green;
892 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
893 if (cube_info->associate_alpha != MagickFalse)
894 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
895 p+=count*GetPixelChannels(image);
897 if (cube_info->colors > cube_info->maximum_colors)
899 PruneToCubeDepth(image,cube_info,cube_info->root);
902 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
904 if (proceed == MagickFalse)
907 for (y++; y < (ssize_t) image->rows; y++)
909 register const Quantum
915 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
916 if (p == (const Quantum *) NULL)
918 if (cube_info->nodes > MaxNodes)
921 Prune one level if the color tree is too large.
923 PruneLevel(image,cube_info,cube_info->root);
926 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
929 Start at the root and descend the color cube tree.
931 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
936 GetPixelPacket(image,p+count*GetPixelChannels(image),&packet);
937 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
940 AssociateAlphaPixel(image,cube_info,p,&pixel);
941 index=MaxTreeDepth-1;
942 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
944 node_info=cube_info->root;
945 for (level=1; level <= cube_info->depth; level++)
948 id=ColorToNodeId(cube_info,&pixel,index);
949 mid.red+=(id & 1) != 0 ? bisect : -bisect;
950 mid.green+=(id & 2) != 0 ? bisect : -bisect;
951 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
952 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
953 if (node_info->child[id] == (NodeInfo *) NULL)
956 Set colors of new node to contain pixel.
958 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
959 if (node_info->child[id] == (NodeInfo *) NULL)
960 (void) ThrowMagickException(exception,GetMagickModule(),
961 ResourceLimitError,"MemoryAllocationFailed","%s",
963 if (level == cube_info->depth)
967 Approximate the quantization error represented by this node.
969 node_info=node_info->child[id];
970 error.red=QuantumScale*(pixel.red-mid.red);
971 error.green=QuantumScale*(pixel.green-mid.green);
972 error.blue=QuantumScale*(pixel.blue-mid.blue);
973 if (cube_info->associate_alpha != MagickFalse)
974 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
975 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
976 count*error.green*error.green+count*error.blue*error.blue+
977 count*error.alpha*error.alpha));
978 cube_info->root->quantize_error+=node_info->quantize_error;
982 Sum RGB for this leaf for later derivation of the mean cube color.
984 node_info->number_unique+=count;
985 node_info->total_color.red+=count*QuantumScale*pixel.red;
986 node_info->total_color.green+=count*QuantumScale*pixel.green;
987 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
988 if (cube_info->associate_alpha != MagickFalse)
989 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
990 p+=count*GetPixelChannels(image);
992 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
994 if (proceed == MagickFalse)
997 image_view=DestroyCacheView(image_view);
998 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
999 (cube_info->quantize_info->colorspace != CMYKColorspace))
1000 (void) TransformImageColorspace((Image *) image,RGBColorspace);
1005 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1009 % C l o n e Q u a n t i z e I n f o %
1013 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1015 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1016 % or if quantize info is NULL, a new one.
1018 % The format of the CloneQuantizeInfo method is:
1020 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1022 % A description of each parameter follows:
1024 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1025 % quantize info, or if image info is NULL a new one.
1027 % o quantize_info: a structure of type info.
1030 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1035 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1036 if (clone_info == (QuantizeInfo *) NULL)
1037 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1038 GetQuantizeInfo(clone_info);
1039 if (quantize_info == (QuantizeInfo *) NULL)
1041 clone_info->number_colors=quantize_info->number_colors;
1042 clone_info->tree_depth=quantize_info->tree_depth;
1043 clone_info->dither=quantize_info->dither;
1044 clone_info->dither_method=quantize_info->dither_method;
1045 clone_info->colorspace=quantize_info->colorspace;
1046 clone_info->measure_error=quantize_info->measure_error;
1051 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1055 + C l o s e s t C o l o r %
1059 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1061 % ClosestColor() traverses the color cube tree at a particular node and
1062 % determines which colormap entry best represents the input color.
1064 % The format of the ClosestColor method is:
1066 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1067 % const NodeInfo *node_info)
1069 % A description of each parameter follows.
1071 % o image: the image.
1073 % o cube_info: A pointer to the Cube structure.
1075 % o node_info: the address of a structure of type NodeInfo which points to a
1076 % node in the color cube tree that is to be pruned.
1079 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1080 const NodeInfo *node_info)
1089 Traverse any children.
1091 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1092 for (i=0; i < (ssize_t) number_children; i++)
1093 if (node_info->child[i] != (NodeInfo *) NULL)
1094 ClosestColor(image,cube_info,node_info->child[i]);
1095 if (node_info->number_unique != 0)
1100 register MagickRealType
1105 register PixelPacket
1108 register RealPixelPacket
1112 Determine if this color is "closest".
1114 p=image->colormap+node_info->color_number;
1115 q=(&cube_info->target);
1118 if (cube_info->associate_alpha != MagickFalse)
1120 alpha=(MagickRealType) (QuantumScale*p->alpha);
1121 beta=(MagickRealType) (QuantumScale*q->alpha);
1123 pixel=alpha*p->red-beta*q->red;
1124 distance=pixel*pixel;
1125 if (distance <= cube_info->distance)
1127 pixel=alpha*p->green-beta*q->green;
1128 distance+=pixel*pixel;
1129 if (distance <= cube_info->distance)
1131 pixel=alpha*p->blue-beta*q->blue;
1132 distance+=pixel*pixel;
1133 if (distance <= cube_info->distance)
1136 distance+=pixel*pixel;
1137 if (distance <= cube_info->distance)
1139 cube_info->distance=distance;
1140 cube_info->color_number=node_info->color_number;
1149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1153 % C o m p r e s s I m a g e C o l o r m a p %
1157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1159 % CompressImageColormap() compresses an image colormap by removing any
1160 % duplicate or unused color entries.
1162 % The format of the CompressImageColormap method is:
1164 % MagickBooleanType CompressImageColormap(Image *image)
1166 % A description of each parameter follows:
1168 % o image: the image.
1171 MagickExport MagickBooleanType CompressImageColormap(Image *image)
1176 assert(image != (Image *) NULL);
1177 assert(image->signature == MagickSignature);
1178 if (image->debug != MagickFalse)
1179 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1180 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1181 return(MagickFalse);
1182 GetQuantizeInfo(&quantize_info);
1183 quantize_info.number_colors=image->colors;
1184 quantize_info.tree_depth=MaxTreeDepth;
1185 return(QuantizeImage(&quantize_info,image));
1189 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1193 + D e f i n e I m a g e C o l o r m a p %
1197 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1199 % DefineImageColormap() traverses the color cube tree and notes each colormap
1200 % entry. A colormap entry is any node in the color cube tree where the
1201 % of unique colors is not zero. DefineImageColormap() returns the number of
1202 % colors in the image colormap.
1204 % The format of the DefineImageColormap method is:
1206 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1207 % NodeInfo *node_info)
1209 % A description of each parameter follows.
1211 % o image: the image.
1213 % o cube_info: A pointer to the Cube structure.
1215 % o node_info: the address of a structure of type NodeInfo which points to a
1216 % node in the color cube tree that is to be pruned.
1219 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1220 NodeInfo *node_info)
1229 Traverse any children.
1231 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1232 for (i=0; i < (ssize_t) number_children; i++)
1233 if (node_info->child[i] != (NodeInfo *) NULL)
1234 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1235 if (node_info->number_unique != 0)
1237 register MagickRealType
1240 register PixelPacket
1244 Colormap entry is defined by the mean color in this cube.
1246 q=image->colormap+image->colors;
1247 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1248 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1249 if (cube_info->associate_alpha == MagickFalse)
1251 q->red=ClampToQuantum((MagickRealType)
1252 (alpha*QuantumRange*node_info->total_color.red));
1253 q->green=ClampToQuantum((MagickRealType)
1254 (alpha*QuantumRange*node_info->total_color.green));
1255 q->blue=ClampToQuantum((MagickRealType)
1256 (alpha*QuantumRange*node_info->total_color.blue));
1257 q->alpha=OpaqueAlpha;
1264 opacity=(MagickRealType) (alpha*QuantumRange*
1265 node_info->total_color.alpha);
1266 q->alpha=ClampToQuantum(opacity);
1267 if (q->alpha == OpaqueAlpha)
1269 q->red=ClampToQuantum((MagickRealType)
1270 (alpha*QuantumRange*node_info->total_color.red));
1271 q->green=ClampToQuantum((MagickRealType)
1272 (alpha*QuantumRange*node_info->total_color.green));
1273 q->blue=ClampToQuantum((MagickRealType)
1274 (alpha*QuantumRange*node_info->total_color.blue));
1281 gamma=(MagickRealType) (QuantumScale*q->alpha);
1282 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
1283 q->red=ClampToQuantum((MagickRealType)
1284 (alpha*gamma*QuantumRange*node_info->total_color.red));
1285 q->green=ClampToQuantum((MagickRealType)
1286 (alpha*gamma*QuantumRange*node_info->total_color.green));
1287 q->blue=ClampToQuantum((MagickRealType)
1288 (alpha*gamma*QuantumRange*node_info->total_color.blue));
1289 if (node_info->number_unique > cube_info->transparent_pixels)
1291 cube_info->transparent_pixels=node_info->number_unique;
1292 cube_info->transparent_index=(ssize_t) image->colors;
1296 node_info->color_number=image->colors++;
1298 return(image->colors);
1302 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1306 + D e s t r o y C u b e I n f o %
1310 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1312 % DestroyCubeInfo() deallocates memory associated with an image.
1314 % The format of the DestroyCubeInfo method is:
1316 % DestroyCubeInfo(CubeInfo *cube_info)
1318 % A description of each parameter follows:
1320 % o cube_info: the address of a structure of type CubeInfo.
1323 static void DestroyCubeInfo(CubeInfo *cube_info)
1329 Release color cube tree storage.
1333 nodes=cube_info->node_queue->next;
1334 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1335 cube_info->node_queue->nodes);
1336 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1337 cube_info->node_queue);
1338 cube_info->node_queue=nodes;
1339 } while (cube_info->node_queue != (Nodes *) NULL);
1340 if (cube_info->cache != (ssize_t *) NULL)
1341 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1342 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1343 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1347 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1351 % D e s t r o y Q u a n t i z e I n f o %
1355 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1357 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1360 % The format of the DestroyQuantizeInfo method is:
1362 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1364 % A description of each parameter follows:
1366 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1369 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1371 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1372 assert(quantize_info != (QuantizeInfo *) NULL);
1373 assert(quantize_info->signature == MagickSignature);
1374 quantize_info->signature=(~MagickSignature);
1375 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1376 return(quantize_info);
1380 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1384 + D i t h e r I m a g e %
1388 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1390 % DitherImage() distributes the difference between an original image and
1391 % the corresponding color reduced algorithm to neighboring pixels using
1392 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1393 % MagickTrue if the image is dithered otherwise MagickFalse.
1395 % The format of the DitherImage method is:
1397 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1399 % A description of each parameter follows.
1401 % o image: the image.
1403 % o cube_info: A pointer to the Cube structure.
1407 static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1412 assert(pixels != (RealPixelPacket **) NULL);
1413 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1414 if (pixels[i] != (RealPixelPacket *) NULL)
1415 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1416 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1420 static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1431 number_threads=GetOpenMPMaximumThreads();
1432 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1434 if (pixels == (RealPixelPacket **) NULL)
1435 return((RealPixelPacket **) NULL);
1436 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1437 for (i=0; i < (ssize_t) number_threads; i++)
1439 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1440 2*sizeof(**pixels));
1441 if (pixels[i] == (RealPixelPacket *) NULL)
1442 return(DestroyPixelThreadSet(pixels));
1447 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1448 const RealPixelPacket *pixel)
1450 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1451 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1452 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1453 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1459 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
1460 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
1461 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
1462 if (cube_info->associate_alpha != MagickFalse)
1463 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1468 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1470 #define DitherImageTag "Dither/Image"
1488 Distribute quantization error using Floyd-Steinberg.
1490 pixels=AcquirePixelThreadSet(image->columns);
1491 if (pixels == (RealPixelPacket **) NULL)
1492 return(MagickFalse);
1493 exception=(&image->exception);
1495 image_view=AcquireCacheView(image);
1496 for (y=0; y < (ssize_t) image->rows; y++)
1499 id = GetOpenMPThreadId();
1520 if (status == MagickFalse)
1522 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1523 if (q == (const Quantum *) NULL)
1528 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
1530 current=pixels[id]+(y & 0x01)*image->columns;
1531 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1532 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1533 for (x=0; x < (ssize_t) image->columns; x++)
1545 q-=(y & 0x01)*GetPixelChannels(image);
1546 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1547 AssociateAlphaPixel(image,&cube,q,&pixel);
1550 pixel.red+=7*current[u-v].red/16;
1551 pixel.green+=7*current[u-v].green/16;
1552 pixel.blue+=7*current[u-v].blue/16;
1553 if (cube.associate_alpha != MagickFalse)
1554 pixel.alpha+=7*current[u-v].alpha/16;
1558 if (x < (ssize_t) (image->columns-1))
1560 pixel.red+=previous[u+v].red/16;
1561 pixel.green+=previous[u+v].green/16;
1562 pixel.blue+=previous[u+v].blue/16;
1563 if (cube.associate_alpha != MagickFalse)
1564 pixel.alpha+=previous[u+v].alpha/16;
1566 pixel.red+=5*previous[u].red/16;
1567 pixel.green+=5*previous[u].green/16;
1568 pixel.blue+=5*previous[u].blue/16;
1569 if (cube.associate_alpha != MagickFalse)
1570 pixel.alpha+=5*previous[u].alpha/16;
1573 pixel.red+=3*previous[u-v].red/16;
1574 pixel.green+=3*previous[u-v].green/16;
1575 pixel.blue+=3*previous[u-v].blue/16;
1576 if (cube.associate_alpha != MagickFalse)
1577 pixel.alpha+=3*previous[u-v].alpha/16;
1580 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1581 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1582 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1583 if (cube.associate_alpha != MagickFalse)
1584 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
1585 i=CacheOffset(&cube,&pixel);
1586 if (cube.cache[i] < 0)
1595 Identify the deepest node containing the pixel's color.
1597 node_info=cube.root;
1598 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1600 id=ColorToNodeId(&cube,&pixel,index);
1601 if (node_info->child[id] == (NodeInfo *) NULL)
1603 node_info=node_info->child[id];
1606 Find closest color among siblings and their children.
1609 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1611 ClosestColor(image,&cube,node_info->parent);
1612 cube.cache[i]=(ssize_t) cube.color_number;
1615 Assign pixel to closest colormap entry.
1617 index=(size_t) cube.cache[i];
1618 if (image->storage_class == PseudoClass)
1619 SetPixelIndex(image,(Quantum) index,q);
1620 if (cube.quantize_info->measure_error == MagickFalse)
1622 SetPixelRed(image,image->colormap[index].red,q);
1623 SetPixelGreen(image,image->colormap[index].green,q);
1624 SetPixelBlue(image,image->colormap[index].blue,q);
1625 if (cube.associate_alpha != MagickFalse)
1626 SetPixelAlpha(image,image->colormap[index].alpha,q);
1628 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1633 AssociateAlphaPixelPacket(image,&cube,image->colormap+index,&color);
1634 current[u].red=pixel.red-color.red;
1635 current[u].green=pixel.green-color.green;
1636 current[u].blue=pixel.blue-color.blue;
1637 if (cube.associate_alpha != MagickFalse)
1638 current[u].alpha=pixel.alpha-color.alpha;
1639 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1644 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1645 #pragma omp critical (MagickCore_FloydSteinbergDither)
1647 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1649 if (proceed == MagickFalse)
1652 q+=((y+1) & 0x01)*GetPixelChannels(image);
1655 image_view=DestroyCacheView(image_view);
1656 pixels=DestroyPixelThreadSet(pixels);
1660 static MagickBooleanType
1661 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1663 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1664 const size_t level,const unsigned int direction)
1671 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1672 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1673 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1678 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1679 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1680 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1685 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1686 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1687 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1692 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1693 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1694 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1705 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1707 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1708 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1709 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1710 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1711 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1716 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1717 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1718 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1719 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1720 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1721 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1722 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1727 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1728 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1729 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1730 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1731 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1732 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1733 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1738 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1739 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1740 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1741 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1742 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1743 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1744 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1752 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1753 CubeInfo *cube_info,const unsigned int direction)
1755 #define DitherImageTag "Dither/Image"
1771 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1772 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1786 exception=(&image->exception);
1787 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1788 if (q == (const Quantum *) NULL)
1789 return(MagickFalse);
1790 AssociateAlphaPixel(image,cube_info,q,&pixel);
1791 for (i=0; i < ErrorQueueLength; i++)
1793 pixel.red+=p->weights[i]*p->error[i].red;
1794 pixel.green+=p->weights[i]*p->error[i].green;
1795 pixel.blue+=p->weights[i]*p->error[i].blue;
1796 if (cube_info->associate_alpha != MagickFalse)
1797 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1799 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1800 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1801 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1802 if (cube_info->associate_alpha != MagickFalse)
1803 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
1804 i=CacheOffset(cube_info,&pixel);
1805 if (p->cache[i] < 0)
1814 Identify the deepest node containing the pixel's color.
1817 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1819 id=ColorToNodeId(cube_info,&pixel,index);
1820 if (node_info->child[id] == (NodeInfo *) NULL)
1822 node_info=node_info->child[id];
1824 node_info=node_info->parent;
1826 Find closest color among siblings and their children.
1829 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1830 QuantumRange+1.0)+1.0);
1831 ClosestColor(image,p,node_info->parent);
1832 p->cache[i]=(ssize_t) p->color_number;
1835 Assign pixel to closest colormap entry.
1837 index=(size_t) p->cache[i];
1838 if (image->storage_class == PseudoClass)
1839 SetPixelIndex(image,(Quantum) index,q);
1840 if (cube_info->quantize_info->measure_error == MagickFalse)
1842 SetPixelRed(image,image->colormap[index].red,q);
1843 SetPixelGreen(image,image->colormap[index].green,q);
1844 SetPixelBlue(image,image->colormap[index].blue,q);
1845 if (cube_info->associate_alpha != MagickFalse)
1846 SetPixelAlpha(image,image->colormap[index].alpha,q);
1848 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1849 return(MagickFalse);
1851 Propagate the error as the last entry of the error queue.
1853 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1854 sizeof(p->error[0]));
1855 AssociateAlphaPixelPacket(image,cube_info,image->colormap+index,&color);
1856 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1857 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1858 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1859 if (cube_info->associate_alpha != MagickFalse)
1860 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1861 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1862 if (proceed == MagickFalse)
1863 return(MagickFalse);
1868 case WestGravity: p->x--; break;
1869 case EastGravity: p->x++; break;
1870 case NorthGravity: p->y--; break;
1871 case SouthGravity: p->y++; break;
1876 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1883 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1890 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1904 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1905 return(FloydSteinbergDither(image,cube_info));
1907 Distribute quantization error along a Hilbert curve.
1909 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1910 sizeof(*cube_info->error));
1913 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1914 for (depth=1; i != 0; depth++)
1916 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1918 cube_info->offset=0;
1919 cube_info->span=(MagickSizeType) image->columns*image->rows;
1920 image_view=AcquireCacheView(image);
1922 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1923 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1924 image_view=DestroyCacheView(image_view);
1929 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1933 + G e t C u b e I n f o %
1937 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1939 % GetCubeInfo() initialize the Cube data structure.
1941 % The format of the GetCubeInfo method is:
1943 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1944 % const size_t depth,const size_t maximum_colors)
1946 % A description of each parameter follows.
1948 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1950 % o depth: Normally, this integer value is zero or one. A zero or
1951 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1952 % A tree of this depth generally allows the best representation of the
1953 % reference image with the least amount of memory and the fastest
1954 % computational speed. In some cases, such as an image with low color
1955 % dispersion (a few number of colors), a value other than
1956 % Log4(number_colors) is required. To expand the color tree completely,
1959 % o maximum_colors: maximum colors.
1962 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1963 const size_t depth,const size_t maximum_colors)
1979 Initialize tree to describe color cube_info.
1981 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1982 if (cube_info == (CubeInfo *) NULL)
1983 return((CubeInfo *) NULL);
1984 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1985 cube_info->depth=depth;
1986 if (cube_info->depth > MaxTreeDepth)
1987 cube_info->depth=MaxTreeDepth;
1988 if (cube_info->depth < 2)
1990 cube_info->maximum_colors=maximum_colors;
1992 Initialize root node.
1994 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1995 if (cube_info->root == (NodeInfo *) NULL)
1996 return((CubeInfo *) NULL);
1997 cube_info->root->parent=cube_info->root;
1998 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1999 if (cube_info->quantize_info->dither == MagickFalse)
2002 Initialize dither resources.
2004 length=(size_t) (1UL << (4*(8-CacheShift)));
2005 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
2006 sizeof(*cube_info->cache));
2007 if (cube_info->cache == (ssize_t *) NULL)
2008 return((CubeInfo *) NULL);
2010 Initialize color cache.
2012 for (i=0; i < (ssize_t) length; i++)
2013 cube_info->cache[i]=(-1);
2015 Distribute weights along a curve of exponential decay.
2018 for (i=0; i < ErrorQueueLength; i++)
2020 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2021 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2024 Normalize the weighting factors.
2027 for (i=0; i < ErrorQueueLength; i++)
2028 weight+=cube_info->weights[i];
2030 for (i=0; i < ErrorQueueLength; i++)
2032 cube_info->weights[i]/=weight;
2033 sum+=cube_info->weights[i];
2035 cube_info->weights[0]+=1.0-sum;
2040 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2044 + G e t N o d e I n f o %
2048 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2050 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2051 % presets all fields to zero.
2053 % The format of the GetNodeInfo method is:
2055 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2056 % const size_t level,NodeInfo *parent)
2058 % A description of each parameter follows.
2060 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2062 % o id: Specifies the child number of the node.
2064 % o level: Specifies the level in the storage_class the node resides.
2067 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2068 const size_t level,NodeInfo *parent)
2073 if (cube_info->free_nodes == 0)
2079 Allocate a new queue of nodes.
2081 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2082 if (nodes == (Nodes *) NULL)
2083 return((NodeInfo *) NULL);
2084 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2085 sizeof(*nodes->nodes));
2086 if (nodes->nodes == (NodeInfo *) NULL)
2087 return((NodeInfo *) NULL);
2088 nodes->next=cube_info->node_queue;
2089 cube_info->node_queue=nodes;
2090 cube_info->next_node=nodes->nodes;
2091 cube_info->free_nodes=NodesInAList;
2094 cube_info->free_nodes--;
2095 node_info=cube_info->next_node++;
2096 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2097 node_info->parent=parent;
2099 node_info->level=level;
2104 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2108 % G e t I m a g e Q u a n t i z e E r r o r %
2112 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2114 % GetImageQuantizeError() measures the difference between the original
2115 % and quantized images. This difference is the total quantization error.
2116 % The error is computed by summing over all pixels in an image the distance
2117 % squared in RGB space between each reference pixel value and its quantized
2118 % value. These values are computed:
2120 % o mean_error_per_pixel: This value is the mean error for any single
2121 % pixel in the image.
2123 % o normalized_mean_square_error: This value is the normalized mean
2124 % quantization error for any single pixel in the image. This distance
2125 % measure is normalized to a range between 0 and 1. It is independent
2126 % of the range of red, green, and blue values in the image.
2128 % o normalized_maximum_square_error: Thsi value is the normalized
2129 % maximum quantization error for any single pixel in the image. This
2130 % distance measure is normalized to a range between 0 and 1. It is
2131 % independent of the range of red, green, and blue values in your image.
2133 % The format of the GetImageQuantizeError method is:
2135 % MagickBooleanType GetImageQuantizeError(Image *image)
2137 % A description of each parameter follows.
2139 % o image: the image.
2142 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2157 mean_error_per_pixel;
2165 assert(image != (Image *) NULL);
2166 assert(image->signature == MagickSignature);
2167 if (image->debug != MagickFalse)
2168 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2169 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2170 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2171 if (image->storage_class == DirectClass)
2175 area=3.0*image->columns*image->rows;
2177 mean_error_per_pixel=0.0;
2179 exception=(&image->exception);
2180 image_view=AcquireCacheView(image);
2181 for (y=0; y < (ssize_t) image->rows; y++)
2183 register const Quantum
2189 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2190 if (p == (const Quantum *) NULL)
2192 for (x=0; x < (ssize_t) image->columns; x++)
2194 index=1UL*GetPixelIndex(image,p);
2195 if (image->matte != MagickFalse)
2197 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,p));
2198 beta=(MagickRealType) (QuantumScale*image->colormap[index].alpha);
2200 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2201 image->colormap[index].red);
2202 mean_error_per_pixel+=distance;
2203 mean_error+=distance*distance;
2204 if (distance > maximum_error)
2205 maximum_error=distance;
2206 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2207 image->colormap[index].green);
2208 mean_error_per_pixel+=distance;
2209 mean_error+=distance*distance;
2210 if (distance > maximum_error)
2211 maximum_error=distance;
2212 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2213 image->colormap[index].blue);
2214 mean_error_per_pixel+=distance;
2215 mean_error+=distance*distance;
2216 if (distance > maximum_error)
2217 maximum_error=distance;
2218 p+=GetPixelChannels(image);
2221 image_view=DestroyCacheView(image_view);
2222 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2223 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2225 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2230 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2234 % G e t Q u a n t i z e I n f o %
2238 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2240 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2242 % The format of the GetQuantizeInfo method is:
2244 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2246 % A description of each parameter follows:
2248 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2251 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2253 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2254 assert(quantize_info != (QuantizeInfo *) NULL);
2255 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2256 quantize_info->number_colors=256;
2257 quantize_info->dither=MagickTrue;
2258 quantize_info->dither_method=RiemersmaDitherMethod;
2259 quantize_info->colorspace=UndefinedColorspace;
2260 quantize_info->measure_error=MagickFalse;
2261 quantize_info->signature=MagickSignature;
2265 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2269 % P o s t e r i z e I m a g e C h a n n e l %
2273 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2275 % PosterizeImage() reduces the image to a limited number of colors for a
2278 % The format of the PosterizeImage method is:
2280 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2281 % const MagickBooleanType dither)
2282 % MagickBooleanType PosterizeImageChannel(Image *image,
2283 % const ChannelType channel,const size_t levels,
2284 % const MagickBooleanType dither)
2286 % A description of each parameter follows:
2288 % o image: Specifies a pointer to an Image structure.
2290 % o levels: Number of color levels allowed in each channel. Very low values
2291 % (2, 3, or 4) have the most visible effect.
2293 % o dither: Set this integer value to something other than zero to dither
2298 static inline ssize_t MagickRound(MagickRealType x)
2301 Round the fraction to nearest integer.
2304 return((ssize_t) (x+0.5));
2305 return((ssize_t) (x-0.5));
2308 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2309 const MagickBooleanType dither)
2314 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2318 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2319 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2321 #define PosterizeImageTag "Posterize/Image"
2322 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2323 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2346 assert(image != (Image *) NULL);
2347 assert(image->signature == MagickSignature);
2348 if (image->debug != MagickFalse)
2349 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2350 if (image->storage_class == PseudoClass)
2351 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2352 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2354 for (i=0; i < (ssize_t) image->colors; i++)
2359 if ((GetPixelRedTraits(image) & ActivePixelTrait) != 0)
2360 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2361 if ((GetPixelGreenTraits(image) & ActivePixelTrait) != 0)
2362 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2363 if ((GetPixelBlueTraits(image) & ActivePixelTrait) != 0)
2364 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2365 if ((GetPixelAlphaTraits(image) & ActivePixelTrait) != 0)
2366 image->colormap[i].alpha=PosterizePixel(image->colormap[i].alpha);
2373 exception=(&image->exception);
2374 image_view=AcquireCacheView(image);
2375 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2376 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2378 for (y=0; y < (ssize_t) image->rows; y++)
2386 if (status == MagickFalse)
2388 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2389 if (q == (const Quantum *) NULL)
2394 for (x=0; x < (ssize_t) image->columns; x++)
2396 if ((GetPixelRedTraits(image) & ActivePixelTrait) != 0)
2397 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2398 if ((GetPixelGreenTraits(image) & ActivePixelTrait) != 0)
2399 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2400 if ((GetPixelBlueTraits(image) & ActivePixelTrait) != 0)
2401 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2402 if (((GetPixelBlackTraits(image) & ActivePixelTrait) != 0) &&
2403 (image->colorspace == CMYKColorspace))
2404 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2405 if (((GetPixelAlphaTraits(image) & ActivePixelTrait) != 0) &&
2406 (image->matte == MagickTrue))
2407 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2408 q+=GetPixelChannels(image);
2410 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2412 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2417 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2418 #pragma omp critical (MagickCore_PosterizeImageChannel)
2420 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2422 if (proceed == MagickFalse)
2426 image_view=DestroyCacheView(image_view);
2427 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2428 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2429 levels,MaxColormapSize+1);
2430 quantize_info->dither=dither;
2431 quantize_info->tree_depth=MaxTreeDepth;
2432 status=QuantizeImage(quantize_info,image);
2433 quantize_info=DestroyQuantizeInfo(quantize_info);
2438 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2442 + P r u n e C h i l d %
2446 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2448 % PruneChild() deletes the given node and merges its statistics into its
2451 % The format of the PruneSubtree method is:
2453 % PruneChild(const Image *image,CubeInfo *cube_info,
2454 % const NodeInfo *node_info)
2456 % A description of each parameter follows.
2458 % o image: the image.
2460 % o cube_info: A pointer to the Cube structure.
2462 % o node_info: pointer to node in color cube tree that is to be pruned.
2465 static void PruneChild(const Image *image,CubeInfo *cube_info,
2466 const NodeInfo *node_info)
2478 Traverse any children.
2480 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2481 for (i=0; i < (ssize_t) number_children; i++)
2482 if (node_info->child[i] != (NodeInfo *) NULL)
2483 PruneChild(image,cube_info,node_info->child[i]);
2485 Merge color statistics into parent.
2487 parent=node_info->parent;
2488 parent->number_unique+=node_info->number_unique;
2489 parent->total_color.red+=node_info->total_color.red;
2490 parent->total_color.green+=node_info->total_color.green;
2491 parent->total_color.blue+=node_info->total_color.blue;
2492 parent->total_color.alpha+=node_info->total_color.alpha;
2493 parent->child[node_info->id]=(NodeInfo *) NULL;
2498 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2502 + P r u n e L e v e l %
2506 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2508 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2509 % their color statistics into their parent node.
2511 % The format of the PruneLevel method is:
2513 % PruneLevel(const Image *image,CubeInfo *cube_info,
2514 % const NodeInfo *node_info)
2516 % A description of each parameter follows.
2518 % o image: the image.
2520 % o cube_info: A pointer to the Cube structure.
2522 % o node_info: pointer to node in color cube tree that is to be pruned.
2525 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2526 const NodeInfo *node_info)
2535 Traverse any children.
2537 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2538 for (i=0; i < (ssize_t) number_children; i++)
2539 if (node_info->child[i] != (NodeInfo *) NULL)
2540 PruneLevel(image,cube_info,node_info->child[i]);
2541 if (node_info->level == cube_info->depth)
2542 PruneChild(image,cube_info,node_info);
2546 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2550 + P r u n e T o C u b e D e p t h %
2554 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2556 % PruneToCubeDepth() deletes any nodes at a depth greater than
2557 % cube_info->depth while merging their color statistics into their parent
2560 % The format of the PruneToCubeDepth method is:
2562 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2563 % const NodeInfo *node_info)
2565 % A description of each parameter follows.
2567 % o cube_info: A pointer to the Cube structure.
2569 % o node_info: pointer to node in color cube tree that is to be pruned.
2572 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2573 const NodeInfo *node_info)
2582 Traverse any children.
2584 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2585 for (i=0; i < (ssize_t) number_children; i++)
2586 if (node_info->child[i] != (NodeInfo *) NULL)
2587 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2588 if (node_info->level > cube_info->depth)
2589 PruneChild(image,cube_info,node_info);
2593 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2597 % Q u a n t i z e I m a g e %
2601 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2603 % QuantizeImage() analyzes the colors within a reference image and chooses a
2604 % fixed number of colors to represent the image. The goal of the algorithm
2605 % is to minimize the color difference between the input and output image while
2606 % minimizing the processing time.
2608 % The format of the QuantizeImage method is:
2610 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2613 % A description of each parameter follows:
2615 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2617 % o image: the image.
2620 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2633 assert(quantize_info != (const QuantizeInfo *) NULL);
2634 assert(quantize_info->signature == MagickSignature);
2635 assert(image != (Image *) NULL);
2636 assert(image->signature == MagickSignature);
2637 if (image->debug != MagickFalse)
2638 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2639 maximum_colors=quantize_info->number_colors;
2640 if (maximum_colors == 0)
2641 maximum_colors=MaxColormapSize;
2642 if (maximum_colors > MaxColormapSize)
2643 maximum_colors=MaxColormapSize;
2644 if ((IsImageGray(image,&image->exception) != MagickFalse) &&
2645 (image->matte == MagickFalse))
2646 (void) SetGrayscaleImage(image);
2647 if ((image->storage_class == PseudoClass) &&
2648 (image->colors <= maximum_colors))
2650 depth=quantize_info->tree_depth;
2657 Depth of color tree is: Log4(colormap size)+2.
2659 colors=maximum_colors;
2660 for (depth=1; colors != 0; depth++)
2662 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2664 if ((image->matte != MagickFalse) && (depth > 5))
2668 Initialize color cube.
2670 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2671 if (cube_info == (CubeInfo *) NULL)
2672 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2674 status=ClassifyImageColors(cube_info,image,&image->exception);
2675 if (status != MagickFalse)
2678 Reduce the number of colors in the image.
2680 ReduceImageColors(image,cube_info);
2681 status=AssignImageColors(image,cube_info);
2683 DestroyCubeInfo(cube_info);
2688 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2692 % Q u a n t i z e I m a g e s %
2696 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2698 % QuantizeImages() analyzes the colors within a set of reference images and
2699 % chooses a fixed number of colors to represent the set. The goal of the
2700 % algorithm is to minimize the color difference between the input and output
2701 % images while minimizing the processing time.
2703 % The format of the QuantizeImages method is:
2705 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2708 % A description of each parameter follows:
2710 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2712 % o images: Specifies a pointer to a list of Image structures.
2715 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2728 MagickProgressMonitor
2739 assert(quantize_info != (const QuantizeInfo *) NULL);
2740 assert(quantize_info->signature == MagickSignature);
2741 assert(images != (Image *) NULL);
2742 assert(images->signature == MagickSignature);
2743 if (images->debug != MagickFalse)
2744 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2745 if (GetNextImageInList(images) == (Image *) NULL)
2748 Handle a single image with QuantizeImage.
2750 status=QuantizeImage(quantize_info,images);
2754 maximum_colors=quantize_info->number_colors;
2755 if (maximum_colors == 0)
2756 maximum_colors=MaxColormapSize;
2757 if (maximum_colors > MaxColormapSize)
2758 maximum_colors=MaxColormapSize;
2759 depth=quantize_info->tree_depth;
2766 Depth of color tree is: Log4(colormap size)+2.
2768 colors=maximum_colors;
2769 for (depth=1; colors != 0; depth++)
2771 if (quantize_info->dither != MagickFalse)
2775 Initialize color cube.
2777 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2778 if (cube_info == (CubeInfo *) NULL)
2780 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2781 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2782 return(MagickFalse);
2784 number_images=GetImageListLength(images);
2786 for (i=0; image != (Image *) NULL; i++)
2788 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2789 image->client_data);
2790 status=ClassifyImageColors(cube_info,image,&image->exception);
2791 if (status == MagickFalse)
2793 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2794 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2796 if (proceed == MagickFalse)
2798 image=GetNextImageInList(image);
2800 if (status != MagickFalse)
2803 Reduce the number of colors in an image sequence.
2805 ReduceImageColors(images,cube_info);
2807 for (i=0; image != (Image *) NULL; i++)
2809 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2810 NULL,image->client_data);
2811 status=AssignImageColors(image,cube_info);
2812 if (status == MagickFalse)
2814 (void) SetImageProgressMonitor(image,progress_monitor,
2815 image->client_data);
2816 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2818 if (proceed == MagickFalse)
2820 image=GetNextImageInList(image);
2823 DestroyCubeInfo(cube_info);
2828 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2836 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2838 % Reduce() traverses the color cube tree and prunes any node whose
2839 % quantization error falls below a particular threshold.
2841 % The format of the Reduce method is:
2843 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2845 % A description of each parameter follows.
2847 % o image: the image.
2849 % o cube_info: A pointer to the Cube structure.
2851 % o node_info: pointer to node in color cube tree that is to be pruned.
2854 static void Reduce(const Image *image,CubeInfo *cube_info,
2855 const NodeInfo *node_info)
2864 Traverse any children.
2866 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2867 for (i=0; i < (ssize_t) number_children; i++)
2868 if (node_info->child[i] != (NodeInfo *) NULL)
2869 Reduce(image,cube_info,node_info->child[i]);
2870 if (node_info->quantize_error <= cube_info->pruning_threshold)
2871 PruneChild(image,cube_info,node_info);
2875 Find minimum pruning threshold.
2877 if (node_info->number_unique > 0)
2878 cube_info->colors++;
2879 if (node_info->quantize_error < cube_info->next_threshold)
2880 cube_info->next_threshold=node_info->quantize_error;
2885 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2889 + R e d u c e I m a g e C o l o r s %
2893 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2895 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
2896 % with n2 > 0 is less than or equal to the maximum number of colors allowed
2897 % in the output image. On any given iteration over the tree, it selects
2898 % those nodes whose E value is minimal for pruning and merges their
2899 % color statistics upward. It uses a pruning threshold, Ep, to govern
2900 % node selection as follows:
2903 % while number of nodes with (n2 > 0) > required maximum number of colors
2904 % prune all nodes such that E <= Ep
2905 % Set Ep to minimum E in remaining nodes
2907 % This has the effect of minimizing any quantization error when merging
2908 % two nodes together.
2910 % When a node to be pruned has offspring, the pruning procedure invokes
2911 % itself recursively in order to prune the tree from the leaves upward.
2912 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
2913 % corresponding data in that node's parent. This retains the pruned
2914 % node's color characteristics for later averaging.
2916 % For each node, n2 pixels exist for which that node represents the
2917 % smallest volume in RGB space containing those pixel's colors. When n2
2918 % > 0 the node will uniquely define a color in the output image. At the
2919 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
2920 % the tree which represent colors present in the input image.
2922 % The other pixel count, n1, indicates the total number of colors
2923 % within the cubic volume which the node represents. This includes n1 -
2924 % n2 pixels whose colors should be defined by nodes at a lower level in
2927 % The format of the ReduceImageColors method is:
2929 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
2931 % A description of each parameter follows.
2933 % o image: the image.
2935 % o cube_info: A pointer to the Cube structure.
2938 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2940 #define ReduceImageTag "Reduce/Image"
2951 cube_info->next_threshold=0.0;
2952 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2954 cube_info->pruning_threshold=cube_info->next_threshold;
2955 cube_info->next_threshold=cube_info->root->quantize_error-1;
2956 cube_info->colors=0;
2957 Reduce(image,cube_info,cube_info->root);
2958 offset=(MagickOffsetType) span-cube_info->colors;
2959 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2960 cube_info->maximum_colors+1);
2961 if (proceed == MagickFalse)
2967 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2971 % R e m a p I m a g e %
2975 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2977 % RemapImage() replaces the colors of an image with the closest color from
2978 % a reference image.
2980 % The format of the RemapImage method is:
2982 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2983 % Image *image,const Image *remap_image)
2985 % A description of each parameter follows:
2987 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2989 % o image: the image.
2991 % o remap_image: the reference image.
2994 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2995 Image *image,const Image *remap_image)
3004 Initialize color cube.
3006 assert(image != (Image *) NULL);
3007 assert(image->signature == MagickSignature);
3008 if (image->debug != MagickFalse)
3009 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3010 assert(remap_image != (Image *) NULL);
3011 assert(remap_image->signature == MagickSignature);
3012 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3013 quantize_info->number_colors);
3014 if (cube_info == (CubeInfo *) NULL)
3015 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3017 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3018 if (status != MagickFalse)
3021 Classify image colors from the reference image.
3023 cube_info->quantize_info->number_colors=cube_info->colors;
3024 status=AssignImageColors(image,cube_info);
3026 DestroyCubeInfo(cube_info);
3031 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3035 % R e m a p I m a g e s %
3039 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3041 % RemapImages() replaces the colors of a sequence of images with the
3042 % closest color from a reference image.
3044 % The format of the RemapImage method is:
3046 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3047 % Image *images,Image *remap_image)
3049 % A description of each parameter follows:
3051 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3053 % o images: the image sequence.
3055 % o remap_image: the reference image.
3058 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3059 Image *images,const Image *remap_image)
3070 assert(images != (Image *) NULL);
3071 assert(images->signature == MagickSignature);
3072 if (images->debug != MagickFalse)
3073 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3075 if (remap_image == (Image *) NULL)
3078 Create a global colormap for an image sequence.
3080 status=QuantizeImages(quantize_info,images);
3084 Classify image colors from the reference image.
3086 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3087 quantize_info->number_colors);
3088 if (cube_info == (CubeInfo *) NULL)
3089 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3091 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3092 if (status != MagickFalse)
3095 Classify image colors from the reference image.
3097 cube_info->quantize_info->number_colors=cube_info->colors;
3099 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3101 status=AssignImageColors(image,cube_info);
3102 if (status == MagickFalse)
3106 DestroyCubeInfo(cube_info);
3111 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3115 % S e t G r a y s c a l e I m a g e %
3119 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3121 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3123 % The format of the SetGrayscaleImage method is:
3125 % MagickBooleanType SetGrayscaleImage(Image *image)
3127 % A description of each parameter follows:
3129 % o image: The image.
3133 #if defined(__cplusplus) || defined(c_plusplus)
3137 static int IntensityCompare(const void *x,const void *y)
3146 color_1=(PixelPacket *) x;
3147 color_2=(PixelPacket *) y;
3148 intensity=GetPixelPacketIntensity(color_1)-(ssize_t)
3149 GetPixelPacketIntensity(color_2);
3150 return((int) intensity);
3153 #if defined(__cplusplus) || defined(c_plusplus)
3157 static MagickBooleanType SetGrayscaleImage(Image *image)
3179 assert(image != (Image *) NULL);
3180 assert(image->signature == MagickSignature);
3181 if (image->type != GrayscaleType)
3182 (void) TransformImageColorspace(image,GRAYColorspace);
3183 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3184 sizeof(*colormap_index));
3185 if (colormap_index == (ssize_t *) NULL)
3186 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3188 if (image->storage_class != PseudoClass)
3193 for (i=0; i <= (ssize_t) MaxMap; i++)
3194 colormap_index[i]=(-1);
3195 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3196 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3200 exception=(&image->exception);
3201 image_view=AcquireCacheView(image);
3202 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3203 #pragma omp parallel for schedule(dynamic,4) shared(status)
3205 for (y=0; y < (ssize_t) image->rows; y++)
3213 if (status == MagickFalse)
3215 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3217 if (q == (const Quantum *) NULL)
3222 for (x=0; x < (ssize_t) image->columns; x++)
3227 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3228 if (colormap_index[intensity] < 0)
3230 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3231 #pragma omp critical (MagickCore_SetGrayscaleImage)
3233 if (colormap_index[intensity] < 0)
3235 colormap_index[intensity]=(ssize_t) image->colors;
3236 image->colormap[image->colors].red=GetPixelRed(image,q);
3237 image->colormap[image->colors].green=GetPixelGreen(image,q);
3238 image->colormap[image->colors].blue=GetPixelBlue(image,q);
3242 SetPixelIndex(image,(Quantum)
3243 colormap_index[intensity],q);
3244 q+=GetPixelChannels(image);
3246 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3249 image_view=DestroyCacheView(image_view);
3251 for (i=0; i < (ssize_t) image->colors; i++)
3252 image->colormap[i].alpha=(unsigned short) i;
3253 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3255 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3257 if (colormap == (PixelPacket *) NULL)
3258 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3261 colormap[j]=image->colormap[0];
3262 for (i=0; i < (ssize_t) image->colors; i++)
3264 if (IsPixelPacketEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3267 colormap[j]=image->colormap[i];
3269 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3271 image->colors=(size_t) (j+1);
3272 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3273 image->colormap=colormap;
3275 exception=(&image->exception);
3276 image_view=AcquireCacheView(image);
3277 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3278 #pragma omp parallel for schedule(dynamic,4) shared(status)
3280 for (y=0; y < (ssize_t) image->rows; y++)
3288 if (status == MagickFalse)
3290 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3291 if (q == (const Quantum *) NULL)
3296 for (x=0; x < (ssize_t) image->columns; x++)
3298 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3299 GetPixelIndex(image,q))],q);
3300 q+=GetPixelChannels(image);
3302 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3305 image_view=DestroyCacheView(image_view);
3306 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3307 image->type=GrayscaleType;
3308 if (IsImageMonochrome(image,&image->exception) != MagickFalse)
3309 image->type=BilevelType;