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 MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1930 ExceptionInfo *exception)
1944 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1945 return(FloydSteinbergDither(image,cube_info,exception));
1947 Distribute quantization error along a Hilbert curve.
1949 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1950 sizeof(*cube_info->error));
1953 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1954 for (depth=1; i != 0; depth++)
1956 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1958 cube_info->offset=0;
1959 cube_info->span=(MagickSizeType) image->columns*image->rows;
1960 image_view=AcquireAuthenticCacheView(image,exception);
1962 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1963 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1964 image_view=DestroyCacheView(image_view);
1969 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1973 + G e t C u b e I n f o %
1977 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1979 % GetCubeInfo() initialize the Cube data structure.
1981 % The format of the GetCubeInfo method is:
1983 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1984 % const size_t depth,const size_t maximum_colors)
1986 % A description of each parameter follows.
1988 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1990 % o depth: Normally, this integer value is zero or one. A zero or
1991 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1992 % A tree of this depth generally allows the best representation of the
1993 % reference image with the least amount of memory and the fastest
1994 % computational speed. In some cases, such as an image with low color
1995 % dispersion (a few number of colors), a value other than
1996 % Log4(number_colors) is required. To expand the color tree completely,
1999 % o maximum_colors: maximum colors.
2002 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2003 const size_t depth,const size_t maximum_colors)
2019 Initialize tree to describe color cube_info.
2021 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2022 if (cube_info == (CubeInfo *) NULL)
2023 return((CubeInfo *) NULL);
2024 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2025 cube_info->depth=depth;
2026 if (cube_info->depth > MaxTreeDepth)
2027 cube_info->depth=MaxTreeDepth;
2028 if (cube_info->depth < 2)
2030 cube_info->maximum_colors=maximum_colors;
2032 Initialize root node.
2034 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2035 if (cube_info->root == (NodeInfo *) NULL)
2036 return((CubeInfo *) NULL);
2037 cube_info->root->parent=cube_info->root;
2038 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2039 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2042 Initialize dither resources.
2044 length=(size_t) (1UL << (4*(8-CacheShift)));
2045 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2046 if (cube_info->memory_info == (MemoryInfo *) NULL)
2047 return((CubeInfo *) NULL);
2048 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2050 Initialize color cache.
2052 for (i=0; i < (ssize_t) length; i++)
2053 cube_info->cache[i]=(-1);
2055 Distribute weights along a curve of exponential decay.
2058 for (i=0; i < ErrorQueueLength; i++)
2060 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2061 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2064 Normalize the weighting factors.
2067 for (i=0; i < ErrorQueueLength; i++)
2068 weight+=cube_info->weights[i];
2070 for (i=0; i < ErrorQueueLength; i++)
2072 cube_info->weights[i]/=weight;
2073 sum+=cube_info->weights[i];
2075 cube_info->weights[0]+=1.0-sum;
2080 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2084 + G e t N o d e I n f o %
2088 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2090 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2091 % presets all fields to zero.
2093 % The format of the GetNodeInfo method is:
2095 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2096 % const size_t level,NodeInfo *parent)
2098 % A description of each parameter follows.
2100 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2102 % o id: Specifies the child number of the node.
2104 % o level: Specifies the level in the storage_class the node resides.
2107 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2108 const size_t level,NodeInfo *parent)
2113 if (cube_info->free_nodes == 0)
2119 Allocate a new queue of nodes.
2121 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2122 if (nodes == (Nodes *) NULL)
2123 return((NodeInfo *) NULL);
2124 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2125 sizeof(*nodes->nodes));
2126 if (nodes->nodes == (NodeInfo *) NULL)
2127 return((NodeInfo *) NULL);
2128 nodes->next=cube_info->node_queue;
2129 cube_info->node_queue=nodes;
2130 cube_info->next_node=nodes->nodes;
2131 cube_info->free_nodes=NodesInAList;
2134 cube_info->free_nodes--;
2135 node_info=cube_info->next_node++;
2136 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2137 node_info->parent=parent;
2139 node_info->level=level;
2144 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2148 % G e t I m a g e Q u a n t i z e E r r o r %
2152 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2154 % GetImageQuantizeError() measures the difference between the original
2155 % and quantized images. This difference is the total quantization error.
2156 % The error is computed by summing over all pixels in an image the distance
2157 % squared in RGB space between each reference pixel value and its quantized
2158 % value. These values are computed:
2160 % o mean_error_per_pixel: This value is the mean error for any single
2161 % pixel in the image.
2163 % o normalized_mean_square_error: This value is the normalized mean
2164 % quantization error for any single pixel in the image. This distance
2165 % measure is normalized to a range between 0 and 1. It is independent
2166 % of the range of red, green, and blue values in the image.
2168 % o normalized_maximum_square_error: Thsi value is the normalized
2169 % maximum quantization error for any single pixel in the image. This
2170 % distance measure is normalized to a range between 0 and 1. It is
2171 % independent of the range of red, green, and blue values in your image.
2173 % The format of the GetImageQuantizeError method is:
2175 % MagickBooleanType GetImageQuantizeError(Image *image,
2176 % ExceptionInfo *exception)
2178 % A description of each parameter follows.
2180 % o image: the image.
2182 % o exception: return any errors or warnings in this structure.
2185 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2186 ExceptionInfo *exception)
2198 mean_error_per_pixel;
2206 assert(image != (Image *) NULL);
2207 assert(image->signature == MagickSignature);
2208 if (image->debug != MagickFalse)
2209 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2210 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2211 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2212 if (image->storage_class == DirectClass)
2216 area=3.0*image->columns*image->rows;
2218 mean_error_per_pixel=0.0;
2220 image_view=AcquireVirtualCacheView(image,exception);
2221 for (y=0; y < (ssize_t) image->rows; y++)
2223 register const Quantum
2229 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2230 if (p == (const Quantum *) NULL)
2232 for (x=0; x < (ssize_t) image->columns; x++)
2234 index=1UL*GetPixelIndex(image,p);
2235 if (image->alpha_trait != UndefinedPixelTrait)
2237 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2238 beta=(double) (QuantumScale*image->colormap[index].alpha);
2240 distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
2241 image->colormap[index].red));
2242 mean_error_per_pixel+=distance;
2243 mean_error+=distance*distance;
2244 if (distance > maximum_error)
2245 maximum_error=distance;
2246 distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
2247 image->colormap[index].green));
2248 mean_error_per_pixel+=distance;
2249 mean_error+=distance*distance;
2250 if (distance > maximum_error)
2251 maximum_error=distance;
2252 distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta*
2253 image->colormap[index].blue));
2254 mean_error_per_pixel+=distance;
2255 mean_error+=distance*distance;
2256 if (distance > maximum_error)
2257 maximum_error=distance;
2258 p+=GetPixelChannels(image);
2261 image_view=DestroyCacheView(image_view);
2262 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2263 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2265 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2270 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2274 % G e t Q u a n t i z e I n f o %
2278 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2280 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2282 % The format of the GetQuantizeInfo method is:
2284 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2286 % A description of each parameter follows:
2288 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2291 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2293 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2294 assert(quantize_info != (QuantizeInfo *) NULL);
2295 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2296 quantize_info->number_colors=256;
2297 quantize_info->dither_method=RiemersmaDitherMethod;
2298 quantize_info->colorspace=UndefinedColorspace;
2299 quantize_info->measure_error=MagickFalse;
2300 quantize_info->signature=MagickSignature;
2304 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2308 % P o s t e r i z e I m a g e %
2312 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2314 % PosterizeImage() reduces the image to a limited number of colors for a
2317 % The format of the PosterizeImage method is:
2319 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2320 % const DitherMethod dither_method,ExceptionInfo *exception)
2322 % A description of each parameter follows:
2324 % o image: Specifies a pointer to an Image structure.
2326 % o levels: Number of color levels allowed in each channel. Very low values
2327 % (2, 3, or 4) have the most visible effect.
2329 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2330 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2332 % o exception: return any errors or warnings in this structure.
2336 static inline double MagickRound(double x)
2339 Round the fraction to nearest integer.
2341 if ((x-floor(x)) < (ceil(x)-x))
2346 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2347 const DitherMethod dither_method,ExceptionInfo *exception)
2349 #define PosterizeImageTag "Posterize/Image"
2350 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2351 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2371 assert(image != (Image *) NULL);
2372 assert(image->signature == MagickSignature);
2373 if (image->debug != MagickFalse)
2374 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2375 if (image->storage_class == PseudoClass)
2376 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2377 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2378 magick_threads(image,image,1,1)
2380 for (i=0; i < (ssize_t) image->colors; i++)
2385 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2386 image->colormap[i].red=(double)
2387 PosterizePixel(image->colormap[i].red);
2388 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2389 image->colormap[i].green=(double)
2390 PosterizePixel(image->colormap[i].green);
2391 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2392 image->colormap[i].blue=(double)
2393 PosterizePixel(image->colormap[i].blue);
2394 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2395 image->colormap[i].alpha=(double)
2396 PosterizePixel(image->colormap[i].alpha);
2403 image_view=AcquireAuthenticCacheView(image,exception);
2404 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2405 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2406 magick_threads(image,image,image->rows,1)
2408 for (y=0; y < (ssize_t) image->rows; y++)
2416 if (status == MagickFalse)
2418 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2419 if (q == (Quantum *) NULL)
2424 for (x=0; x < (ssize_t) image->columns; x++)
2426 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2427 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2428 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2429 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2430 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2431 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2432 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2433 (image->colorspace == CMYKColorspace))
2434 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2435 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2436 (image->alpha_trait != UndefinedPixelTrait))
2437 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2438 q+=GetPixelChannels(image);
2440 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2442 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2447 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2448 #pragma omp critical (MagickCore_PosterizeImage)
2450 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2452 if (proceed == MagickFalse)
2456 image_view=DestroyCacheView(image_view);
2457 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2458 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2459 levels,MaxColormapSize+1);
2460 quantize_info->dither_method=dither_method;
2461 quantize_info->tree_depth=MaxTreeDepth;
2462 status=QuantizeImage(quantize_info,image,exception);
2463 quantize_info=DestroyQuantizeInfo(quantize_info);
2468 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2472 + P r u n e C h i l d %
2476 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2478 % PruneChild() deletes the given node and merges its statistics into its
2481 % The format of the PruneSubtree method is:
2483 % PruneChild(const Image *image,CubeInfo *cube_info,
2484 % const NodeInfo *node_info)
2486 % A description of each parameter follows.
2488 % o image: the image.
2490 % o cube_info: A pointer to the Cube structure.
2492 % o node_info: pointer to node in color cube tree that is to be pruned.
2495 static void PruneChild(const Image *image,CubeInfo *cube_info,
2496 const NodeInfo *node_info)
2508 Traverse any children.
2510 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2511 for (i=0; i < (ssize_t) number_children; i++)
2512 if (node_info->child[i] != (NodeInfo *) NULL)
2513 PruneChild(image,cube_info,node_info->child[i]);
2515 Merge color statistics into parent.
2517 parent=node_info->parent;
2518 parent->number_unique+=node_info->number_unique;
2519 parent->total_color.red+=node_info->total_color.red;
2520 parent->total_color.green+=node_info->total_color.green;
2521 parent->total_color.blue+=node_info->total_color.blue;
2522 parent->total_color.alpha+=node_info->total_color.alpha;
2523 parent->child[node_info->id]=(NodeInfo *) NULL;
2528 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2532 + P r u n e L e v e l %
2536 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2538 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2539 % their color statistics into their parent node.
2541 % The format of the PruneLevel method is:
2543 % PruneLevel(const Image *image,CubeInfo *cube_info,
2544 % const NodeInfo *node_info)
2546 % A description of each parameter follows.
2548 % o image: the image.
2550 % o cube_info: A pointer to the Cube structure.
2552 % o node_info: pointer to node in color cube tree that is to be pruned.
2555 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2556 const NodeInfo *node_info)
2565 Traverse any children.
2567 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2568 for (i=0; i < (ssize_t) number_children; i++)
2569 if (node_info->child[i] != (NodeInfo *) NULL)
2570 PruneLevel(image,cube_info,node_info->child[i]);
2571 if (node_info->level == cube_info->depth)
2572 PruneChild(image,cube_info,node_info);
2576 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2580 + P r u n e T o C u b e D e p t h %
2584 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2586 % PruneToCubeDepth() deletes any nodes at a depth greater than
2587 % cube_info->depth while merging their color statistics into their parent
2590 % The format of the PruneToCubeDepth method is:
2592 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2593 % const NodeInfo *node_info)
2595 % A description of each parameter follows.
2597 % o cube_info: A pointer to the Cube structure.
2599 % o node_info: pointer to node in color cube tree that is to be pruned.
2602 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2603 const NodeInfo *node_info)
2612 Traverse any children.
2614 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2615 for (i=0; i < (ssize_t) number_children; i++)
2616 if (node_info->child[i] != (NodeInfo *) NULL)
2617 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2618 if (node_info->level > cube_info->depth)
2619 PruneChild(image,cube_info,node_info);
2623 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2627 % Q u a n t i z e I m a g e %
2631 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2633 % QuantizeImage() analyzes the colors within a reference image and chooses a
2634 % fixed number of colors to represent the image. The goal of the algorithm
2635 % is to minimize the color difference between the input and output image while
2636 % minimizing the processing time.
2638 % The format of the QuantizeImage method is:
2640 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2641 % Image *image,ExceptionInfo *exception)
2643 % A description of each parameter follows:
2645 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2647 % o image: the image.
2649 % o exception: return any errors or warnings in this structure.
2653 static MagickBooleanType DirectToColormapImage(Image *image,
2654 ExceptionInfo *exception)
2672 number_colors=(size_t) (image->columns*image->rows);
2673 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2674 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2676 if (image->colors != number_colors)
2677 return(MagickFalse);
2679 image_view=AcquireAuthenticCacheView(image,exception);
2680 for (y=0; y < (ssize_t) image->rows; y++)
2691 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2692 if (q == (Quantum *) NULL)
2694 for (x=0; x < (ssize_t) image->columns; x++)
2696 image->colormap[i].red=(double) GetPixelRed(image,q);
2697 image->colormap[i].green=(double) GetPixelGreen(image,q);
2698 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2699 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2700 SetPixelIndex(image,(Quantum) i,q);
2702 q+=GetPixelChannels(image);
2704 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2706 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2708 if (proceed == MagickFalse)
2711 image_view=DestroyCacheView(image_view);
2715 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2716 Image *image,ExceptionInfo *exception)
2728 assert(quantize_info != (const QuantizeInfo *) NULL);
2729 assert(quantize_info->signature == MagickSignature);
2730 assert(image != (Image *) NULL);
2731 assert(image->signature == MagickSignature);
2732 if (image->debug != MagickFalse)
2733 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2734 maximum_colors=quantize_info->number_colors;
2735 if (maximum_colors == 0)
2736 maximum_colors=MaxColormapSize;
2737 if (maximum_colors > MaxColormapSize)
2738 maximum_colors=MaxColormapSize;
2739 if (image->alpha_trait == UndefinedPixelTrait)
2741 if ((image->columns*image->rows) <= maximum_colors)
2742 (void) DirectToColormapImage(image,exception);
2743 if (IsImageGray(image,exception) != MagickFalse)
2744 (void) SetGrayscaleImage(image,exception);
2746 if ((image->storage_class == PseudoClass) &&
2747 (image->colors <= maximum_colors))
2749 depth=quantize_info->tree_depth;
2756 Depth of color tree is: Log4(colormap size)+2.
2758 colors=maximum_colors;
2759 for (depth=1; colors != 0; depth++)
2761 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2763 if ((image->alpha_trait != UndefinedPixelTrait) && (depth > 5))
2765 if (IsImageGray(image,exception) != MagickFalse)
2769 Initialize color cube.
2771 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2772 if (cube_info == (CubeInfo *) NULL)
2773 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2775 status=ClassifyImageColors(cube_info,image,exception);
2776 if (status != MagickFalse)
2779 Reduce the number of colors in the image.
2781 ReduceImageColors(image,cube_info);
2782 status=AssignImageColors(image,cube_info,exception);
2784 DestroyCubeInfo(cube_info);
2789 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2793 % Q u a n t i z e I m a g e s %
2797 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2799 % QuantizeImages() analyzes the colors within a set of reference images and
2800 % chooses a fixed number of colors to represent the set. The goal of the
2801 % algorithm is to minimize the color difference between the input and output
2802 % images while minimizing the processing time.
2804 % The format of the QuantizeImages method is:
2806 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2807 % Image *images,ExceptionInfo *exception)
2809 % A description of each parameter follows:
2811 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2813 % o images: Specifies a pointer to a list of Image structures.
2815 % o exception: return any errors or warnings in this structure.
2818 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2819 Image *images,ExceptionInfo *exception)
2831 MagickProgressMonitor
2842 assert(quantize_info != (const QuantizeInfo *) NULL);
2843 assert(quantize_info->signature == MagickSignature);
2844 assert(images != (Image *) NULL);
2845 assert(images->signature == MagickSignature);
2846 if (images->debug != MagickFalse)
2847 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2848 if (GetNextImageInList(images) == (Image *) NULL)
2851 Handle a single image with QuantizeImage.
2853 status=QuantizeImage(quantize_info,images,exception);
2857 maximum_colors=quantize_info->number_colors;
2858 if (maximum_colors == 0)
2859 maximum_colors=MaxColormapSize;
2860 if (maximum_colors > MaxColormapSize)
2861 maximum_colors=MaxColormapSize;
2862 depth=quantize_info->tree_depth;
2869 Depth of color tree is: Log4(colormap size)+2.
2871 colors=maximum_colors;
2872 for (depth=1; colors != 0; depth++)
2874 if (quantize_info->dither_method != NoDitherMethod)
2878 Initialize color cube.
2880 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2881 if (cube_info == (CubeInfo *) NULL)
2883 (void) ThrowMagickException(exception,GetMagickModule(),
2884 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2885 return(MagickFalse);
2887 number_images=GetImageListLength(images);
2889 for (i=0; image != (Image *) NULL; i++)
2891 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2892 image->client_data);
2893 status=ClassifyImageColors(cube_info,image,exception);
2894 if (status == MagickFalse)
2896 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2897 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2899 if (proceed == MagickFalse)
2901 image=GetNextImageInList(image);
2903 if (status != MagickFalse)
2906 Reduce the number of colors in an image sequence.
2908 ReduceImageColors(images,cube_info);
2910 for (i=0; image != (Image *) NULL; i++)
2912 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2913 NULL,image->client_data);
2914 status=AssignImageColors(image,cube_info,exception);
2915 if (status == MagickFalse)
2917 (void) SetImageProgressMonitor(image,progress_monitor,
2918 image->client_data);
2919 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2921 if (proceed == MagickFalse)
2923 image=GetNextImageInList(image);
2926 DestroyCubeInfo(cube_info);
2931 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2935 + Q u a n t i z e E r r o r F l a t t e n %
2939 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2941 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2942 % error into a sorted 1D array. This accelerates the color reduction process.
2944 % Contributed by Yoya.
2946 % The format of the QuantizeImages method is:
2948 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2949 % const NodeInfo *node_info,const ssize_t offset,
2950 % MagickRealType *quantize_error)
2952 % A description of each parameter follows.
2954 % o image: the image.
2956 % o cube_info: A pointer to the Cube structure.
2958 % o node_info: pointer to node in color cube tree that is current pointer.
2960 % o offset: quantize error offset.
2962 % o quantize_error: the quantization error vector.
2965 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2966 const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
2975 if (offset >= (ssize_t) cube_info->nodes)
2977 quantize_error[offset]=node_info->quantize_error;
2979 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2980 for (i=0; i < (ssize_t) number_children ; i++)
2981 if (node_info->child[i] != (NodeInfo *) NULL)
2982 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
2988 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2996 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2998 % Reduce() traverses the color cube tree and prunes any node whose
2999 % quantization error falls below a particular threshold.
3001 % The format of the Reduce method is:
3003 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3005 % A description of each parameter follows.
3007 % o image: the image.
3009 % o cube_info: A pointer to the Cube structure.
3011 % o node_info: pointer to node in color cube tree that is to be pruned.
3014 static void Reduce(const Image *image,CubeInfo *cube_info,
3015 const NodeInfo *node_info)
3024 Traverse any children.
3026 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3027 for (i=0; i < (ssize_t) number_children; i++)
3028 if (node_info->child[i] != (NodeInfo *) NULL)
3029 Reduce(image,cube_info,node_info->child[i]);
3030 if (node_info->quantize_error <= cube_info->pruning_threshold)
3031 PruneChild(image,cube_info,node_info);
3035 Find minimum pruning threshold.
3037 if (node_info->number_unique > 0)
3038 cube_info->colors++;
3039 if (node_info->quantize_error < cube_info->next_threshold)
3040 cube_info->next_threshold=node_info->quantize_error;
3045 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3049 + R e d u c e I m a g e C o l o r s %
3053 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3055 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3056 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3057 % in the output image. On any given iteration over the tree, it selects
3058 % those nodes whose E value is minimal for pruning and merges their
3059 % color statistics upward. It uses a pruning threshold, Ep, to govern
3060 % node selection as follows:
3063 % while number of nodes with (n2 > 0) > required maximum number of colors
3064 % prune all nodes such that E <= Ep
3065 % Set Ep to minimum E in remaining nodes
3067 % This has the effect of minimizing any quantization error when merging
3068 % two nodes together.
3070 % When a node to be pruned has offspring, the pruning procedure invokes
3071 % itself recursively in order to prune the tree from the leaves upward.
3072 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3073 % corresponding data in that node's parent. This retains the pruned
3074 % node's color characteristics for later averaging.
3076 % For each node, n2 pixels exist for which that node represents the
3077 % smallest volume in RGB space containing those pixel's colors. When n2
3078 % > 0 the node will uniquely define a color in the output image. At the
3079 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3080 % the tree which represent colors present in the input image.
3082 % The other pixel count, n1, indicates the total number of colors
3083 % within the cubic volume which the node represents. This includes n1 -
3084 % n2 pixels whose colors should be defined by nodes at a lower level in
3087 % The format of the ReduceImageColors method is:
3089 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3091 % A description of each parameter follows.
3093 % o image: the image.
3095 % o cube_info: A pointer to the Cube structure.
3099 static int MagickRealTypeCompare(const void *error_p,const void *error_q)
3105 p=(MagickRealType *) error_p;
3106 q=(MagickRealType *) error_q;
3109 if (fabs((double) (*q-*p)) <= MagickEpsilon)
3114 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3116 #define ReduceImageTag "Reduce/Image"
3127 cube_info->next_threshold=0.0;
3128 if ((cube_info->colors > cube_info->maximum_colors) &&
3129 (cube_info->nodes > 128))
3135 Enable rapid reduction of the number of unique colors.
3137 quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
3138 sizeof(*quantize_error));
3139 if (quantize_error != (MagickRealType *) NULL)
3141 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3143 qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
3144 MagickRealTypeCompare);
3145 cube_info->next_threshold=quantize_error[MagickMax((ssize_t)
3146 cube_info->nodes-110*(cube_info->maximum_colors+1)/100,0)];
3147 quantize_error=(MagickRealType *) RelinquishMagickMemory(
3151 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3153 cube_info->pruning_threshold=cube_info->next_threshold;
3154 cube_info->next_threshold=cube_info->root->quantize_error-1;
3155 cube_info->colors=0;
3156 Reduce(image,cube_info,cube_info->root);
3157 offset=(MagickOffsetType) span-cube_info->colors;
3158 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3159 cube_info->maximum_colors+1);
3160 if (proceed == MagickFalse)
3166 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3170 % R e m a p I m a g e %
3174 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3176 % RemapImage() replaces the colors of an image with a dither of the colors
3179 % The format of the RemapImage method is:
3181 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3182 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3184 % A description of each parameter follows:
3186 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3188 % o image: the image.
3190 % o remap_image: the reference image.
3192 % o exception: return any errors or warnings in this structure.
3195 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3196 Image *image,const Image *remap_image,ExceptionInfo *exception)
3205 Initialize color cube.
3207 assert(image != (Image *) NULL);
3208 assert(image->signature == MagickSignature);
3209 if (image->debug != MagickFalse)
3210 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3211 assert(remap_image != (Image *) NULL);
3212 assert(remap_image->signature == MagickSignature);
3213 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3214 quantize_info->number_colors);
3215 if (cube_info == (CubeInfo *) NULL)
3216 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3218 status=ClassifyImageColors(cube_info,remap_image,exception);
3219 if (status != MagickFalse)
3222 Classify image colors from the reference image.
3224 cube_info->quantize_info->number_colors=cube_info->colors;
3225 status=AssignImageColors(image,cube_info,exception);
3227 DestroyCubeInfo(cube_info);
3232 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3236 % R e m a p I m a g e s %
3240 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3242 % RemapImages() replaces the colors of a sequence of images with the
3243 % closest color from a reference image.
3245 % The format of the RemapImage method is:
3247 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3248 % Image *images,Image *remap_image,ExceptionInfo *exception)
3250 % A description of each parameter follows:
3252 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3254 % o images: the image sequence.
3256 % o remap_image: the reference image.
3258 % o exception: return any errors or warnings in this structure.
3261 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3262 Image *images,const Image *remap_image,ExceptionInfo *exception)
3273 assert(images != (Image *) NULL);
3274 assert(images->signature == MagickSignature);
3275 if (images->debug != MagickFalse)
3276 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3278 if (remap_image == (Image *) NULL)
3281 Create a global colormap for an image sequence.
3283 status=QuantizeImages(quantize_info,images,exception);
3287 Classify image colors from the reference image.
3289 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3290 quantize_info->number_colors);
3291 if (cube_info == (CubeInfo *) NULL)
3292 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3294 status=ClassifyImageColors(cube_info,remap_image,exception);
3295 if (status != MagickFalse)
3298 Classify image colors from the reference image.
3300 cube_info->quantize_info->number_colors=cube_info->colors;
3302 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3304 status=AssignImageColors(image,cube_info,exception);
3305 if (status == MagickFalse)
3309 DestroyCubeInfo(cube_info);
3314 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3318 % S e t G r a y s c a l e I m a g e %
3322 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3324 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3326 % The format of the SetGrayscaleImage method is:
3328 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3330 % A description of each parameter follows:
3332 % o image: The image.
3334 % o exception: return any errors or warnings in this structure.
3338 #if defined(__cplusplus) || defined(c_plusplus)
3342 static int IntensityCompare(const void *x,const void *y)
3351 color_1=(PixelInfo *) x;
3352 color_2=(PixelInfo *) y;
3353 intensity=(ssize_t) (GetPixelInfoIntensity((const Image *) NULL,color_1)-
3354 (ssize_t) GetPixelInfoIntensity((const Image *) NULL,color_2));
3355 return((int) intensity);
3358 #if defined(__cplusplus) || defined(c_plusplus)
3362 static MagickBooleanType SetGrayscaleImage(Image *image,
3363 ExceptionInfo *exception)
3382 assert(image != (Image *) NULL);
3383 assert(image->signature == MagickSignature);
3384 if (image->type != GrayscaleType)
3385 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3386 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3387 sizeof(*colormap_index));
3388 if (colormap_index == (ssize_t *) NULL)
3389 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3391 if (image->storage_class != PseudoClass)
3393 for (i=0; i <= (ssize_t) MaxMap; i++)
3394 colormap_index[i]=(-1);
3395 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3396 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3400 image_view=AcquireAuthenticCacheView(image,exception);
3401 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3402 #pragma omp parallel for schedule(static,4) shared(status) \
3403 magick_threads(image,image,image->rows,1)
3405 for (y=0; y < (ssize_t) image->rows; y++)
3413 if (status == MagickFalse)
3415 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3417 if (q == (Quantum *) NULL)
3422 for (x=0; x < (ssize_t) image->columns; x++)
3427 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3428 if (colormap_index[intensity] < 0)
3430 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3431 #pragma omp critical (MagickCore_SetGrayscaleImage)
3433 if (colormap_index[intensity] < 0)
3435 colormap_index[intensity]=(ssize_t) image->colors;
3436 image->colormap[image->colors].red=(double)
3437 GetPixelRed(image,q);
3438 image->colormap[image->colors].green=(double)
3439 GetPixelGreen(image,q);
3440 image->colormap[image->colors].blue=(double)
3441 GetPixelBlue(image,q);
3445 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3446 q+=GetPixelChannels(image);
3448 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3451 image_view=DestroyCacheView(image_view);
3453 for (i=0; i < (ssize_t) image->colors; i++)
3454 image->colormap[i].alpha=(double) i;
3455 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3457 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3458 if (colormap == (PixelInfo *) NULL)
3459 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3462 colormap[j]=image->colormap[0];
3463 for (i=0; i < (ssize_t) image->colors; i++)
3465 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3468 colormap[j]=image->colormap[i];
3470 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3472 image->colors=(size_t) (j+1);
3473 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3474 image->colormap=colormap;
3476 image_view=AcquireAuthenticCacheView(image,exception);
3477 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3478 #pragma omp parallel for schedule(static,4) shared(status) \
3479 magick_threads(image,image,image->rows,1)
3481 for (y=0; y < (ssize_t) image->rows; y++)
3489 if (status == MagickFalse)
3491 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3492 if (q == (Quantum *) NULL)
3497 for (x=0; x < (ssize_t) image->columns; x++)
3499 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3500 GetPixelIndex(image,q))],q);
3501 q+=GetPixelChannels(image);
3503 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3506 image_view=DestroyCacheView(image_view);
3507 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3508 image->type=GrayscaleType;
3509 if (IsImageMonochrome(image,exception) != MagickFalse)
3510 image->type=BilevelType;