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-2013 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/pixel-private.h"
198 #include "MagickCore/quantize.h"
199 #include "MagickCore/quantum.h"
200 #include "MagickCore/quantum-private.h"
201 #include "MagickCore/resource_.h"
202 #include "MagickCore/string_.h"
203 #include "MagickCore/thread-private.h"
208 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
213 #define ErrorQueueLength 16
214 #define MaxNodes 266817
215 #define MaxTreeDepth 8
216 #define NodesInAList 1920
221 typedef struct _RealPixelInfo
230 typedef struct _NodeInfo
251 typedef struct _Nodes
260 typedef struct _CubeInfo
298 error[ErrorQueueLength];
301 weights[ErrorQueueLength];
327 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
330 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
332 static MagickBooleanType
333 AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
334 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
335 DitherImage(Image *,CubeInfo *,ExceptionInfo *),
336 SetGrayscaleImage(Image *,ExceptionInfo *);
339 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
342 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
343 DestroyCubeInfo(CubeInfo *),
344 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
345 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
346 ReduceImageColors(const Image *,CubeInfo *);
349 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
353 % A c q u i r e Q u a n t i z e I n f o %
357 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
359 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
361 % The format of the AcquireQuantizeInfo method is:
363 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
365 % A description of each parameter follows:
367 % o image_info: the image info.
370 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
375 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
376 if (quantize_info == (QuantizeInfo *) NULL)
377 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
378 GetQuantizeInfo(quantize_info);
379 if (image_info != (ImageInfo *) NULL)
384 quantize_info->dither_method=image_info->dither == MagickFalse ?
385 NoDitherMethod : RiemersmaDitherMethod;
386 option=GetImageOption(image_info,"dither");
387 if (option != (const char *) NULL)
388 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
389 MagickDitherOptions,MagickFalse,option);
390 quantize_info->measure_error=image_info->verbose;
392 return(quantize_info);
396 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
400 + A s s i g n I m a g e C o l o r s %
404 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
406 % AssignImageColors() generates the output image from the pruned tree. The
407 % output image consists of two parts: (1) A color map, which is an array
408 % of color descriptions (RGB triples) for each color present in the
409 % output image; (2) A pixel array, which represents each pixel as an
410 % index into the color map array.
412 % First, the assignment phase makes one pass over the pruned color
413 % description tree to establish the image's color map. For each node
414 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
415 % color of all pixels that classify no lower than this node. Each of
416 % these colors becomes an entry in the color map.
418 % Finally, the assignment phase reclassifies each pixel in the pruned
419 % tree to identify the deepest node containing the pixel's color. The
420 % pixel's value in the pixel array becomes the index of this node's mean
421 % color in the color map.
423 % The format of the AssignImageColors() method is:
425 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
427 % A description of each parameter follows.
429 % o image: the image.
431 % o cube_info: A pointer to the Cube structure.
435 static inline void AssociateAlphaPixel(const Image *image,
436 const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
441 if ((cube_info->associate_alpha == MagickFalse) ||
442 (GetPixelAlpha(image,pixel)== OpaqueAlpha))
444 alpha_pixel->red=(double) GetPixelRed(image,pixel);
445 alpha_pixel->green=(double) GetPixelGreen(image,pixel);
446 alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
447 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
450 alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
451 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
452 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
453 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
454 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
457 static inline void AssociateAlphaPixelInfo(const Image *image,
458 const CubeInfo *cube_info,const PixelInfo *pixel,
459 RealPixelInfo *alpha_pixel)
464 if ((cube_info->associate_alpha == MagickFalse) ||
465 (pixel->alpha == OpaqueAlpha))
467 alpha_pixel->red=(double) pixel->red;
468 alpha_pixel->green=(double) pixel->green;
469 alpha_pixel->blue=(double) pixel->blue;
470 alpha_pixel->alpha=(double) pixel->alpha;
473 alpha=(double) (QuantumScale*pixel->alpha);
474 alpha_pixel->red=alpha*pixel->red;
475 alpha_pixel->green=alpha*pixel->green;
476 alpha_pixel->blue=alpha*pixel->blue;
477 alpha_pixel->alpha=(double) pixel->alpha;
480 static inline Quantum ClampPixel(const MagickRealType value)
484 if (value >= (MagickRealType) QuantumRange)
485 return((Quantum) QuantumRange);
486 #if !defined(MAGICKCORE_HDRI_SUPPORT)
487 return((Quantum) (value+0.5f));
493 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
494 const RealPixelInfo *pixel,size_t index)
499 id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
500 ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
501 ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
502 if (cube_info->associate_alpha != MagickFalse)
503 id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
507 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
508 ExceptionInfo *exception)
510 #define AssignImageTag "Assign/Image"
516 Allocate image colormap.
518 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
519 (cube_info->quantize_info->colorspace != CMYKColorspace))
520 (void) TransformImageColorspace((Image *) image,
521 cube_info->quantize_info->colorspace,exception);
523 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
524 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
525 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
526 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
529 cube_info->transparent_pixels=0;
530 cube_info->transparent_index=(-1);
531 (void) DefineImageColormap(image,cube_info,cube_info->root);
533 Create a reduced color image.
535 if ((cube_info->quantize_info->dither_method != NoDitherMethod) &&
536 (cube_info->quantize_info->dither_method != NoDitherMethod))
537 (void) DitherImage(image,cube_info,exception);
547 image_view=AcquireAuthenticCacheView(image,exception);
548 #if defined(MAGICKCORE_OPENMP_SUPPORT)
549 #pragma omp parallel for schedule(static,4) shared(status) \
550 magick_threads(image,image,image->rows,1)
552 for (y=0; y < (ssize_t) image->rows; y++)
566 if (status == MagickFalse)
568 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
570 if (q == (Quantum *) NULL)
576 for (x=0; x < (ssize_t) image->columns; x+=count)
581 register const NodeInfo
592 Identify the deepest node containing the pixel's color.
594 for (count=1; (x+count) < (ssize_t) image->columns; count++)
599 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
600 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
603 AssociateAlphaPixel(image,&cube,q,&pixel);
605 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
607 id=ColorToNodeId(&cube,&pixel,index);
608 if (node_info->child[id] == (NodeInfo *) NULL)
610 node_info=node_info->child[id];
613 Find closest color among siblings and their children.
616 cube.distance=(double) (4.0*(QuantumRange+1.0)*
617 (QuantumRange+1.0)+1.0);
618 ClosestColor(image,&cube,node_info->parent);
619 index=cube.color_number;
620 for (i=0; i < (ssize_t) count; i++)
622 if (image->storage_class == PseudoClass)
623 SetPixelIndex(image,(Quantum) index,q);
624 if (cube.quantize_info->measure_error == MagickFalse)
626 SetPixelRed(image,ClampToQuantum(
627 image->colormap[index].red),q);
628 SetPixelGreen(image,ClampToQuantum(
629 image->colormap[index].green),q);
630 SetPixelBlue(image,ClampToQuantum(
631 image->colormap[index].blue),q);
632 if (cube.associate_alpha != MagickFalse)
633 SetPixelAlpha(image,ClampToQuantum(
634 image->colormap[index].alpha),q);
636 q+=GetPixelChannels(image);
639 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
641 if (image->progress_monitor != (MagickProgressMonitor) NULL)
646 #if defined(MAGICKCORE_OPENMP_SUPPORT)
647 #pragma omp critical (MagickCore_AssignImageColors)
649 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
651 if (proceed == MagickFalse)
655 image_view=DestroyCacheView(image_view);
657 if (cube_info->quantize_info->measure_error != MagickFalse)
658 (void) GetImageQuantizeError(image,exception);
659 if ((cube_info->quantize_info->number_colors == 2) &&
660 (cube_info->quantize_info->colorspace == GRAYColorspace))
675 for (i=0; i < (ssize_t) image->colors; i++)
677 intensity=(double) ((double) GetPixelInfoIntensity(q) <
678 ((double) QuantumRange/2.0) ? 0 : QuantumRange);
685 (void) SyncImage(image,exception);
686 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
687 (cube_info->quantize_info->colorspace != CMYKColorspace))
688 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
693 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
697 + C l a s s i f y I m a g e C o l o r s %
701 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
703 % ClassifyImageColors() begins by initializing a color description tree
704 % of sufficient depth to represent each possible input color in a leaf.
705 % However, it is impractical to generate a fully-formed color
706 % description tree in the storage_class phase for realistic values of
707 % Cmax. If colors components in the input image are quantized to k-bit
708 % precision, so that Cmax= 2k-1, the tree would need k levels below the
709 % root node to allow representing each possible input color in a leaf.
710 % This becomes prohibitive because the tree's total number of nodes is
713 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
714 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
715 % Initializes data structures for nodes only as they are needed; (2)
716 % Chooses a maximum depth for the tree as a function of the desired
717 % number of colors in the output image (currently log2(colormap size)).
719 % For each pixel in the input image, storage_class scans downward from
720 % the root of the color description tree. At each level of the tree it
721 % identifies the single node which represents a cube in RGB space
722 % containing It updates the following data for each such node:
724 % n1 : Number of pixels whose color is contained in the RGB cube
725 % which this node represents;
727 % n2 : Number of pixels whose color is not represented in a node at
728 % lower depth in the tree; initially, n2 = 0 for all nodes except
729 % leaves of the tree.
731 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
732 % all pixels not classified at a lower depth. The combination of
733 % these sums and n2 will ultimately characterize the mean color of a
734 % set of pixels represented by this node.
736 % E: the distance squared in RGB space between each pixel contained
737 % within a node and the nodes' center. This represents the quantization
740 % The format of the ClassifyImageColors() method is:
742 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
743 % const Image *image,ExceptionInfo *exception)
745 % A description of each parameter follows.
747 % o cube_info: A pointer to the Cube structure.
749 % o image: the image.
753 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
758 associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
760 if (cube_info->quantize_info->colorspace == TransparentColorspace)
761 associate_alpha=MagickFalse;
762 if ((cube_info->quantize_info->number_colors == 2) &&
763 (cube_info->quantize_info->colorspace == GRAYColorspace))
764 associate_alpha=MagickFalse;
765 cube_info->associate_alpha=associate_alpha;
768 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
769 const Image *image,ExceptionInfo *exception)
771 #define ClassifyImageTag "Classify/Image"
801 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
803 SetAssociatedAlpha(image,cube_info);
804 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
805 (cube_info->quantize_info->colorspace != CMYKColorspace))
806 (void) TransformImageColorspace((Image *) image,
807 cube_info->quantize_info->colorspace,exception);
809 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
810 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
811 midpoint.red=(double) QuantumRange/2.0;
812 midpoint.green=(double) QuantumRange/2.0;
813 midpoint.blue=(double) QuantumRange/2.0;
814 midpoint.alpha=(double) QuantumRange/2.0;
816 image_view=AcquireVirtualCacheView(image,exception);
817 for (y=0; y < (ssize_t) image->rows; y++)
819 register const Quantum
825 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
826 if (p == (const Quantum *) NULL)
828 if (cube_info->nodes > MaxNodes)
831 Prune one level if the color tree is too large.
833 PruneLevel(image,cube_info,cube_info->root);
836 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
839 Start at the root and descend the color cube tree.
841 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
846 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
847 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
850 AssociateAlphaPixel(image,cube_info,p,&pixel);
851 index=MaxTreeDepth-1;
852 bisect=((double) QuantumRange+1.0)/2.0;
854 node_info=cube_info->root;
855 for (level=1; level <= MaxTreeDepth; level++)
858 id=ColorToNodeId(cube_info,&pixel,index);
859 mid.red+=(id & 1) != 0 ? bisect : -bisect;
860 mid.green+=(id & 2) != 0 ? bisect : -bisect;
861 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
862 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
863 if (node_info->child[id] == (NodeInfo *) NULL)
866 Set colors of new node to contain pixel.
868 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
869 if (node_info->child[id] == (NodeInfo *) NULL)
870 (void) ThrowMagickException(exception,GetMagickModule(),
871 ResourceLimitError,"MemoryAllocationFailed","`%s'",
873 if (level == MaxTreeDepth)
877 Approximate the quantization error represented by this node.
879 node_info=node_info->child[id];
880 error.red=QuantumScale*(pixel.red-mid.red);
881 error.green=QuantumScale*(pixel.green-mid.green);
882 error.blue=QuantumScale*(pixel.blue-mid.blue);
883 if (cube_info->associate_alpha != MagickFalse)
884 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
885 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
886 count*error.green*error.green+count*error.blue*error.blue+count*
887 error.alpha*error.alpha));
888 cube_info->root->quantize_error+=node_info->quantize_error;
892 Sum RGB for this leaf for later derivation of the mean cube color.
894 node_info->number_unique+=count;
895 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
896 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
897 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
898 if (cube_info->associate_alpha != MagickFalse)
899 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
901 p+=count*GetPixelChannels(image);
903 if (cube_info->colors > cube_info->maximum_colors)
905 PruneToCubeDepth(image,cube_info,cube_info->root);
908 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
910 if (proceed == MagickFalse)
913 for (y++; y < (ssize_t) image->rows; y++)
915 register const Quantum
921 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
922 if (p == (const Quantum *) NULL)
924 if (cube_info->nodes > MaxNodes)
927 Prune one level if the color tree is too large.
929 PruneLevel(image,cube_info,cube_info->root);
932 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
935 Start at the root and descend the color cube tree.
937 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
942 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
943 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
946 AssociateAlphaPixel(image,cube_info,p,&pixel);
947 index=MaxTreeDepth-1;
948 bisect=((double) QuantumRange+1.0)/2.0;
950 node_info=cube_info->root;
951 for (level=1; level <= cube_info->depth; level++)
954 id=ColorToNodeId(cube_info,&pixel,index);
955 mid.red+=(id & 1) != 0 ? bisect : -bisect;
956 mid.green+=(id & 2) != 0 ? bisect : -bisect;
957 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
958 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
959 if (node_info->child[id] == (NodeInfo *) NULL)
962 Set colors of new node to contain pixel.
964 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
965 if (node_info->child[id] == (NodeInfo *) NULL)
966 (void) ThrowMagickException(exception,GetMagickModule(),
967 ResourceLimitError,"MemoryAllocationFailed","%s",
969 if (level == cube_info->depth)
973 Approximate the quantization error represented by this node.
975 node_info=node_info->child[id];
976 error.red=QuantumScale*(pixel.red-mid.red);
977 error.green=QuantumScale*(pixel.green-mid.green);
978 error.blue=QuantumScale*(pixel.blue-mid.blue);
979 if (cube_info->associate_alpha != MagickFalse)
980 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
981 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
982 count*error.green*error.green+count*error.blue*error.blue+count*
983 error.alpha*error.alpha));
984 cube_info->root->quantize_error+=node_info->quantize_error;
988 Sum RGB for this leaf for later derivation of the mean cube color.
990 node_info->number_unique+=count;
991 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
992 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
993 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
994 if (cube_info->associate_alpha != MagickFalse)
995 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
997 p+=count*GetPixelChannels(image);
999 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1001 if (proceed == MagickFalse)
1004 image_view=DestroyCacheView(image_view);
1005 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1006 (cube_info->quantize_info->colorspace != CMYKColorspace))
1007 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1012 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1016 % C l o n e Q u a n t i z e I n f o %
1020 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1022 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1023 % or if quantize info is NULL, a new one.
1025 % The format of the CloneQuantizeInfo method is:
1027 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1029 % A description of each parameter follows:
1031 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1032 % quantize info, or if image info is NULL a new one.
1034 % o quantize_info: a structure of type info.
1037 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1042 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1043 if (clone_info == (QuantizeInfo *) NULL)
1044 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1045 GetQuantizeInfo(clone_info);
1046 if (quantize_info == (QuantizeInfo *) NULL)
1048 clone_info->number_colors=quantize_info->number_colors;
1049 clone_info->tree_depth=quantize_info->tree_depth;
1050 clone_info->dither_method=quantize_info->dither_method;
1051 clone_info->colorspace=quantize_info->colorspace;
1052 clone_info->measure_error=quantize_info->measure_error;
1057 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1061 + C l o s e s t C o l o r %
1065 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1067 % ClosestColor() traverses the color cube tree at a particular node and
1068 % determines which colormap entry best represents the input color.
1070 % The format of the ClosestColor method is:
1072 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1073 % const NodeInfo *node_info)
1075 % A description of each parameter follows.
1077 % o image: the image.
1079 % o cube_info: A pointer to the Cube structure.
1081 % o node_info: the address of a structure of type NodeInfo which points to a
1082 % node in the color cube tree that is to be pruned.
1085 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1086 const NodeInfo *node_info)
1095 Traverse any children.
1097 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1098 for (i=0; i < (ssize_t) number_children; i++)
1099 if (node_info->child[i] != (NodeInfo *) NULL)
1100 ClosestColor(image,cube_info,node_info->child[i]);
1101 if (node_info->number_unique != 0)
1114 register RealPixelInfo
1118 Determine if this color is "closest".
1120 p=image->colormap+node_info->color_number;
1121 q=(&cube_info->target);
1124 if (cube_info->associate_alpha != MagickFalse)
1126 alpha=(double) (QuantumScale*p->alpha);
1127 beta=(double) (QuantumScale*q->alpha);
1129 pixel=alpha*p->red-beta*q->red;
1130 distance=pixel*pixel;
1131 if (distance <= cube_info->distance)
1133 pixel=alpha*p->green-beta*q->green;
1134 distance+=pixel*pixel;
1135 if (distance <= cube_info->distance)
1137 pixel=alpha*p->blue-beta*q->blue;
1138 distance+=pixel*pixel;
1139 if (distance <= cube_info->distance)
1142 distance+=pixel*pixel;
1143 if (distance <= cube_info->distance)
1145 cube_info->distance=distance;
1146 cube_info->color_number=node_info->color_number;
1155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1159 % C o m p r e s s I m a g e C o l o r m a p %
1163 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1165 % CompressImageColormap() compresses an image colormap by removing any
1166 % duplicate or unused color entries.
1168 % The format of the CompressImageColormap method is:
1170 % MagickBooleanType CompressImageColormap(Image *image,
1171 % ExceptionInfo *exception)
1173 % A description of each parameter follows:
1175 % o image: the image.
1177 % o exception: return any errors or warnings in this structure.
1180 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1181 ExceptionInfo *exception)
1186 assert(image != (Image *) NULL);
1187 assert(image->signature == MagickSignature);
1188 if (image->debug != MagickFalse)
1189 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1190 if (IsPaletteImage(image,exception) == MagickFalse)
1191 return(MagickFalse);
1192 GetQuantizeInfo(&quantize_info);
1193 quantize_info.number_colors=image->colors;
1194 quantize_info.tree_depth=MaxTreeDepth;
1195 return(QuantizeImage(&quantize_info,image,exception));
1199 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1203 + D e f i n e I m a g e C o l o r m a p %
1207 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1209 % DefineImageColormap() traverses the color cube tree and notes each colormap
1210 % entry. A colormap entry is any node in the color cube tree where the
1211 % of unique colors is not zero. DefineImageColormap() returns the number of
1212 % colors in the image colormap.
1214 % The format of the DefineImageColormap method is:
1216 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1217 % NodeInfo *node_info)
1219 % A description of each parameter follows.
1221 % o image: the image.
1223 % o cube_info: A pointer to the Cube structure.
1225 % o node_info: the address of a structure of type NodeInfo which points to a
1226 % node in the color cube tree that is to be pruned.
1229 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1230 NodeInfo *node_info)
1239 Traverse any children.
1241 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1242 for (i=0; i < (ssize_t) number_children; i++)
1243 if (node_info->child[i] != (NodeInfo *) NULL)
1244 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1245 if (node_info->number_unique != 0)
1254 Colormap entry is defined by the mean color in this cube.
1256 q=image->colormap+image->colors;
1257 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1258 alpha=PerceptibleReciprocal(alpha);
1259 if (cube_info->associate_alpha == MagickFalse)
1261 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1262 node_info->total_color.red);
1263 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1264 node_info->total_color.green);
1265 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1266 node_info->total_color.blue);
1267 q->alpha=(double) OpaqueAlpha;
1274 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1275 q->alpha=(double) ClampToQuantum((opacity));
1276 if (q->alpha == OpaqueAlpha)
1278 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1279 node_info->total_color.red);
1280 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1281 node_info->total_color.green);
1282 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1283 node_info->total_color.blue);
1290 gamma=(double) (QuantumScale*q->alpha);
1291 gamma=PerceptibleReciprocal(gamma);
1292 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1293 node_info->total_color.red);
1294 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1295 node_info->total_color.green);
1296 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1297 node_info->total_color.blue);
1298 if (node_info->number_unique > cube_info->transparent_pixels)
1300 cube_info->transparent_pixels=node_info->number_unique;
1301 cube_info->transparent_index=(ssize_t) image->colors;
1305 node_info->color_number=image->colors++;
1307 return(image->colors);
1311 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1315 + D e s t r o y C u b e I n f o %
1319 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1321 % DestroyCubeInfo() deallocates memory associated with an image.
1323 % The format of the DestroyCubeInfo method is:
1325 % DestroyCubeInfo(CubeInfo *cube_info)
1327 % A description of each parameter follows:
1329 % o cube_info: the address of a structure of type CubeInfo.
1332 static void DestroyCubeInfo(CubeInfo *cube_info)
1338 Release color cube tree storage.
1342 nodes=cube_info->node_queue->next;
1343 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1344 cube_info->node_queue->nodes);
1345 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1346 cube_info->node_queue);
1347 cube_info->node_queue=nodes;
1348 } while (cube_info->node_queue != (Nodes *) NULL);
1349 if (cube_info->cache != (ssize_t *) NULL)
1350 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
1351 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1352 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1356 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1360 % D e s t r o y Q u a n t i z e I n f o %
1364 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1366 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1369 % The format of the DestroyQuantizeInfo method is:
1371 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1373 % A description of each parameter follows:
1375 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1378 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1380 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1381 assert(quantize_info != (QuantizeInfo *) NULL);
1382 assert(quantize_info->signature == MagickSignature);
1383 quantize_info->signature=(~MagickSignature);
1384 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1385 return(quantize_info);
1389 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1393 + D i t h e r I m a g e %
1397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1399 % DitherImage() distributes the difference between an original image and
1400 % the corresponding color reduced algorithm to neighboring pixels using
1401 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1402 % MagickTrue if the image is dithered otherwise MagickFalse.
1404 % The format of the DitherImage method is:
1406 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1407 % ExceptionInfo *exception)
1409 % A description of each parameter follows.
1411 % o image: the image.
1413 % o cube_info: A pointer to the Cube structure.
1415 % o exception: return any errors or warnings in this structure.
1419 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1424 assert(pixels != (RealPixelInfo **) NULL);
1425 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1426 if (pixels[i] != (RealPixelInfo *) NULL)
1427 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1428 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1432 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1443 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1444 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1446 if (pixels == (RealPixelInfo **) NULL)
1447 return((RealPixelInfo **) NULL);
1448 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1449 for (i=0; i < (ssize_t) number_threads; i++)
1451 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1452 if (pixels[i] == (RealPixelInfo *) NULL)
1453 return(DestroyPixelThreadSet(pixels));
1458 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1459 const RealPixelInfo *pixel)
1461 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1462 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1463 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1464 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1469 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1470 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1471 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1472 if (cube_info->associate_alpha != MagickFalse)
1473 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1477 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1478 ExceptionInfo *exception)
1480 #define DitherImageTag "Dither/Image"
1495 Distribute quantization error using Floyd-Steinberg.
1497 pixels=AcquirePixelThreadSet(image->columns);
1498 if (pixels == (RealPixelInfo **) NULL)
1499 return(MagickFalse);
1501 image_view=AcquireAuthenticCacheView(image,exception);
1502 for (y=0; y < (ssize_t) image->rows; y++)
1505 id = GetOpenMPThreadId();
1526 if (status == MagickFalse)
1528 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1529 if (q == (Quantum *) NULL)
1534 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
1536 current=pixels[id]+(y & 0x01)*image->columns;
1537 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1538 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1539 for (x=0; x < (ssize_t) image->columns; x++)
1551 q-=(y & 0x01)*GetPixelChannels(image);
1552 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1553 AssociateAlphaPixel(image,&cube,q,&pixel);
1556 pixel.red+=7*current[u-v].red/16;
1557 pixel.green+=7*current[u-v].green/16;
1558 pixel.blue+=7*current[u-v].blue/16;
1559 if (cube.associate_alpha != MagickFalse)
1560 pixel.alpha+=7*current[u-v].alpha/16;
1564 if (x < (ssize_t) (image->columns-1))
1566 pixel.red+=previous[u+v].red/16;
1567 pixel.green+=previous[u+v].green/16;
1568 pixel.blue+=previous[u+v].blue/16;
1569 if (cube.associate_alpha != MagickFalse)
1570 pixel.alpha+=previous[u+v].alpha/16;
1572 pixel.red+=5*previous[u].red/16;
1573 pixel.green+=5*previous[u].green/16;
1574 pixel.blue+=5*previous[u].blue/16;
1575 if (cube.associate_alpha != MagickFalse)
1576 pixel.alpha+=5*previous[u].alpha/16;
1579 pixel.red+=3*previous[u-v].red/16;
1580 pixel.green+=3*previous[u-v].green/16;
1581 pixel.blue+=3*previous[u-v].blue/16;
1582 if (cube.associate_alpha != MagickFalse)
1583 pixel.alpha+=3*previous[u-v].alpha/16;
1586 pixel.red=(double) ClampPixel(pixel.red);
1587 pixel.green=(double) ClampPixel(pixel.green);
1588 pixel.blue=(double) ClampPixel(pixel.blue);
1589 if (cube.associate_alpha != MagickFalse)
1590 pixel.alpha=(double) ClampPixel(pixel.alpha);
1591 i=CacheOffset(&cube,&pixel);
1592 if (cube.cache[i] < 0)
1601 Identify the deepest node containing the pixel's color.
1603 node_info=cube.root;
1604 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1606 id=ColorToNodeId(&cube,&pixel,index);
1607 if (node_info->child[id] == (NodeInfo *) NULL)
1609 node_info=node_info->child[id];
1612 Find closest color among siblings and their children.
1615 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1617 ClosestColor(image,&cube,node_info->parent);
1618 cube.cache[i]=(ssize_t) cube.color_number;
1621 Assign pixel to closest colormap entry.
1623 index=(size_t) cube.cache[i];
1624 if (image->storage_class == PseudoClass)
1625 SetPixelIndex(image,(Quantum) index,q);
1626 if (cube.quantize_info->measure_error == MagickFalse)
1628 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1629 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1630 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1631 if (cube.associate_alpha != MagickFalse)
1632 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1634 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1639 AssociateAlphaPixelInfo(image,&cube,image->colormap+index,&color);
1640 current[u].red=pixel.red-color.red;
1641 current[u].green=pixel.green-color.green;
1642 current[u].blue=pixel.blue-color.blue;
1643 if (cube.associate_alpha != MagickFalse)
1644 current[u].alpha=pixel.alpha-color.alpha;
1645 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1650 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1651 #pragma omp critical (MagickCore_FloydSteinbergDither)
1653 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1655 if (proceed == MagickFalse)
1658 q+=((y+1) & 0x01)*GetPixelChannels(image);
1661 image_view=DestroyCacheView(image_view);
1662 pixels=DestroyPixelThreadSet(pixels);
1666 static MagickBooleanType
1667 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1668 ExceptionInfo *exception);
1670 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1671 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1678 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1680 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1682 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1688 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1690 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1692 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1698 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1700 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1702 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1710 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1712 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1724 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1726 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1728 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1730 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1732 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1734 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1736 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1742 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1744 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1746 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1748 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1750 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1752 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1754 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1760 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1762 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1764 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1766 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1768 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1770 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1772 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1778 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1780 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1782 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1784 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1786 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1788 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1790 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1799 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1800 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1802 #define DitherImageTag "Dither/Image"
1818 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1819 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1830 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1831 if (q == (Quantum *) NULL)
1832 return(MagickFalse);
1833 AssociateAlphaPixel(image,cube_info,q,&pixel);
1834 for (i=0; i < ErrorQueueLength; i++)
1836 pixel.red+=p->weights[i]*p->error[i].red;
1837 pixel.green+=p->weights[i]*p->error[i].green;
1838 pixel.blue+=p->weights[i]*p->error[i].blue;
1839 if (cube_info->associate_alpha != MagickFalse)
1840 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1842 pixel.red=(double) ClampPixel(pixel.red);
1843 pixel.green=(double) ClampPixel(pixel.green);
1844 pixel.blue=(double) ClampPixel(pixel.blue);
1845 if (cube_info->associate_alpha != MagickFalse)
1846 pixel.alpha=(double) ClampPixel(pixel.alpha);
1847 i=CacheOffset(cube_info,&pixel);
1848 if (p->cache[i] < 0)
1857 Identify the deepest node containing the pixel's color.
1860 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1862 id=ColorToNodeId(cube_info,&pixel,index);
1863 if (node_info->child[id] == (NodeInfo *) NULL)
1865 node_info=node_info->child[id];
1867 node_info=node_info->parent;
1869 Find closest color among siblings and their children.
1872 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1873 QuantumRange+1.0)+1.0);
1874 ClosestColor(image,p,node_info->parent);
1875 p->cache[i]=(ssize_t) p->color_number;
1878 Assign pixel to closest colormap entry.
1880 index=(size_t) p->cache[i];
1881 if (image->storage_class == PseudoClass)
1882 SetPixelIndex(image,(Quantum) index,q);
1883 if (cube_info->quantize_info->measure_error == MagickFalse)
1885 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1886 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1887 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1888 if (cube_info->associate_alpha != MagickFalse)
1889 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1891 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1892 return(MagickFalse);
1894 Propagate the error as the last entry of the error queue.
1896 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1897 sizeof(p->error[0]));
1898 AssociateAlphaPixelInfo(image,cube_info,image->colormap+index,&color);
1899 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1900 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1901 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1902 if (cube_info->associate_alpha != MagickFalse)
1903 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1904 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1905 if (proceed == MagickFalse)
1906 return(MagickFalse);
1911 case WestGravity: p->x--; break;
1912 case EastGravity: p->x++; break;
1913 case NorthGravity: p->y--; break;
1914 case SouthGravity: p->y++; break;
1919 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1926 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1933 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1934 ExceptionInfo *exception)
1948 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1949 return(FloydSteinbergDither(image,cube_info,exception));
1951 Distribute quantization error along a Hilbert curve.
1953 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1954 sizeof(*cube_info->error));
1957 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1958 for (depth=1; i != 0; depth++)
1960 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1962 cube_info->offset=0;
1963 cube_info->span=(MagickSizeType) image->columns*image->rows;
1964 image_view=AcquireAuthenticCacheView(image,exception);
1966 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1967 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1968 image_view=DestroyCacheView(image_view);
1973 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1977 + G e t C u b e I n f o %
1981 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1983 % GetCubeInfo() initialize the Cube data structure.
1985 % The format of the GetCubeInfo method is:
1987 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1988 % const size_t depth,const size_t maximum_colors)
1990 % A description of each parameter follows.
1992 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1994 % o depth: Normally, this integer value is zero or one. A zero or
1995 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1996 % A tree of this depth generally allows the best representation of the
1997 % reference image with the least amount of memory and the fastest
1998 % computational speed. In some cases, such as an image with low color
1999 % dispersion (a few number of colors), a value other than
2000 % Log4(number_colors) is required. To expand the color tree completely,
2003 % o maximum_colors: maximum colors.
2006 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2007 const size_t depth,const size_t maximum_colors)
2023 Initialize tree to describe color cube_info.
2025 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2026 if (cube_info == (CubeInfo *) NULL)
2027 return((CubeInfo *) NULL);
2028 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2029 cube_info->depth=depth;
2030 if (cube_info->depth > MaxTreeDepth)
2031 cube_info->depth=MaxTreeDepth;
2032 if (cube_info->depth < 2)
2034 cube_info->maximum_colors=maximum_colors;
2036 Initialize root node.
2038 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2039 if (cube_info->root == (NodeInfo *) NULL)
2040 return((CubeInfo *) NULL);
2041 cube_info->root->parent=cube_info->root;
2042 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2043 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2046 Initialize dither resources.
2048 length=(size_t) (1UL << (4*(8-CacheShift)));
2049 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
2050 sizeof(*cube_info->cache));
2051 if (cube_info->cache == (ssize_t *) NULL)
2052 return((CubeInfo *) NULL);
2054 Initialize color cache.
2056 for (i=0; i < (ssize_t) length; i++)
2057 cube_info->cache[i]=(-1);
2059 Distribute weights along a curve of exponential decay.
2062 for (i=0; i < ErrorQueueLength; i++)
2064 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2065 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2068 Normalize the weighting factors.
2071 for (i=0; i < ErrorQueueLength; i++)
2072 weight+=cube_info->weights[i];
2074 for (i=0; i < ErrorQueueLength; i++)
2076 cube_info->weights[i]/=weight;
2077 sum+=cube_info->weights[i];
2079 cube_info->weights[0]+=1.0-sum;
2084 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2088 + G e t N o d e I n f o %
2092 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2094 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2095 % presets all fields to zero.
2097 % The format of the GetNodeInfo method is:
2099 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2100 % const size_t level,NodeInfo *parent)
2102 % A description of each parameter follows.
2104 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2106 % o id: Specifies the child number of the node.
2108 % o level: Specifies the level in the storage_class the node resides.
2111 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2112 const size_t level,NodeInfo *parent)
2117 if (cube_info->free_nodes == 0)
2123 Allocate a new queue of nodes.
2125 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2126 if (nodes == (Nodes *) NULL)
2127 return((NodeInfo *) NULL);
2128 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2129 sizeof(*nodes->nodes));
2130 if (nodes->nodes == (NodeInfo *) NULL)
2131 return((NodeInfo *) NULL);
2132 nodes->next=cube_info->node_queue;
2133 cube_info->node_queue=nodes;
2134 cube_info->next_node=nodes->nodes;
2135 cube_info->free_nodes=NodesInAList;
2138 cube_info->free_nodes--;
2139 node_info=cube_info->next_node++;
2140 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2141 node_info->parent=parent;
2143 node_info->level=level;
2148 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2152 % G e t I m a g e Q u a n t i z e E r r o r %
2156 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2158 % GetImageQuantizeError() measures the difference between the original
2159 % and quantized images. This difference is the total quantization error.
2160 % The error is computed by summing over all pixels in an image the distance
2161 % squared in RGB space between each reference pixel value and its quantized
2162 % value. These values are computed:
2164 % o mean_error_per_pixel: This value is the mean error for any single
2165 % pixel in the image.
2167 % o normalized_mean_square_error: This value is the normalized mean
2168 % quantization error for any single pixel in the image. This distance
2169 % measure is normalized to a range between 0 and 1. It is independent
2170 % of the range of red, green, and blue values in the image.
2172 % o normalized_maximum_square_error: Thsi value is the normalized
2173 % maximum quantization error for any single pixel in the image. This
2174 % distance measure is normalized to a range between 0 and 1. It is
2175 % independent of the range of red, green, and blue values in your image.
2177 % The format of the GetImageQuantizeError method is:
2179 % MagickBooleanType GetImageQuantizeError(Image *image,
2180 % ExceptionInfo *exception)
2182 % A description of each parameter follows.
2184 % o image: the image.
2186 % o exception: return any errors or warnings in this structure.
2189 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2190 ExceptionInfo *exception)
2202 mean_error_per_pixel;
2210 assert(image != (Image *) NULL);
2211 assert(image->signature == MagickSignature);
2212 if (image->debug != MagickFalse)
2213 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2214 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2215 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2216 if (image->storage_class == DirectClass)
2220 area=3.0*image->columns*image->rows;
2222 mean_error_per_pixel=0.0;
2224 image_view=AcquireVirtualCacheView(image,exception);
2225 for (y=0; y < (ssize_t) image->rows; y++)
2227 register const Quantum
2233 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2234 if (p == (const Quantum *) NULL)
2236 for (x=0; x < (ssize_t) image->columns; x++)
2238 index=1UL*GetPixelIndex(image,p);
2239 if (image->alpha_trait == BlendPixelTrait)
2241 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2242 beta=(double) (QuantumScale*image->colormap[index].alpha);
2244 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2245 image->colormap[index].red);
2246 mean_error_per_pixel+=distance;
2247 mean_error+=distance*distance;
2248 if (distance > maximum_error)
2249 maximum_error=distance;
2250 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2251 image->colormap[index].green);
2252 mean_error_per_pixel+=distance;
2253 mean_error+=distance*distance;
2254 if (distance > maximum_error)
2255 maximum_error=distance;
2256 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2257 image->colormap[index].blue);
2258 mean_error_per_pixel+=distance;
2259 mean_error+=distance*distance;
2260 if (distance > maximum_error)
2261 maximum_error=distance;
2262 p+=GetPixelChannels(image);
2265 image_view=DestroyCacheView(image_view);
2266 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2267 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2269 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2274 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2278 % G e t Q u a n t i z e I n f o %
2282 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2284 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2286 % The format of the GetQuantizeInfo method is:
2288 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2290 % A description of each parameter follows:
2292 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2295 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2297 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2298 assert(quantize_info != (QuantizeInfo *) NULL);
2299 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2300 quantize_info->number_colors=256;
2301 quantize_info->dither_method=RiemersmaDitherMethod;
2302 quantize_info->colorspace=UndefinedColorspace;
2303 quantize_info->measure_error=MagickFalse;
2304 quantize_info->signature=MagickSignature;
2308 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2312 % P o s t e r i z e I m a g e %
2316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2318 % PosterizeImage() reduces the image to a limited number of colors for a
2321 % The format of the PosterizeImage method is:
2323 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2324 % const DitherMethod dither_method,ExceptionInfo *exception)
2326 % A description of each parameter follows:
2328 % o image: Specifies a pointer to an Image structure.
2330 % o levels: Number of color levels allowed in each channel. Very low values
2331 % (2, 3, or 4) have the most visible effect.
2333 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2334 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2336 % o exception: return any errors or warnings in this structure.
2340 static inline double MagickRound(double x)
2343 Round the fraction to nearest integer.
2345 if ((x-floor(x)) < (ceil(x)-x)
2350 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2351 const DitherMethod dither_method,ExceptionInfo *exception)
2353 #define PosterizeImageTag "Posterize/Image"
2354 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2355 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2375 assert(image != (Image *) NULL);
2376 assert(image->signature == MagickSignature);
2377 if (image->debug != MagickFalse)
2378 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2379 if (image->storage_class == PseudoClass)
2380 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2381 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2382 magick_threads(image,image,1,1)
2384 for (i=0; i < (ssize_t) image->colors; i++)
2389 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2390 image->colormap[i].red=(double)
2391 PosterizePixel(image->colormap[i].red);
2392 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2393 image->colormap[i].green=(double)
2394 PosterizePixel(image->colormap[i].green);
2395 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2396 image->colormap[i].blue=(double)
2397 PosterizePixel(image->colormap[i].blue);
2398 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2399 image->colormap[i].alpha=(double)
2400 PosterizePixel(image->colormap[i].alpha);
2407 image_view=AcquireAuthenticCacheView(image,exception);
2408 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2409 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2410 magick_threads(image,image,image->rows,1)
2412 for (y=0; y < (ssize_t) image->rows; y++)
2420 if (status == MagickFalse)
2422 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2423 if (q == (Quantum *) NULL)
2428 for (x=0; x < (ssize_t) image->columns; x++)
2430 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2431 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2432 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2433 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2434 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2435 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2436 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2437 (image->colorspace == CMYKColorspace))
2438 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2439 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2440 (image->alpha_trait == BlendPixelTrait))
2441 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2442 q+=GetPixelChannels(image);
2444 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2446 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2451 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2452 #pragma omp critical (MagickCore_PosterizeImage)
2454 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2456 if (proceed == MagickFalse)
2460 image_view=DestroyCacheView(image_view);
2461 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2462 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2463 levels,MaxColormapSize+1);
2464 quantize_info->dither_method=dither_method;
2465 quantize_info->tree_depth=MaxTreeDepth;
2466 status=QuantizeImage(quantize_info,image,exception);
2467 quantize_info=DestroyQuantizeInfo(quantize_info);
2472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2476 + P r u n e C h i l d %
2480 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2482 % PruneChild() deletes the given node and merges its statistics into its
2485 % The format of the PruneSubtree method is:
2487 % PruneChild(const Image *image,CubeInfo *cube_info,
2488 % const NodeInfo *node_info)
2490 % A description of each parameter follows.
2492 % o image: the image.
2494 % o cube_info: A pointer to the Cube structure.
2496 % o node_info: pointer to node in color cube tree that is to be pruned.
2499 static void PruneChild(const Image *image,CubeInfo *cube_info,
2500 const NodeInfo *node_info)
2512 Traverse any children.
2514 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2515 for (i=0; i < (ssize_t) number_children; i++)
2516 if (node_info->child[i] != (NodeInfo *) NULL)
2517 PruneChild(image,cube_info,node_info->child[i]);
2519 Merge color statistics into parent.
2521 parent=node_info->parent;
2522 parent->number_unique+=node_info->number_unique;
2523 parent->total_color.red+=node_info->total_color.red;
2524 parent->total_color.green+=node_info->total_color.green;
2525 parent->total_color.blue+=node_info->total_color.blue;
2526 parent->total_color.alpha+=node_info->total_color.alpha;
2527 parent->child[node_info->id]=(NodeInfo *) NULL;
2532 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2536 + P r u n e L e v e l %
2540 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2542 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2543 % their color statistics into their parent node.
2545 % The format of the PruneLevel method is:
2547 % PruneLevel(const Image *image,CubeInfo *cube_info,
2548 % const NodeInfo *node_info)
2550 % A description of each parameter follows.
2552 % o image: the image.
2554 % o cube_info: A pointer to the Cube structure.
2556 % o node_info: pointer to node in color cube tree that is to be pruned.
2559 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2560 const NodeInfo *node_info)
2569 Traverse any children.
2571 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2572 for (i=0; i < (ssize_t) number_children; i++)
2573 if (node_info->child[i] != (NodeInfo *) NULL)
2574 PruneLevel(image,cube_info,node_info->child[i]);
2575 if (node_info->level == cube_info->depth)
2576 PruneChild(image,cube_info,node_info);
2580 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2584 + P r u n e T o C u b e D e p t h %
2588 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2590 % PruneToCubeDepth() deletes any nodes at a depth greater than
2591 % cube_info->depth while merging their color statistics into their parent
2594 % The format of the PruneToCubeDepth method is:
2596 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2597 % const NodeInfo *node_info)
2599 % A description of each parameter follows.
2601 % o cube_info: A pointer to the Cube structure.
2603 % o node_info: pointer to node in color cube tree that is to be pruned.
2606 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2607 const NodeInfo *node_info)
2616 Traverse any children.
2618 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2619 for (i=0; i < (ssize_t) number_children; i++)
2620 if (node_info->child[i] != (NodeInfo *) NULL)
2621 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2622 if (node_info->level > cube_info->depth)
2623 PruneChild(image,cube_info,node_info);
2627 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2631 % Q u a n t i z e I m a g e %
2635 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2637 % QuantizeImage() analyzes the colors within a reference image and chooses a
2638 % fixed number of colors to represent the image. The goal of the algorithm
2639 % is to minimize the color difference between the input and output image while
2640 % minimizing the processing time.
2642 % The format of the QuantizeImage method is:
2644 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2645 % Image *image,ExceptionInfo *exception)
2647 % A description of each parameter follows:
2649 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2651 % o image: the image.
2653 % o exception: return any errors or warnings in this structure.
2657 static MagickBooleanType DirectToColormapImage(Image *image,
2658 ExceptionInfo *exception)
2676 number_colors=(size_t) (image->columns*image->rows);
2677 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2678 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2680 if (image->colors != number_colors)
2681 return(MagickFalse);
2683 image_view=AcquireAuthenticCacheView(image,exception);
2684 for (y=0; y < (ssize_t) image->rows; y++)
2695 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2696 if (q == (Quantum *) NULL)
2698 for (x=0; x < (ssize_t) image->columns; x++)
2700 image->colormap[i].red=(double) GetPixelRed(image,q);
2701 image->colormap[i].green=(double) GetPixelGreen(image,q);
2702 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2703 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2704 SetPixelIndex(image,(Quantum) i,q);
2706 q+=GetPixelChannels(image);
2708 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2710 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2712 if (proceed == MagickFalse)
2715 image_view=DestroyCacheView(image_view);
2719 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2720 Image *image,ExceptionInfo *exception)
2732 assert(quantize_info != (const QuantizeInfo *) NULL);
2733 assert(quantize_info->signature == MagickSignature);
2734 assert(image != (Image *) NULL);
2735 assert(image->signature == MagickSignature);
2736 if (image->debug != MagickFalse)
2737 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2738 maximum_colors=quantize_info->number_colors;
2739 if (maximum_colors == 0)
2740 maximum_colors=MaxColormapSize;
2741 if (maximum_colors > MaxColormapSize)
2742 maximum_colors=MaxColormapSize;
2743 if (image->alpha_trait != BlendPixelTrait)
2745 if ((image->columns*image->rows) <= maximum_colors)
2746 (void) DirectToColormapImage(image,exception);
2747 if (IsImageGray(image,exception) != MagickFalse)
2748 (void) SetGrayscaleImage(image,exception);
2750 if ((image->storage_class == PseudoClass) &&
2751 (image->colors <= maximum_colors))
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_method != NoDitherMethod) && (depth > 2))
2767 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2771 Initialize color cube.
2773 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2774 if (cube_info == (CubeInfo *) NULL)
2775 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2777 status=ClassifyImageColors(cube_info,image,exception);
2778 if (status != MagickFalse)
2781 Reduce the number of colors in the image.
2783 ReduceImageColors(image,cube_info);
2784 status=AssignImageColors(image,cube_info,exception);
2786 DestroyCubeInfo(cube_info);
2791 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2795 % Q u a n t i z e I m a g e s %
2799 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2801 % QuantizeImages() analyzes the colors within a set of reference images and
2802 % chooses a fixed number of colors to represent the set. The goal of the
2803 % algorithm is to minimize the color difference between the input and output
2804 % images while minimizing the processing time.
2806 % The format of the QuantizeImages method is:
2808 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2809 % Image *images,ExceptionInfo *exception)
2811 % A description of each parameter follows:
2813 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2815 % o images: Specifies a pointer to a list of Image structures.
2817 % o exception: return any errors or warnings in this structure.
2820 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2821 Image *images,ExceptionInfo *exception)
2833 MagickProgressMonitor
2844 assert(quantize_info != (const QuantizeInfo *) NULL);
2845 assert(quantize_info->signature == MagickSignature);
2846 assert(images != (Image *) NULL);
2847 assert(images->signature == MagickSignature);
2848 if (images->debug != MagickFalse)
2849 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2850 if (GetNextImageInList(images) == (Image *) NULL)
2853 Handle a single image with QuantizeImage.
2855 status=QuantizeImage(quantize_info,images,exception);
2859 maximum_colors=quantize_info->number_colors;
2860 if (maximum_colors == 0)
2861 maximum_colors=MaxColormapSize;
2862 if (maximum_colors > MaxColormapSize)
2863 maximum_colors=MaxColormapSize;
2864 depth=quantize_info->tree_depth;
2871 Depth of color tree is: Log4(colormap size)+2.
2873 colors=maximum_colors;
2874 for (depth=1; colors != 0; depth++)
2876 if (quantize_info->dither_method != NoDitherMethod)
2880 Initialize color cube.
2882 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2883 if (cube_info == (CubeInfo *) NULL)
2885 (void) ThrowMagickException(exception,GetMagickModule(),
2886 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2887 return(MagickFalse);
2889 number_images=GetImageListLength(images);
2891 for (i=0; image != (Image *) NULL; i++)
2893 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2894 image->client_data);
2895 status=ClassifyImageColors(cube_info,image,exception);
2896 if (status == MagickFalse)
2898 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2899 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2901 if (proceed == MagickFalse)
2903 image=GetNextImageInList(image);
2905 if (status != MagickFalse)
2908 Reduce the number of colors in an image sequence.
2910 ReduceImageColors(images,cube_info);
2912 for (i=0; image != (Image *) NULL; i++)
2914 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2915 NULL,image->client_data);
2916 status=AssignImageColors(image,cube_info,exception);
2917 if (status == MagickFalse)
2919 (void) SetImageProgressMonitor(image,progress_monitor,
2920 image->client_data);
2921 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2923 if (proceed == MagickFalse)
2925 image=GetNextImageInList(image);
2928 DestroyCubeInfo(cube_info);
2933 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2941 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2943 % Reduce() traverses the color cube tree and prunes any node whose
2944 % quantization error falls below a particular threshold.
2946 % The format of the Reduce method is:
2948 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2950 % A description of each parameter follows.
2952 % o image: the image.
2954 % o cube_info: A pointer to the Cube structure.
2956 % o node_info: pointer to node in color cube tree that is to be pruned.
2959 static void Reduce(const Image *image,CubeInfo *cube_info,
2960 const NodeInfo *node_info)
2969 Traverse any children.
2971 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2972 for (i=0; i < (ssize_t) number_children; i++)
2973 if (node_info->child[i] != (NodeInfo *) NULL)
2974 Reduce(image,cube_info,node_info->child[i]);
2975 if (node_info->quantize_error <= cube_info->pruning_threshold)
2976 PruneChild(image,cube_info,node_info);
2980 Find minimum pruning threshold.
2982 if (node_info->number_unique > 0)
2983 cube_info->colors++;
2984 if (node_info->quantize_error < cube_info->next_threshold)
2985 cube_info->next_threshold=node_info->quantize_error;
2990 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2994 + R e d u c e I m a g e C o l o r s %
2998 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3000 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3001 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3002 % in the output image. On any given iteration over the tree, it selects
3003 % those nodes whose E value is minimal for pruning and merges their
3004 % color statistics upward. It uses a pruning threshold, Ep, to govern
3005 % node selection as follows:
3008 % while number of nodes with (n2 > 0) > required maximum number of colors
3009 % prune all nodes such that E <= Ep
3010 % Set Ep to minimum E in remaining nodes
3012 % This has the effect of minimizing any quantization error when merging
3013 % two nodes together.
3015 % When a node to be pruned has offspring, the pruning procedure invokes
3016 % itself recursively in order to prune the tree from the leaves upward.
3017 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3018 % corresponding data in that node's parent. This retains the pruned
3019 % node's color characteristics for later averaging.
3021 % For each node, n2 pixels exist for which that node represents the
3022 % smallest volume in RGB space containing those pixel's colors. When n2
3023 % > 0 the node will uniquely define a color in the output image. At the
3024 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3025 % the tree which represent colors present in the input image.
3027 % The other pixel count, n1, indicates the total number of colors
3028 % within the cubic volume which the node represents. This includes n1 -
3029 % n2 pixels whose colors should be defined by nodes at a lower level in
3032 % The format of the ReduceImageColors method is:
3034 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3036 % A description of each parameter follows.
3038 % o image: the image.
3040 % o cube_info: A pointer to the Cube structure.
3043 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3045 #define ReduceImageTag "Reduce/Image"
3056 cube_info->next_threshold=0.0;
3057 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3059 cube_info->pruning_threshold=cube_info->next_threshold;
3060 cube_info->next_threshold=cube_info->root->quantize_error-1;
3061 cube_info->colors=0;
3062 Reduce(image,cube_info,cube_info->root);
3063 offset=(MagickOffsetType) span-cube_info->colors;
3064 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3065 cube_info->maximum_colors+1);
3066 if (proceed == MagickFalse)
3072 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3076 % R e m a p I m a g e %
3080 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3082 % RemapImage() replaces the colors of an image with a dither of the colors
3085 % The format of the RemapImage method is:
3087 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3088 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3090 % A description of each parameter follows:
3092 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3094 % o image: the image.
3096 % o remap_image: the reference image.
3098 % o exception: return any errors or warnings in this structure.
3101 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3102 Image *image,const Image *remap_image,ExceptionInfo *exception)
3111 Initialize color cube.
3113 assert(image != (Image *) NULL);
3114 assert(image->signature == MagickSignature);
3115 if (image->debug != MagickFalse)
3116 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3117 assert(remap_image != (Image *) NULL);
3118 assert(remap_image->signature == MagickSignature);
3119 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3120 quantize_info->number_colors);
3121 if (cube_info == (CubeInfo *) NULL)
3122 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3124 status=ClassifyImageColors(cube_info,remap_image,exception);
3125 if (status != MagickFalse)
3128 Classify image colors from the reference image.
3130 cube_info->quantize_info->number_colors=cube_info->colors;
3131 status=AssignImageColors(image,cube_info,exception);
3133 DestroyCubeInfo(cube_info);
3138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3142 % R e m a p I m a g e s %
3146 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3148 % RemapImages() replaces the colors of a sequence of images with the
3149 % closest color from a reference image.
3151 % The format of the RemapImage method is:
3153 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3154 % Image *images,Image *remap_image,ExceptionInfo *exception)
3156 % A description of each parameter follows:
3158 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3160 % o images: the image sequence.
3162 % o remap_image: the reference image.
3164 % o exception: return any errors or warnings in this structure.
3167 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3168 Image *images,const Image *remap_image,ExceptionInfo *exception)
3179 assert(images != (Image *) NULL);
3180 assert(images->signature == MagickSignature);
3181 if (images->debug != MagickFalse)
3182 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3184 if (remap_image == (Image *) NULL)
3187 Create a global colormap for an image sequence.
3189 status=QuantizeImages(quantize_info,images,exception);
3193 Classify image colors from the reference image.
3195 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3196 quantize_info->number_colors);
3197 if (cube_info == (CubeInfo *) NULL)
3198 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3200 status=ClassifyImageColors(cube_info,remap_image,exception);
3201 if (status != MagickFalse)
3204 Classify image colors from the reference image.
3206 cube_info->quantize_info->number_colors=cube_info->colors;
3208 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3210 status=AssignImageColors(image,cube_info,exception);
3211 if (status == MagickFalse)
3215 DestroyCubeInfo(cube_info);
3220 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3224 % S e t G r a y s c a l e I m a g e %
3228 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3230 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3232 % The format of the SetGrayscaleImage method is:
3234 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3236 % A description of each parameter follows:
3238 % o image: The image.
3240 % o exception: return any errors or warnings in this structure.
3244 #if defined(__cplusplus) || defined(c_plusplus)
3248 static int IntensityCompare(const void *x,const void *y)
3257 color_1=(PixelInfo *) x;
3258 color_2=(PixelInfo *) y;
3259 intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
3260 GetPixelInfoIntensity(color_2));
3261 return((int) intensity);
3264 #if defined(__cplusplus) || defined(c_plusplus)
3268 static MagickBooleanType SetGrayscaleImage(Image *image,
3269 ExceptionInfo *exception)
3288 assert(image != (Image *) NULL);
3289 assert(image->signature == MagickSignature);
3290 if (image->type != GrayscaleType)
3291 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3292 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3293 sizeof(*colormap_index));
3294 if (colormap_index == (ssize_t *) NULL)
3295 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3297 if (image->storage_class != PseudoClass)
3299 for (i=0; i <= (ssize_t) MaxMap; i++)
3300 colormap_index[i]=(-1);
3301 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3302 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3306 image_view=AcquireAuthenticCacheView(image,exception);
3307 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3308 #pragma omp parallel for schedule(static,4) shared(status) \
3309 magick_threads(image,image,image->rows,1)
3311 for (y=0; y < (ssize_t) image->rows; y++)
3319 if (status == MagickFalse)
3321 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3323 if (q == (Quantum *) NULL)
3328 for (x=0; x < (ssize_t) image->columns; x++)
3333 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3334 if (colormap_index[intensity] < 0)
3336 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3337 #pragma omp critical (MagickCore_SetGrayscaleImage)
3339 if (colormap_index[intensity] < 0)
3341 colormap_index[intensity]=(ssize_t) image->colors;
3342 image->colormap[image->colors].red=(double)
3343 GetPixelRed(image,q);
3344 image->colormap[image->colors].green=(double)
3345 GetPixelGreen(image,q);
3346 image->colormap[image->colors].blue=(double)
3347 GetPixelBlue(image,q);
3351 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3352 q+=GetPixelChannels(image);
3354 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3357 image_view=DestroyCacheView(image_view);
3359 for (i=0; i < (ssize_t) image->colors; i++)
3360 image->colormap[i].alpha=(double) i;
3361 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3363 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,
3365 if (colormap == (PixelInfo *) NULL)
3366 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3369 colormap[j]=image->colormap[0];
3370 for (i=0; i < (ssize_t) image->colors; i++)
3372 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3375 colormap[j]=image->colormap[i];
3377 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3379 image->colors=(size_t) (j+1);
3380 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3381 image->colormap=colormap;
3383 image_view=AcquireAuthenticCacheView(image,exception);
3384 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3385 #pragma omp parallel for schedule(static,4) shared(status) \
3386 magick_threads(image,image,image->rows,1)
3388 for (y=0; y < (ssize_t) image->rows; y++)
3396 if (status == MagickFalse)
3398 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3399 if (q == (Quantum *) NULL)
3404 for (x=0; x < (ssize_t) image->columns; x++)
3406 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3407 GetPixelIndex(image,q))],q);
3408 q+=GetPixelChannels(image);
3410 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3413 image_view=DestroyCacheView(image_view);
3414 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3415 image->type=GrayscaleType;
3416 if (IsImageMonochrome(image,exception) != MagickFalse)
3417 image->type=BilevelType;