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-2015 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 (vertex
65 % nearest the origin in RGB space and the vertex farthest from the origin).
67 % The tree's root node represents the entire domain, (0,0,0) through
68 % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
69 % subdividing one node's cube into eight smaller cubes of equal size.
70 % This corresponds to bisecting the parent cube with planes passing
71 % through the midpoints of each edge.
73 % The basic algorithm operates in three phases: Classification,
74 % Reduction, and Assignment. Classification builds a color description
75 % tree for the image. Reduction collapses the tree until the number it
76 % represents, at most, the number of colors desired in the output image.
77 % Assignment defines the output image's color map and sets each pixel's
78 % color by restorage_class in the reduced tree. Our goal is to minimize
79 % the numerical discrepancies between the original colors and quantized
80 % colors (quantization error).
82 % Classification begins by initializing a color description tree of
83 % sufficient depth to represent each possible input color in a leaf.
84 % However, it is impractical to generate a fully-formed color description
85 % tree in the storage_class phase for realistic values of Cmax. If
86 % colors components in the input image are quantized to k-bit precision,
87 % so that Cmax= 2k-1, the tree would need k levels below the root node to
88 % allow representing each possible input color in a leaf. This becomes
89 % prohibitive because the tree's total number of nodes is 1 +
92 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
93 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
94 % Initializes data structures for nodes only as they are needed; (2)
95 % Chooses a maximum depth for the tree as a function of the desired
96 % number of colors in the output image (currently log2(colormap size)).
98 % For each pixel in the input image, storage_class scans downward from
99 % the root of the color description tree. At each level of the tree it
100 % identifies the single node which represents a cube in RGB space
101 % containing the pixel's color. It updates the following data for each
104 % n1: Number of pixels whose color is contained in the RGB cube which
105 % this node represents;
107 % n2: Number of pixels whose color is not represented in a node at
108 % lower depth in the tree; initially, n2 = 0 for all nodes except
109 % leaves of the tree.
111 % Sr, Sg, Sb: Sums of the red, green, and blue component values for all
112 % pixels not classified at a lower depth. The combination of these sums
113 % and n2 will ultimately characterize the mean color of a set of
114 % pixels represented by this node.
116 % E: the distance squared in RGB space between each pixel contained
117 % within a node and the nodes' center. This represents the
118 % quantization error for a node.
120 % Reduction repeatedly prunes the tree until the number of nodes with n2
121 % > 0 is less than or equal to the maximum number of colors allowed in
122 % the output image. On any given iteration over the tree, it selects
123 % those nodes whose E count is minimal for pruning and merges their color
124 % statistics upward. It uses a pruning threshold, Ep, to govern node
125 % selection as follows:
128 % while number of nodes with (n2 > 0) > required maximum number of colors
129 % prune all nodes such that E <= Ep
130 % Set Ep to minimum E in remaining nodes
132 % This has the effect of minimizing any quantization error when merging
133 % two nodes together.
135 % When a node to be pruned has offspring, the pruning procedure invokes
136 % itself recursively in order to prune the tree from the leaves upward.
137 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
138 % corresponding data in that node's parent. This retains the pruned
139 % node's color characteristics for later averaging.
141 % For each node, n2 pixels exist for which that node represents the
142 % smallest volume in RGB space containing those pixel's colors. When n2
143 % > 0 the node will uniquely define a color in the output image. At the
144 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
145 % the tree which represent colors present in the input image.
147 % The other pixel count, n1, indicates the total number of colors within
148 % the cubic volume which the node represents. This includes n1 - n2
149 % pixels whose colors should be defined by nodes at a lower level in the
152 % Assignment generates the output image from the pruned tree. The output
153 % image consists of two parts: (1) A color map, which is an array of
154 % color descriptions (RGB triples) for each color present in the output
155 % image; (2) A pixel array, which represents each pixel as an index
156 % into the color map array.
158 % First, the assignment phase makes one pass over the pruned color
159 % description tree to establish the image's color map. For each node
160 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
161 % color of all pixels that classify no lower than this node. Each of
162 % these colors becomes an entry in the color map.
164 % Finally, the assignment phase reclassifies each pixel in the pruned
165 % tree to identify the deepest node containing the pixel's color. The
166 % pixel's value in the pixel array becomes the index of this node's mean
167 % color in the color map.
169 % This method is based on a similar algorithm written by Paul Raveling.
174 Include declarations.
176 #include "MagickCore/studio.h"
177 #include "MagickCore/attribute.h"
178 #include "MagickCore/cache-view.h"
179 #include "MagickCore/color.h"
180 #include "MagickCore/color-private.h"
181 #include "MagickCore/colormap.h"
182 #include "MagickCore/colorspace.h"
183 #include "MagickCore/colorspace-private.h"
184 #include "MagickCore/enhance.h"
185 #include "MagickCore/exception.h"
186 #include "MagickCore/exception-private.h"
187 #include "MagickCore/histogram.h"
188 #include "MagickCore/image.h"
189 #include "MagickCore/image-private.h"
190 #include "MagickCore/list.h"
191 #include "MagickCore/memory_.h"
192 #include "MagickCore/monitor.h"
193 #include "MagickCore/monitor-private.h"
194 #include "MagickCore/option.h"
195 #include "MagickCore/pixel-accessor.h"
196 #include "MagickCore/pixel-private.h"
197 #include "MagickCore/quantize.h"
198 #include "MagickCore/quantum.h"
199 #include "MagickCore/quantum-private.h"
200 #include "MagickCore/resource_.h"
201 #include "MagickCore/string_.h"
202 #include "MagickCore/thread-private.h"
207 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
212 #define ErrorQueueLength 16
213 #define MaxNodes 266817
214 #define MaxTreeDepth 8
215 #define NodesInAList 1920
220 typedef struct _RealPixelInfo
229 typedef struct _NodeInfo
250 typedef struct _Nodes
259 typedef struct _CubeInfo
300 error[ErrorQueueLength];
303 weights[ErrorQueueLength];
329 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
332 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
334 static MagickBooleanType
335 AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
336 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
337 DitherImage(Image *,CubeInfo *,ExceptionInfo *),
338 SetGrayscaleImage(Image *,ExceptionInfo *);
341 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
344 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
345 DestroyCubeInfo(CubeInfo *),
346 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
347 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
348 ReduceImageColors(const Image *,CubeInfo *);
351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
355 % A c q u i r e Q u a n t i z e I n f o %
359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
361 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
363 % The format of the AcquireQuantizeInfo method is:
365 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
367 % A description of each parameter follows:
369 % o image_info: the image info.
372 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
377 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
378 if (quantize_info == (QuantizeInfo *) NULL)
379 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
380 GetQuantizeInfo(quantize_info);
381 if (image_info != (ImageInfo *) NULL)
386 quantize_info->dither_method=image_info->dither == MagickFalse ?
387 NoDitherMethod : RiemersmaDitherMethod;
388 option=GetImageOption(image_info,"dither");
389 if (option != (const char *) NULL)
390 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
391 MagickDitherOptions,MagickFalse,option);
392 quantize_info->measure_error=image_info->verbose;
394 return(quantize_info);
398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
402 + A s s i g n I m a g e C o l o r s %
406 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
408 % AssignImageColors() generates the output image from the pruned tree. The
409 % output image consists of two parts: (1) A color map, which is an array
410 % of color descriptions (RGB triples) for each color present in the
411 % output image; (2) A pixel array, which represents each pixel as an
412 % index into the color map array.
414 % First, the assignment phase makes one pass over the pruned color
415 % description tree to establish the image's color map. For each node
416 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
417 % color of all pixels that classify no lower than this node. Each of
418 % these colors becomes an entry in the color map.
420 % Finally, the assignment phase reclassifies each pixel in the pruned
421 % tree to identify the deepest node containing the pixel's color. The
422 % pixel's value in the pixel array becomes the index of this node's mean
423 % color in the color map.
425 % The format of the AssignImageColors() method is:
427 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
429 % A description of each parameter follows.
431 % o image: the image.
433 % o cube_info: A pointer to the Cube structure.
437 static inline void AssociateAlphaPixel(const Image *image,
438 const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
443 if ((cube_info->associate_alpha == MagickFalse) ||
444 (GetPixelAlpha(image,pixel)== OpaqueAlpha))
446 alpha_pixel->red=(double) GetPixelRed(image,pixel);
447 alpha_pixel->green=(double) GetPixelGreen(image,pixel);
448 alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
449 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
452 alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
453 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
454 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
455 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
456 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
459 static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
460 const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
465 if ((cube_info->associate_alpha == MagickFalse) ||
466 (pixel->alpha == OpaqueAlpha))
468 alpha_pixel->red=(double) pixel->red;
469 alpha_pixel->green=(double) pixel->green;
470 alpha_pixel->blue=(double) pixel->blue;
471 alpha_pixel->alpha=(double) pixel->alpha;
474 alpha=(double) (QuantumScale*pixel->alpha);
475 alpha_pixel->red=alpha*pixel->red;
476 alpha_pixel->green=alpha*pixel->green;
477 alpha_pixel->blue=alpha*pixel->blue;
478 alpha_pixel->alpha=(double) pixel->alpha;
481 static inline Quantum ClampPixel(const MagickRealType value)
485 if (value >= (MagickRealType) QuantumRange)
486 return((Quantum) QuantumRange);
487 #if !defined(MAGICKCORE_HDRI_SUPPORT)
488 return((Quantum) (value+0.5f));
494 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
495 const RealPixelInfo *pixel,size_t index)
500 id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
501 ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
502 ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
503 if (cube_info->associate_alpha != MagickFalse)
504 id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
508 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
509 ExceptionInfo *exception)
511 #define AssignImageTag "Assign/Image"
517 Allocate image colormap.
519 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
520 (cube_info->quantize_info->colorspace != CMYKColorspace))
521 (void) TransformImageColorspace((Image *) image,
522 cube_info->quantize_info->colorspace,exception);
524 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
525 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
526 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
527 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
530 cube_info->transparent_pixels=0;
531 cube_info->transparent_index=(-1);
532 (void) DefineImageColormap(image,cube_info,cube_info->root);
534 Create a reduced color image.
536 if (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) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
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 != UndefinedPixelTrait ? MagickTrue :
760 if ((cube_info->quantize_info->number_colors == 2) &&
761 (cube_info->quantize_info->colorspace == GRAYColorspace))
762 associate_alpha=MagickFalse;
763 cube_info->associate_alpha=associate_alpha;
766 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
767 const Image *image,ExceptionInfo *exception)
769 #define ClassifyImageTag "Classify/Image"
799 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
801 SetAssociatedAlpha(image,cube_info);
802 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
803 (cube_info->quantize_info->colorspace != CMYKColorspace))
804 (void) TransformImageColorspace((Image *) image,
805 cube_info->quantize_info->colorspace,exception);
807 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
808 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
809 midpoint.red=(double) QuantumRange/2.0;
810 midpoint.green=(double) QuantumRange/2.0;
811 midpoint.blue=(double) QuantumRange/2.0;
812 midpoint.alpha=(double) QuantumRange/2.0;
814 image_view=AcquireVirtualCacheView(image,exception);
815 for (y=0; y < (ssize_t) image->rows; y++)
817 register const Quantum
823 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
824 if (p == (const Quantum *) NULL)
826 if (cube_info->nodes > MaxNodes)
829 Prune one level if the color tree is too large.
831 PruneLevel(image,cube_info,cube_info->root);
834 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
837 Start at the root and descend the color cube tree.
839 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
844 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
845 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
848 AssociateAlphaPixel(image,cube_info,p,&pixel);
849 index=MaxTreeDepth-1;
850 bisect=((double) QuantumRange+1.0)/2.0;
852 node_info=cube_info->root;
853 for (level=1; level <= MaxTreeDepth; level++)
859 id=ColorToNodeId(cube_info,&pixel,index);
860 mid.red+=(id & 1) != 0 ? bisect : -bisect;
861 mid.green+=(id & 2) != 0 ? bisect : -bisect;
862 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
863 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
864 if (node_info->child[id] == (NodeInfo *) NULL)
867 Set colors of new node to contain pixel.
869 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
870 if (node_info->child[id] == (NodeInfo *) NULL)
872 (void) ThrowMagickException(exception,GetMagickModule(),
873 ResourceLimitError,"MemoryAllocationFailed","`%s'",
877 if (level == MaxTreeDepth)
881 Approximate the quantization error represented by this node.
883 node_info=node_info->child[id];
884 error.red=QuantumScale*(pixel.red-mid.red);
885 error.green=QuantumScale*(pixel.green-mid.green);
886 error.blue=QuantumScale*(pixel.blue-mid.blue);
887 if (cube_info->associate_alpha != MagickFalse)
888 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
889 distance=(double) (error.red*error.red+error.green*error.green+
890 error.blue*error.blue+error.alpha*error.alpha);
891 if (IsNaN(distance) != MagickFalse)
893 node_info->quantize_error+=count*sqrt(distance);
894 cube_info->root->quantize_error+=node_info->quantize_error;
898 Sum RGB for this leaf for later derivation of the mean cube color.
900 node_info->number_unique+=count;
901 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
902 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
903 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
904 if (cube_info->associate_alpha != MagickFalse)
905 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
907 p+=count*GetPixelChannels(image);
909 if (cube_info->colors > cube_info->maximum_colors)
911 PruneToCubeDepth(image,cube_info,cube_info->root);
914 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
916 if (proceed == MagickFalse)
919 for (y++; y < (ssize_t) image->rows; y++)
921 register const Quantum
927 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
928 if (p == (const Quantum *) NULL)
930 if (cube_info->nodes > MaxNodes)
933 Prune one level if the color tree is too large.
935 PruneLevel(image,cube_info,cube_info->root);
938 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
941 Start at the root and descend the color cube tree.
943 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
948 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
949 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
952 AssociateAlphaPixel(image,cube_info,p,&pixel);
953 index=MaxTreeDepth-1;
954 bisect=((double) QuantumRange+1.0)/2.0;
956 node_info=cube_info->root;
957 for (level=1; level <= cube_info->depth; level++)
963 id=ColorToNodeId(cube_info,&pixel,index);
964 mid.red+=(id & 1) != 0 ? bisect : -bisect;
965 mid.green+=(id & 2) != 0 ? bisect : -bisect;
966 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
967 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
968 if (node_info->child[id] == (NodeInfo *) NULL)
971 Set colors of new node to contain pixel.
973 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
974 if (node_info->child[id] == (NodeInfo *) NULL)
976 (void) ThrowMagickException(exception,GetMagickModule(),
977 ResourceLimitError,"MemoryAllocationFailed","%s",
981 if (level == cube_info->depth)
985 Approximate the quantization error represented by this node.
987 node_info=node_info->child[id];
988 error.red=QuantumScale*(pixel.red-mid.red);
989 error.green=QuantumScale*(pixel.green-mid.green);
990 error.blue=QuantumScale*(pixel.blue-mid.blue);
991 if (cube_info->associate_alpha != MagickFalse)
992 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
993 distance=(double) (error.red*error.red+error.green*error.green+
994 error.blue*error.blue+error.alpha*error.alpha);
995 if (IsNaN(distance) != MagickFalse)
997 node_info->quantize_error+=count*sqrt(distance);
998 cube_info->root->quantize_error+=node_info->quantize_error;
1002 Sum RGB for this leaf for later derivation of the mean cube color.
1004 node_info->number_unique+=count;
1005 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
1006 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
1007 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
1008 if (cube_info->associate_alpha != MagickFalse)
1009 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
1011 p+=count*GetPixelChannels(image);
1013 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1015 if (proceed == MagickFalse)
1018 image_view=DestroyCacheView(image_view);
1019 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1020 (cube_info->quantize_info->colorspace != CMYKColorspace))
1021 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1022 return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1030 % C l o n e Q u a n t i z e I n f o %
1034 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1036 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1037 % or if quantize info is NULL, a new one.
1039 % The format of the CloneQuantizeInfo method is:
1041 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1043 % A description of each parameter follows:
1045 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1046 % quantize info, or if image info is NULL a new one.
1048 % o quantize_info: a structure of type info.
1051 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1056 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1057 if (clone_info == (QuantizeInfo *) NULL)
1058 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1059 GetQuantizeInfo(clone_info);
1060 if (quantize_info == (QuantizeInfo *) NULL)
1062 clone_info->number_colors=quantize_info->number_colors;
1063 clone_info->tree_depth=quantize_info->tree_depth;
1064 clone_info->dither_method=quantize_info->dither_method;
1065 clone_info->colorspace=quantize_info->colorspace;
1066 clone_info->measure_error=quantize_info->measure_error;
1071 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1075 + C l o s e s t C o l o r %
1079 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1081 % ClosestColor() traverses the color cube tree at a particular node and
1082 % determines which colormap entry best represents the input color.
1084 % The format of the ClosestColor method is:
1086 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1087 % const NodeInfo *node_info)
1089 % A description of each parameter follows.
1091 % o image: the image.
1093 % o cube_info: A pointer to the Cube structure.
1095 % o node_info: the address of a structure of type NodeInfo which points to a
1096 % node in the color cube tree that is to be pruned.
1099 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1100 const NodeInfo *node_info)
1109 Traverse any children.
1111 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1112 for (i=0; i < (ssize_t) number_children; i++)
1113 if (node_info->child[i] != (NodeInfo *) NULL)
1114 ClosestColor(image,cube_info,node_info->child[i]);
1115 if (node_info->number_unique != 0)
1128 register RealPixelInfo
1132 Determine if this color is "closest".
1134 p=image->colormap+node_info->color_number;
1135 q=(&cube_info->target);
1138 if (cube_info->associate_alpha != MagickFalse)
1140 alpha=(double) (QuantumScale*p->alpha);
1141 beta=(double) (QuantumScale*q->alpha);
1143 pixel=alpha*p->red-beta*q->red;
1144 distance=pixel*pixel;
1145 if (distance <= cube_info->distance)
1147 pixel=alpha*p->green-beta*q->green;
1148 distance+=pixel*pixel;
1149 if (distance <= cube_info->distance)
1151 pixel=alpha*p->blue-beta*q->blue;
1152 distance+=pixel*pixel;
1153 if (distance <= cube_info->distance)
1156 distance+=pixel*pixel;
1157 if (distance <= cube_info->distance)
1159 cube_info->distance=distance;
1160 cube_info->color_number=node_info->color_number;
1169 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1173 % C o m p r e s s I m a g e C o l o r m a p %
1177 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1179 % CompressImageColormap() compresses an image colormap by removing any
1180 % duplicate or unused color entries.
1182 % The format of the CompressImageColormap method is:
1184 % MagickBooleanType CompressImageColormap(Image *image,
1185 % ExceptionInfo *exception)
1187 % A description of each parameter follows:
1189 % o image: the image.
1191 % o exception: return any errors or warnings in this structure.
1194 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1195 ExceptionInfo *exception)
1200 assert(image != (Image *) NULL);
1201 assert(image->signature == MagickSignature);
1202 if (image->debug != MagickFalse)
1203 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1204 if (IsPaletteImage(image,exception) == MagickFalse)
1205 return(MagickFalse);
1206 GetQuantizeInfo(&quantize_info);
1207 quantize_info.number_colors=image->colors;
1208 quantize_info.tree_depth=MaxTreeDepth;
1209 return(QuantizeImage(&quantize_info,image,exception));
1213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1217 + D e f i n e I m a g e C o l o r m a p %
1221 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1223 % DefineImageColormap() traverses the color cube tree and notes each colormap
1224 % entry. A colormap entry is any node in the color cube tree where the
1225 % of unique colors is not zero. DefineImageColormap() returns the number of
1226 % colors in the image colormap.
1228 % The format of the DefineImageColormap method is:
1230 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1231 % NodeInfo *node_info)
1233 % A description of each parameter follows.
1235 % o image: the image.
1237 % o cube_info: A pointer to the Cube structure.
1239 % o node_info: the address of a structure of type NodeInfo which points to a
1240 % node in the color cube tree that is to be pruned.
1243 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1244 NodeInfo *node_info)
1253 Traverse any children.
1255 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1256 for (i=0; i < (ssize_t) number_children; i++)
1257 if (node_info->child[i] != (NodeInfo *) NULL)
1258 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1259 if (node_info->number_unique != 0)
1268 Colormap entry is defined by the mean color in this cube.
1270 q=image->colormap+image->colors;
1271 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1272 alpha=PerceptibleReciprocal(alpha);
1273 if (cube_info->associate_alpha == MagickFalse)
1275 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1276 node_info->total_color.red);
1277 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1278 node_info->total_color.green);
1279 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1280 node_info->total_color.blue);
1281 q->alpha=(double) OpaqueAlpha;
1288 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1289 q->alpha=(double) ClampToQuantum((opacity));
1290 if (q->alpha == OpaqueAlpha)
1292 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1293 node_info->total_color.red);
1294 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1295 node_info->total_color.green);
1296 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1297 node_info->total_color.blue);
1304 gamma=(double) (QuantumScale*q->alpha);
1305 gamma=PerceptibleReciprocal(gamma);
1306 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1307 node_info->total_color.red);
1308 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1309 node_info->total_color.green);
1310 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1311 node_info->total_color.blue);
1312 if (node_info->number_unique > cube_info->transparent_pixels)
1314 cube_info->transparent_pixels=node_info->number_unique;
1315 cube_info->transparent_index=(ssize_t) image->colors;
1319 node_info->color_number=image->colors++;
1321 return(image->colors);
1325 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1329 + D e s t r o y C u b e I n f o %
1333 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1335 % DestroyCubeInfo() deallocates memory associated with an image.
1337 % The format of the DestroyCubeInfo method is:
1339 % DestroyCubeInfo(CubeInfo *cube_info)
1341 % A description of each parameter follows:
1343 % o cube_info: the address of a structure of type CubeInfo.
1346 static void DestroyCubeInfo(CubeInfo *cube_info)
1352 Release color cube tree storage.
1356 nodes=cube_info->node_queue->next;
1357 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1358 cube_info->node_queue->nodes);
1359 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1360 cube_info->node_queue);
1361 cube_info->node_queue=nodes;
1362 } while (cube_info->node_queue != (Nodes *) NULL);
1363 if (cube_info->memory_info != (MemoryInfo *) NULL)
1364 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1365 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1366 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1370 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1374 % D e s t r o y Q u a n t i z e I n f o %
1378 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1380 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1383 % The format of the DestroyQuantizeInfo method is:
1385 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1387 % A description of each parameter follows:
1389 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1392 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1394 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1395 assert(quantize_info != (QuantizeInfo *) NULL);
1396 assert(quantize_info->signature == MagickSignature);
1397 quantize_info->signature=(~MagickSignature);
1398 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1399 return(quantize_info);
1403 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1407 + D i t h e r I m a g e %
1411 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1413 % DitherImage() distributes the difference between an original image and
1414 % the corresponding color reduced algorithm to neighboring pixels using
1415 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1416 % MagickTrue if the image is dithered otherwise MagickFalse.
1418 % The format of the DitherImage method is:
1420 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1421 % ExceptionInfo *exception)
1423 % A description of each parameter follows.
1425 % o image: the image.
1427 % o cube_info: A pointer to the Cube structure.
1429 % o exception: return any errors or warnings in this structure.
1433 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1438 assert(pixels != (RealPixelInfo **) NULL);
1439 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1440 if (pixels[i] != (RealPixelInfo *) NULL)
1441 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1442 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1446 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1457 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1458 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1460 if (pixels == (RealPixelInfo **) NULL)
1461 return((RealPixelInfo **) NULL);
1462 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1463 for (i=0; i < (ssize_t) number_threads; i++)
1465 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1466 if (pixels[i] == (RealPixelInfo *) NULL)
1467 return(DestroyPixelThreadSet(pixels));
1472 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1473 const RealPixelInfo *pixel)
1475 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1476 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1477 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1478 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1483 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1484 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1485 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1486 if (cube_info->associate_alpha != MagickFalse)
1487 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1491 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1492 ExceptionInfo *exception)
1494 #define DitherImageTag "Dither/Image"
1509 Distribute quantization error using Floyd-Steinberg.
1511 pixels=AcquirePixelThreadSet(image->columns);
1512 if (pixels == (RealPixelInfo **) NULL)
1513 return(MagickFalse);
1515 image_view=AcquireAuthenticCacheView(image,exception);
1516 for (y=0; y < (ssize_t) image->rows; y++)
1519 id = GetOpenMPThreadId();
1540 if (status == MagickFalse)
1542 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1543 if (q == (Quantum *) NULL)
1548 q+=(y & 0x01)*GetPixelChannels(image)*image->columns;
1550 current=pixels[id]+(y & 0x01)*image->columns;
1551 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1552 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1553 for (x=0; x < (ssize_t) image->columns; x++)
1565 q-=(y & 0x01)*GetPixelChannels(image);
1566 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1567 AssociateAlphaPixel(image,&cube,q,&pixel);
1570 pixel.red+=7*current[u-v].red/16;
1571 pixel.green+=7*current[u-v].green/16;
1572 pixel.blue+=7*current[u-v].blue/16;
1573 if (cube.associate_alpha != MagickFalse)
1574 pixel.alpha+=7*current[u-v].alpha/16;
1578 if (x < (ssize_t) (image->columns-1))
1580 pixel.red+=previous[u+v].red/16;
1581 pixel.green+=previous[u+v].green/16;
1582 pixel.blue+=previous[u+v].blue/16;
1583 if (cube.associate_alpha != MagickFalse)
1584 pixel.alpha+=previous[u+v].alpha/16;
1586 pixel.red+=5*previous[u].red/16;
1587 pixel.green+=5*previous[u].green/16;
1588 pixel.blue+=5*previous[u].blue/16;
1589 if (cube.associate_alpha != MagickFalse)
1590 pixel.alpha+=5*previous[u].alpha/16;
1593 pixel.red+=3*previous[u-v].red/16;
1594 pixel.green+=3*previous[u-v].green/16;
1595 pixel.blue+=3*previous[u-v].blue/16;
1596 if (cube.associate_alpha != MagickFalse)
1597 pixel.alpha+=3*previous[u-v].alpha/16;
1600 pixel.red=(double) ClampPixel(pixel.red);
1601 pixel.green=(double) ClampPixel(pixel.green);
1602 pixel.blue=(double) ClampPixel(pixel.blue);
1603 if (cube.associate_alpha != MagickFalse)
1604 pixel.alpha=(double) ClampPixel(pixel.alpha);
1605 i=CacheOffset(&cube,&pixel);
1606 if (cube.cache[i] < 0)
1615 Identify the deepest node containing the pixel's color.
1617 node_info=cube.root;
1618 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1620 id=ColorToNodeId(&cube,&pixel,index);
1621 if (node_info->child[id] == (NodeInfo *) NULL)
1623 node_info=node_info->child[id];
1626 Find closest color among siblings and their children.
1629 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1631 ClosestColor(image,&cube,node_info->parent);
1632 cube.cache[i]=(ssize_t) cube.color_number;
1635 Assign pixel to closest colormap entry.
1637 index=(size_t) cube.cache[i];
1638 if (image->storage_class == PseudoClass)
1639 SetPixelIndex(image,(Quantum) index,q);
1640 if (cube.quantize_info->measure_error == MagickFalse)
1642 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1643 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1644 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1645 if (cube.associate_alpha != MagickFalse)
1646 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1648 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1653 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1654 current[u].red=pixel.red-color.red;
1655 current[u].green=pixel.green-color.green;
1656 current[u].blue=pixel.blue-color.blue;
1657 if (cube.associate_alpha != MagickFalse)
1658 current[u].alpha=pixel.alpha-color.alpha;
1659 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1664 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1666 if (proceed == MagickFalse)
1669 q+=((y+1) & 0x01)*GetPixelChannels(image);
1672 image_view=DestroyCacheView(image_view);
1673 pixels=DestroyPixelThreadSet(pixels);
1677 static MagickBooleanType
1678 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1679 ExceptionInfo *exception);
1681 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1682 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1689 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1691 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1693 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1699 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1701 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1703 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1709 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1711 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1713 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1719 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1721 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1723 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1735 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1737 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1739 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1741 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1743 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1745 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1747 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1753 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1755 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1757 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1759 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1761 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1763 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1765 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1771 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1773 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1775 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1777 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1779 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1781 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1783 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1789 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1791 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1793 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1795 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1797 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1799 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1801 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1810 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1811 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1813 #define DitherImageTag "Dither/Image"
1829 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1830 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1841 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1842 if (q == (Quantum *) NULL)
1843 return(MagickFalse);
1844 AssociateAlphaPixel(image,cube_info,q,&pixel);
1845 for (i=0; i < ErrorQueueLength; i++)
1847 pixel.red+=p->weights[i]*p->error[i].red;
1848 pixel.green+=p->weights[i]*p->error[i].green;
1849 pixel.blue+=p->weights[i]*p->error[i].blue;
1850 if (cube_info->associate_alpha != MagickFalse)
1851 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1853 pixel.red=(double) ClampPixel(pixel.red);
1854 pixel.green=(double) ClampPixel(pixel.green);
1855 pixel.blue=(double) ClampPixel(pixel.blue);
1856 if (cube_info->associate_alpha != MagickFalse)
1857 pixel.alpha=(double) ClampPixel(pixel.alpha);
1858 i=CacheOffset(cube_info,&pixel);
1859 if (p->cache[i] < 0)
1868 Identify the deepest node containing the pixel's color.
1871 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1873 id=ColorToNodeId(cube_info,&pixel,index);
1874 if (node_info->child[id] == (NodeInfo *) NULL)
1876 node_info=node_info->child[id];
1879 Find closest color among siblings and their children.
1882 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1883 QuantumRange+1.0)+1.0);
1884 ClosestColor(image,p,node_info->parent);
1885 p->cache[i]=(ssize_t) p->color_number;
1888 Assign pixel to closest colormap entry.
1890 index=(size_t) p->cache[i];
1891 if (image->storage_class == PseudoClass)
1892 SetPixelIndex(image,(Quantum) index,q);
1893 if (cube_info->quantize_info->measure_error == MagickFalse)
1895 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1896 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1897 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1898 if (cube_info->associate_alpha != MagickFalse)
1899 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1901 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1902 return(MagickFalse);
1904 Propagate the error as the last entry of the error queue.
1906 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1907 sizeof(p->error[0]));
1908 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1909 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1910 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1911 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1912 if (cube_info->associate_alpha != MagickFalse)
1913 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1914 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1915 if (proceed == MagickFalse)
1916 return(MagickFalse);
1921 case WestGravity: p->x--; break;
1922 case EastGravity: p->x++; break;
1923 case NorthGravity: p->y--; break;
1924 case SouthGravity: p->y++; break;
1929 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1936 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1943 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1944 ExceptionInfo *exception)
1958 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1959 return(FloydSteinbergDither(image,cube_info,exception));
1961 Distribute quantization error along a Hilbert curve.
1963 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1964 sizeof(*cube_info->error));
1967 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1968 for (depth=1; i != 0; depth++)
1970 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1972 cube_info->offset=0;
1973 cube_info->span=(MagickSizeType) image->columns*image->rows;
1974 image_view=AcquireAuthenticCacheView(image,exception);
1976 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1977 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1978 image_view=DestroyCacheView(image_view);
1983 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1987 + G e t C u b e I n f o %
1991 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1993 % GetCubeInfo() initialize the Cube data structure.
1995 % The format of the GetCubeInfo method is:
1997 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1998 % const size_t depth,const size_t maximum_colors)
2000 % A description of each parameter follows.
2002 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2004 % o depth: Normally, this integer value is zero or one. A zero or
2005 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
2006 % A tree of this depth generally allows the best representation of the
2007 % reference image with the least amount of memory and the fastest
2008 % computational speed. In some cases, such as an image with low color
2009 % dispersion (a few number of colors), a value other than
2010 % Log4(number_colors) is required. To expand the color tree completely,
2013 % o maximum_colors: maximum colors.
2016 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2017 const size_t depth,const size_t maximum_colors)
2033 Initialize tree to describe color cube_info.
2035 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2036 if (cube_info == (CubeInfo *) NULL)
2037 return((CubeInfo *) NULL);
2038 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2039 cube_info->depth=depth;
2040 if (cube_info->depth > MaxTreeDepth)
2041 cube_info->depth=MaxTreeDepth;
2042 if (cube_info->depth < 2)
2044 cube_info->maximum_colors=maximum_colors;
2046 Initialize root node.
2048 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2049 if (cube_info->root == (NodeInfo *) NULL)
2050 return((CubeInfo *) NULL);
2051 cube_info->root->parent=cube_info->root;
2052 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2053 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2056 Initialize dither resources.
2058 length=(size_t) (1UL << (4*(8-CacheShift)));
2059 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2060 if (cube_info->memory_info == (MemoryInfo *) NULL)
2061 return((CubeInfo *) NULL);
2062 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2064 Initialize color cache.
2066 for (i=0; i < (ssize_t) length; i++)
2067 cube_info->cache[i]=(-1);
2069 Distribute weights along a curve of exponential decay.
2072 for (i=0; i < ErrorQueueLength; i++)
2074 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2075 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2078 Normalize the weighting factors.
2081 for (i=0; i < ErrorQueueLength; i++)
2082 weight+=cube_info->weights[i];
2084 for (i=0; i < ErrorQueueLength; i++)
2086 cube_info->weights[i]/=weight;
2087 sum+=cube_info->weights[i];
2089 cube_info->weights[0]+=1.0-sum;
2094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2098 + G e t N o d e I n f o %
2102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2104 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2105 % presets all fields to zero.
2107 % The format of the GetNodeInfo method is:
2109 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2110 % const size_t level,NodeInfo *parent)
2112 % A description of each parameter follows.
2114 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2116 % o id: Specifies the child number of the node.
2118 % o level: Specifies the level in the storage_class the node resides.
2121 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2122 const size_t level,NodeInfo *parent)
2127 if (cube_info->free_nodes == 0)
2133 Allocate a new queue of nodes.
2135 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2136 if (nodes == (Nodes *) NULL)
2137 return((NodeInfo *) NULL);
2138 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2139 sizeof(*nodes->nodes));
2140 if (nodes->nodes == (NodeInfo *) NULL)
2141 return((NodeInfo *) NULL);
2142 nodes->next=cube_info->node_queue;
2143 cube_info->node_queue=nodes;
2144 cube_info->next_node=nodes->nodes;
2145 cube_info->free_nodes=NodesInAList;
2148 cube_info->free_nodes--;
2149 node_info=cube_info->next_node++;
2150 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2151 node_info->parent=parent;
2153 node_info->level=level;
2158 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2162 % G e t I m a g e Q u a n t i z e E r r o r %
2166 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2168 % GetImageQuantizeError() measures the difference between the original
2169 % and quantized images. This difference is the total quantization error.
2170 % The error is computed by summing over all pixels in an image the distance
2171 % squared in RGB space between each reference pixel value and its quantized
2172 % value. These values are computed:
2174 % o mean_error_per_pixel: This value is the mean error for any single
2175 % pixel in the image.
2177 % o normalized_mean_square_error: This value is the normalized mean
2178 % quantization error for any single pixel in the image. This distance
2179 % measure is normalized to a range between 0 and 1. It is independent
2180 % of the range of red, green, and blue values in the image.
2182 % o normalized_maximum_square_error: Thsi value is the normalized
2183 % maximum quantization error for any single pixel in the image. This
2184 % distance measure is normalized to a range between 0 and 1. It is
2185 % independent of the range of red, green, and blue values in your image.
2187 % The format of the GetImageQuantizeError method is:
2189 % MagickBooleanType GetImageQuantizeError(Image *image,
2190 % ExceptionInfo *exception)
2192 % A description of each parameter follows.
2194 % o image: the image.
2196 % o exception: return any errors or warnings in this structure.
2199 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2200 ExceptionInfo *exception)
2212 mean_error_per_pixel;
2220 assert(image != (Image *) NULL);
2221 assert(image->signature == MagickSignature);
2222 if (image->debug != MagickFalse)
2223 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2224 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2225 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2226 if (image->storage_class == DirectClass)
2230 area=3.0*image->columns*image->rows;
2232 mean_error_per_pixel=0.0;
2234 image_view=AcquireVirtualCacheView(image,exception);
2235 for (y=0; y < (ssize_t) image->rows; y++)
2237 register const Quantum
2243 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2244 if (p == (const Quantum *) NULL)
2246 for (x=0; x < (ssize_t) image->columns; x++)
2248 index=1UL*GetPixelIndex(image,p);
2249 if (image->alpha_trait != UndefinedPixelTrait)
2251 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2252 beta=(double) (QuantumScale*image->colormap[index].alpha);
2254 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2255 image->colormap[index].red);
2256 mean_error_per_pixel+=distance;
2257 mean_error+=distance*distance;
2258 if (distance > maximum_error)
2259 maximum_error=distance;
2260 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2261 image->colormap[index].green);
2262 mean_error_per_pixel+=distance;
2263 mean_error+=distance*distance;
2264 if (distance > maximum_error)
2265 maximum_error=distance;
2266 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2267 image->colormap[index].blue);
2268 mean_error_per_pixel+=distance;
2269 mean_error+=distance*distance;
2270 if (distance > maximum_error)
2271 maximum_error=distance;
2272 p+=GetPixelChannels(image);
2275 image_view=DestroyCacheView(image_view);
2276 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2277 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2279 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2284 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2288 % G e t Q u a n t i z e I n f o %
2292 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2294 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2296 % The format of the GetQuantizeInfo method is:
2298 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2300 % A description of each parameter follows:
2302 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2305 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2307 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2308 assert(quantize_info != (QuantizeInfo *) NULL);
2309 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2310 quantize_info->number_colors=256;
2311 quantize_info->dither_method=RiemersmaDitherMethod;
2312 quantize_info->colorspace=UndefinedColorspace;
2313 quantize_info->measure_error=MagickFalse;
2314 quantize_info->signature=MagickSignature;
2318 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2322 % P o s t e r i z e I m a g e %
2326 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2328 % PosterizeImage() reduces the image to a limited number of colors for a
2331 % The format of the PosterizeImage method is:
2333 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2334 % const DitherMethod dither_method,ExceptionInfo *exception)
2336 % A description of each parameter follows:
2338 % o image: Specifies a pointer to an Image structure.
2340 % o levels: Number of color levels allowed in each channel. Very low values
2341 % (2, 3, or 4) have the most visible effect.
2343 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2344 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2346 % o exception: return any errors or warnings in this structure.
2350 static inline double MagickRound(double x)
2353 Round the fraction to nearest integer.
2355 if ((x-floor(x)) < (ceil(x)-x))
2360 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2361 const DitherMethod dither_method,ExceptionInfo *exception)
2363 #define PosterizeImageTag "Posterize/Image"
2364 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2365 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2385 assert(image != (Image *) NULL);
2386 assert(image->signature == MagickSignature);
2387 if (image->debug != MagickFalse)
2388 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2389 if (image->storage_class == PseudoClass)
2390 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2391 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2392 magick_threads(image,image,1,1)
2394 for (i=0; i < (ssize_t) image->colors; i++)
2399 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2400 image->colormap[i].red=(double)
2401 PosterizePixel(image->colormap[i].red);
2402 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2403 image->colormap[i].green=(double)
2404 PosterizePixel(image->colormap[i].green);
2405 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2406 image->colormap[i].blue=(double)
2407 PosterizePixel(image->colormap[i].blue);
2408 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2409 image->colormap[i].alpha=(double)
2410 PosterizePixel(image->colormap[i].alpha);
2417 image_view=AcquireAuthenticCacheView(image,exception);
2418 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2419 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2420 magick_threads(image,image,image->rows,1)
2422 for (y=0; y < (ssize_t) image->rows; y++)
2430 if (status == MagickFalse)
2432 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2433 if (q == (Quantum *) NULL)
2438 for (x=0; x < (ssize_t) image->columns; x++)
2440 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2441 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2442 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2443 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2444 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2445 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2446 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2447 (image->colorspace == CMYKColorspace))
2448 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2449 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2450 (image->alpha_trait != UndefinedPixelTrait))
2451 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2452 q+=GetPixelChannels(image);
2454 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2456 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2461 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2462 #pragma omp critical (MagickCore_PosterizeImage)
2464 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2466 if (proceed == MagickFalse)
2470 image_view=DestroyCacheView(image_view);
2471 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2472 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2473 levels,MaxColormapSize+1);
2474 quantize_info->dither_method=dither_method;
2475 quantize_info->tree_depth=MaxTreeDepth;
2476 status=QuantizeImage(quantize_info,image,exception);
2477 quantize_info=DestroyQuantizeInfo(quantize_info);
2482 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2486 + P r u n e C h i l d %
2490 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2492 % PruneChild() deletes the given node and merges its statistics into its
2495 % The format of the PruneSubtree method is:
2497 % PruneChild(const Image *image,CubeInfo *cube_info,
2498 % const NodeInfo *node_info)
2500 % A description of each parameter follows.
2502 % o image: the image.
2504 % o cube_info: A pointer to the Cube structure.
2506 % o node_info: pointer to node in color cube tree that is to be pruned.
2509 static void PruneChild(const Image *image,CubeInfo *cube_info,
2510 const NodeInfo *node_info)
2522 Traverse any children.
2524 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2525 for (i=0; i < (ssize_t) number_children; i++)
2526 if (node_info->child[i] != (NodeInfo *) NULL)
2527 PruneChild(image,cube_info,node_info->child[i]);
2529 Merge color statistics into parent.
2531 parent=node_info->parent;
2532 parent->number_unique+=node_info->number_unique;
2533 parent->total_color.red+=node_info->total_color.red;
2534 parent->total_color.green+=node_info->total_color.green;
2535 parent->total_color.blue+=node_info->total_color.blue;
2536 parent->total_color.alpha+=node_info->total_color.alpha;
2537 parent->child[node_info->id]=(NodeInfo *) NULL;
2542 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2546 + P r u n e L e v e l %
2550 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2552 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2553 % their color statistics into their parent node.
2555 % The format of the PruneLevel method is:
2557 % PruneLevel(const Image *image,CubeInfo *cube_info,
2558 % const NodeInfo *node_info)
2560 % A description of each parameter follows.
2562 % o image: the image.
2564 % o cube_info: A pointer to the Cube structure.
2566 % o node_info: pointer to node in color cube tree that is to be pruned.
2569 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2570 const NodeInfo *node_info)
2579 Traverse any children.
2581 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2582 for (i=0; i < (ssize_t) number_children; i++)
2583 if (node_info->child[i] != (NodeInfo *) NULL)
2584 PruneLevel(image,cube_info,node_info->child[i]);
2585 if (node_info->level == cube_info->depth)
2586 PruneChild(image,cube_info,node_info);
2590 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2594 + P r u n e T o C u b e D e p t h %
2598 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2600 % PruneToCubeDepth() deletes any nodes at a depth greater than
2601 % cube_info->depth while merging their color statistics into their parent
2604 % The format of the PruneToCubeDepth method is:
2606 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2607 % const NodeInfo *node_info)
2609 % A description of each parameter follows.
2611 % o cube_info: A pointer to the Cube structure.
2613 % o node_info: pointer to node in color cube tree that is to be pruned.
2616 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2617 const NodeInfo *node_info)
2626 Traverse any children.
2628 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2629 for (i=0; i < (ssize_t) number_children; i++)
2630 if (node_info->child[i] != (NodeInfo *) NULL)
2631 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2632 if (node_info->level > cube_info->depth)
2633 PruneChild(image,cube_info,node_info);
2637 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2641 % Q u a n t i z e I m a g e %
2645 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2647 % QuantizeImage() analyzes the colors within a reference image and chooses a
2648 % fixed number of colors to represent the image. The goal of the algorithm
2649 % is to minimize the color difference between the input and output image while
2650 % minimizing the processing time.
2652 % The format of the QuantizeImage method is:
2654 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2655 % Image *image,ExceptionInfo *exception)
2657 % A description of each parameter follows:
2659 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2661 % o image: the image.
2663 % o exception: return any errors or warnings in this structure.
2667 static MagickBooleanType DirectToColormapImage(Image *image,
2668 ExceptionInfo *exception)
2686 number_colors=(size_t) (image->columns*image->rows);
2687 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2688 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2690 if (image->colors != number_colors)
2691 return(MagickFalse);
2693 image_view=AcquireAuthenticCacheView(image,exception);
2694 for (y=0; y < (ssize_t) image->rows; y++)
2705 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2706 if (q == (Quantum *) NULL)
2708 for (x=0; x < (ssize_t) image->columns; x++)
2710 image->colormap[i].red=(double) GetPixelRed(image,q);
2711 image->colormap[i].green=(double) GetPixelGreen(image,q);
2712 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2713 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2714 SetPixelIndex(image,(Quantum) i,q);
2716 q+=GetPixelChannels(image);
2718 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2720 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2722 if (proceed == MagickFalse)
2725 image_view=DestroyCacheView(image_view);
2729 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2730 Image *image,ExceptionInfo *exception)
2742 assert(quantize_info != (const QuantizeInfo *) NULL);
2743 assert(quantize_info->signature == MagickSignature);
2744 assert(image != (Image *) NULL);
2745 assert(image->signature == MagickSignature);
2746 if (image->debug != MagickFalse)
2747 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2748 maximum_colors=quantize_info->number_colors;
2749 if (maximum_colors == 0)
2750 maximum_colors=MaxColormapSize;
2751 if (maximum_colors > MaxColormapSize)
2752 maximum_colors=MaxColormapSize;
2753 if (image->alpha_trait == UndefinedPixelTrait)
2755 if ((image->columns*image->rows) <= maximum_colors)
2756 (void) DirectToColormapImage(image,exception);
2757 if (IsImageGray(image,exception) != MagickFalse)
2758 (void) SetGrayscaleImage(image,exception);
2760 if ((image->storage_class == PseudoClass) &&
2761 (image->colors <= maximum_colors))
2763 depth=quantize_info->tree_depth;
2770 Depth of color tree is: Log4(colormap size)+2.
2772 colors=maximum_colors;
2773 for (depth=1; colors != 0; depth++)
2775 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2777 if ((image->alpha_trait != UndefinedPixelTrait) && (depth > 5))
2779 if (IsImageGray(image,exception) != MagickFalse)
2783 Initialize color cube.
2785 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2786 if (cube_info == (CubeInfo *) NULL)
2787 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2789 status=ClassifyImageColors(cube_info,image,exception);
2790 if (status != MagickFalse)
2793 Reduce the number of colors in the image.
2795 ReduceImageColors(image,cube_info);
2796 status=AssignImageColors(image,cube_info,exception);
2798 DestroyCubeInfo(cube_info);
2803 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2807 % Q u a n t i z e I m a g e s %
2811 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2813 % QuantizeImages() analyzes the colors within a set of reference images and
2814 % chooses a fixed number of colors to represent the set. The goal of the
2815 % algorithm is to minimize the color difference between the input and output
2816 % images while minimizing the processing time.
2818 % The format of the QuantizeImages method is:
2820 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2821 % Image *images,ExceptionInfo *exception)
2823 % A description of each parameter follows:
2825 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2827 % o images: Specifies a pointer to a list of Image structures.
2829 % o exception: return any errors or warnings in this structure.
2832 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2833 Image *images,ExceptionInfo *exception)
2845 MagickProgressMonitor
2856 assert(quantize_info != (const QuantizeInfo *) NULL);
2857 assert(quantize_info->signature == MagickSignature);
2858 assert(images != (Image *) NULL);
2859 assert(images->signature == MagickSignature);
2860 if (images->debug != MagickFalse)
2861 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2862 if (GetNextImageInList(images) == (Image *) NULL)
2865 Handle a single image with QuantizeImage.
2867 status=QuantizeImage(quantize_info,images,exception);
2871 maximum_colors=quantize_info->number_colors;
2872 if (maximum_colors == 0)
2873 maximum_colors=MaxColormapSize;
2874 if (maximum_colors > MaxColormapSize)
2875 maximum_colors=MaxColormapSize;
2876 depth=quantize_info->tree_depth;
2883 Depth of color tree is: Log4(colormap size)+2.
2885 colors=maximum_colors;
2886 for (depth=1; colors != 0; depth++)
2888 if (quantize_info->dither_method != NoDitherMethod)
2892 Initialize color cube.
2894 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2895 if (cube_info == (CubeInfo *) NULL)
2897 (void) ThrowMagickException(exception,GetMagickModule(),
2898 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2899 return(MagickFalse);
2901 number_images=GetImageListLength(images);
2903 for (i=0; image != (Image *) NULL; i++)
2905 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2906 image->client_data);
2907 status=ClassifyImageColors(cube_info,image,exception);
2908 if (status == MagickFalse)
2910 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2911 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2913 if (proceed == MagickFalse)
2915 image=GetNextImageInList(image);
2917 if (status != MagickFalse)
2920 Reduce the number of colors in an image sequence.
2922 ReduceImageColors(images,cube_info);
2924 for (i=0; image != (Image *) NULL; i++)
2926 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2927 NULL,image->client_data);
2928 status=AssignImageColors(image,cube_info,exception);
2929 if (status == MagickFalse)
2931 (void) SetImageProgressMonitor(image,progress_monitor,
2932 image->client_data);
2933 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2935 if (proceed == MagickFalse)
2937 image=GetNextImageInList(image);
2940 DestroyCubeInfo(cube_info);
2945 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2949 + Q u a n t i z e E r r o r F l a t t e n %
2953 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2955 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2956 % error into a sorted 1D array. This accelerates the color reduction process.
2958 % Contributed by Yoya.
2960 % The format of the QuantizeImages method is:
2962 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2963 % const NodeInfo *node_info,const ssize_t offset,
2964 % MagickRealType *quantize_error)
2966 % A description of each parameter follows.
2968 % o image: the image.
2970 % o cube_info: A pointer to the Cube structure.
2972 % o node_info: pointer to node in color cube tree that is current pointer.
2974 % o offset: quantize error offset.
2976 % o quantize_error: the quantization error vector.
2979 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2980 const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
2989 if (offset >= (ssize_t) cube_info->nodes)
2991 quantize_error[offset]=node_info->quantize_error;
2993 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2994 for (i=0; i < (ssize_t) number_children ; i++)
2995 if (node_info->child[i] != (NodeInfo *) NULL)
2996 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
3002 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3010 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3012 % Reduce() traverses the color cube tree and prunes any node whose
3013 % quantization error falls below a particular threshold.
3015 % The format of the Reduce method is:
3017 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3019 % A description of each parameter follows.
3021 % o image: the image.
3023 % o cube_info: A pointer to the Cube structure.
3025 % o node_info: pointer to node in color cube tree that is to be pruned.
3028 static void Reduce(const Image *image,CubeInfo *cube_info,
3029 const NodeInfo *node_info)
3038 Traverse any children.
3040 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3041 for (i=0; i < (ssize_t) number_children; i++)
3042 if (node_info->child[i] != (NodeInfo *) NULL)
3043 Reduce(image,cube_info,node_info->child[i]);
3044 if (node_info->quantize_error <= cube_info->pruning_threshold)
3045 PruneChild(image,cube_info,node_info);
3049 Find minimum pruning threshold.
3051 if (node_info->number_unique > 0)
3052 cube_info->colors++;
3053 if (node_info->quantize_error < cube_info->next_threshold)
3054 cube_info->next_threshold=node_info->quantize_error;
3059 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3063 + R e d u c e I m a g e C o l o r s %
3067 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3069 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3070 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3071 % in the output image. On any given iteration over the tree, it selects
3072 % those nodes whose E value is minimal for pruning and merges their
3073 % color statistics upward. It uses a pruning threshold, Ep, to govern
3074 % node selection as follows:
3077 % while number of nodes with (n2 > 0) > required maximum number of colors
3078 % prune all nodes such that E <= Ep
3079 % Set Ep to minimum E in remaining nodes
3081 % This has the effect of minimizing any quantization error when merging
3082 % two nodes together.
3084 % When a node to be pruned has offspring, the pruning procedure invokes
3085 % itself recursively in order to prune the tree from the leaves upward.
3086 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3087 % corresponding data in that node's parent. This retains the pruned
3088 % node's color characteristics for later averaging.
3090 % For each node, n2 pixels exist for which that node represents the
3091 % smallest volume in RGB space containing those pixel's colors. When n2
3092 % > 0 the node will uniquely define a color in the output image. At the
3093 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3094 % the tree which represent colors present in the input image.
3096 % The other pixel count, n1, indicates the total number of colors
3097 % within the cubic volume which the node represents. This includes n1 -
3098 % n2 pixels whose colors should be defined by nodes at a lower level in
3101 % The format of the ReduceImageColors method is:
3103 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3105 % A description of each parameter follows.
3107 % o image: the image.
3109 % o cube_info: A pointer to the Cube structure.
3113 static int MagickRealTypeCompare(const void *error_p,const void *error_q)
3119 p=(MagickRealType *) error_p;
3120 q=(MagickRealType *) error_q;
3123 if (fabs((double) (*q-*p)) <= MagickEpsilon)
3128 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3130 #define ReduceImageTag "Reduce/Image"
3141 cube_info->next_threshold=0.0;
3142 if ((cube_info->colors > cube_info->maximum_colors) &&
3143 (cube_info->nodes > 128))
3149 Enable rapid reduction of the number of unique colors.
3151 quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
3152 sizeof(*quantize_error));
3153 if (quantize_error != (MagickRealType *) NULL)
3155 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3157 qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
3158 MagickRealTypeCompare);
3159 cube_info->next_threshold=quantize_error[MagickMax((ssize_t)
3160 cube_info->nodes-110*(cube_info->maximum_colors+1)/100,0)];
3161 quantize_error=(MagickRealType *) RelinquishMagickMemory(
3165 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3167 cube_info->pruning_threshold=cube_info->next_threshold;
3168 cube_info->next_threshold=cube_info->root->quantize_error-1;
3169 cube_info->colors=0;
3170 Reduce(image,cube_info,cube_info->root);
3171 offset=(MagickOffsetType) span-cube_info->colors;
3172 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3173 cube_info->maximum_colors+1);
3174 if (proceed == MagickFalse)
3180 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3184 % R e m a p I m a g e %
3188 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3190 % RemapImage() replaces the colors of an image with a dither of the colors
3193 % The format of the RemapImage method is:
3195 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3196 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3198 % A description of each parameter follows:
3200 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3202 % o image: the image.
3204 % o remap_image: the reference image.
3206 % o exception: return any errors or warnings in this structure.
3209 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3210 Image *image,const Image *remap_image,ExceptionInfo *exception)
3219 Initialize color cube.
3221 assert(image != (Image *) NULL);
3222 assert(image->signature == MagickSignature);
3223 if (image->debug != MagickFalse)
3224 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3225 assert(remap_image != (Image *) NULL);
3226 assert(remap_image->signature == MagickSignature);
3227 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3228 quantize_info->number_colors);
3229 if (cube_info == (CubeInfo *) NULL)
3230 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3232 status=ClassifyImageColors(cube_info,remap_image,exception);
3233 if (status != MagickFalse)
3236 Classify image colors from the reference image.
3238 cube_info->quantize_info->number_colors=cube_info->colors;
3239 status=AssignImageColors(image,cube_info,exception);
3241 DestroyCubeInfo(cube_info);
3246 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3250 % R e m a p I m a g e s %
3254 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3256 % RemapImages() replaces the colors of a sequence of images with the
3257 % closest color from a reference image.
3259 % The format of the RemapImage method is:
3261 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3262 % Image *images,Image *remap_image,ExceptionInfo *exception)
3264 % A description of each parameter follows:
3266 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3268 % o images: the image sequence.
3270 % o remap_image: the reference image.
3272 % o exception: return any errors or warnings in this structure.
3275 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3276 Image *images,const Image *remap_image,ExceptionInfo *exception)
3287 assert(images != (Image *) NULL);
3288 assert(images->signature == MagickSignature);
3289 if (images->debug != MagickFalse)
3290 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3292 if (remap_image == (Image *) NULL)
3295 Create a global colormap for an image sequence.
3297 status=QuantizeImages(quantize_info,images,exception);
3301 Classify image colors from the reference image.
3303 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3304 quantize_info->number_colors);
3305 if (cube_info == (CubeInfo *) NULL)
3306 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3308 status=ClassifyImageColors(cube_info,remap_image,exception);
3309 if (status != MagickFalse)
3312 Classify image colors from the reference image.
3314 cube_info->quantize_info->number_colors=cube_info->colors;
3316 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3318 status=AssignImageColors(image,cube_info,exception);
3319 if (status == MagickFalse)
3323 DestroyCubeInfo(cube_info);
3328 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3332 % S e t G r a y s c a l e I m a g e %
3336 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3338 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3340 % The format of the SetGrayscaleImage method is:
3342 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3344 % A description of each parameter follows:
3346 % o image: The image.
3348 % o exception: return any errors or warnings in this structure.
3352 #if defined(__cplusplus) || defined(c_plusplus)
3356 static int IntensityCompare(const void *x,const void *y)
3365 color_1=(PixelInfo *) x;
3366 color_2=(PixelInfo *) y;
3367 intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
3368 GetPixelInfoIntensity(color_2));
3369 return((int) intensity);
3372 #if defined(__cplusplus) || defined(c_plusplus)
3376 static MagickBooleanType SetGrayscaleImage(Image *image,
3377 ExceptionInfo *exception)
3396 assert(image != (Image *) NULL);
3397 assert(image->signature == MagickSignature);
3398 if (image->type != GrayscaleType)
3399 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3400 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3401 sizeof(*colormap_index));
3402 if (colormap_index == (ssize_t *) NULL)
3403 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3405 if (image->storage_class != PseudoClass)
3407 for (i=0; i <= (ssize_t) MaxMap; i++)
3408 colormap_index[i]=(-1);
3409 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3410 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3414 image_view=AcquireAuthenticCacheView(image,exception);
3415 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3416 #pragma omp parallel for schedule(static,4) shared(status) \
3417 magick_threads(image,image,image->rows,1)
3419 for (y=0; y < (ssize_t) image->rows; y++)
3427 if (status == MagickFalse)
3429 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3431 if (q == (Quantum *) NULL)
3436 for (x=0; x < (ssize_t) image->columns; x++)
3441 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3442 if (colormap_index[intensity] < 0)
3444 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3445 #pragma omp critical (MagickCore_SetGrayscaleImage)
3447 if (colormap_index[intensity] < 0)
3449 colormap_index[intensity]=(ssize_t) image->colors;
3450 image->colormap[image->colors].red=(double)
3451 GetPixelRed(image,q);
3452 image->colormap[image->colors].green=(double)
3453 GetPixelGreen(image,q);
3454 image->colormap[image->colors].blue=(double)
3455 GetPixelBlue(image,q);
3459 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3460 q+=GetPixelChannels(image);
3462 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3465 image_view=DestroyCacheView(image_view);
3467 for (i=0; i < (ssize_t) image->colors; i++)
3468 image->colormap[i].alpha=(double) i;
3469 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3471 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3472 if (colormap == (PixelInfo *) NULL)
3473 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3476 colormap[j]=image->colormap[0];
3477 for (i=0; i < (ssize_t) image->colors; i++)
3479 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3482 colormap[j]=image->colormap[i];
3484 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3486 image->colors=(size_t) (j+1);
3487 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3488 image->colormap=colormap;
3490 image_view=AcquireAuthenticCacheView(image,exception);
3491 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3492 #pragma omp parallel for schedule(static,4) shared(status) \
3493 magick_threads(image,image,image->rows,1)
3495 for (y=0; y < (ssize_t) image->rows; y++)
3503 if (status == MagickFalse)
3505 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3506 if (q == (Quantum *) NULL)
3511 for (x=0; x < (ssize_t) image->columns; x++)
3513 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3514 GetPixelIndex(image,q))],q);
3515 q+=GetPixelChannels(image);
3517 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3520 image_view=DestroyCacheView(image_view);
3521 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3522 image->type=GrayscaleType;
3523 if (IsImageMonochrome(image,exception) != MagickFalse)
3524 image->type=BilevelType;