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-2014 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 (cube_info->quantize_info->dither_method != NoDitherMethod))
538 (void) DitherImage(image,cube_info,exception);
548 image_view=AcquireAuthenticCacheView(image,exception);
549 #if defined(MAGICKCORE_OPENMP_SUPPORT)
550 #pragma omp parallel for schedule(static,4) shared(status) \
551 magick_threads(image,image,image->rows,1)
553 for (y=0; y < (ssize_t) image->rows; y++)
567 if (status == MagickFalse)
569 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
571 if (q == (Quantum *) NULL)
577 for (x=0; x < (ssize_t) image->columns; x+=count)
582 register const NodeInfo
593 Identify the deepest node containing the pixel's color.
595 for (count=1; (x+count) < (ssize_t) image->columns; count++)
600 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
601 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
604 AssociateAlphaPixel(image,&cube,q,&pixel);
606 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
608 id=ColorToNodeId(&cube,&pixel,index);
609 if (node_info->child[id] == (NodeInfo *) NULL)
611 node_info=node_info->child[id];
614 Find closest color among siblings and their children.
617 cube.distance=(double) (4.0*(QuantumRange+1.0)*
618 (QuantumRange+1.0)+1.0);
619 ClosestColor(image,&cube,node_info->parent);
620 index=cube.color_number;
621 for (i=0; i < (ssize_t) count; i++)
623 if (image->storage_class == PseudoClass)
624 SetPixelIndex(image,(Quantum) index,q);
625 if (cube.quantize_info->measure_error == MagickFalse)
627 SetPixelRed(image,ClampToQuantum(
628 image->colormap[index].red),q);
629 SetPixelGreen(image,ClampToQuantum(
630 image->colormap[index].green),q);
631 SetPixelBlue(image,ClampToQuantum(
632 image->colormap[index].blue),q);
633 if (cube.associate_alpha != MagickFalse)
634 SetPixelAlpha(image,ClampToQuantum(
635 image->colormap[index].alpha),q);
637 q+=GetPixelChannels(image);
640 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
642 if (image->progress_monitor != (MagickProgressMonitor) NULL)
647 #if defined(MAGICKCORE_OPENMP_SUPPORT)
648 #pragma omp critical (MagickCore_AssignImageColors)
650 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
652 if (proceed == MagickFalse)
656 image_view=DestroyCacheView(image_view);
658 if (cube_info->quantize_info->measure_error != MagickFalse)
659 (void) GetImageQuantizeError(image,exception);
660 if ((cube_info->quantize_info->number_colors == 2) &&
661 (cube_info->quantize_info->colorspace == GRAYColorspace))
676 for (i=0; i < (ssize_t) image->colors; i++)
678 intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
686 (void) SyncImage(image,exception);
687 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
688 (cube_info->quantize_info->colorspace != CMYKColorspace))
689 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
694 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
698 + C l a s s i f y I m a g e C o l o r s %
702 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
704 % ClassifyImageColors() begins by initializing a color description tree
705 % of sufficient depth to represent each possible input color in a leaf.
706 % However, it is impractical to generate a fully-formed color
707 % description tree in the storage_class phase for realistic values of
708 % Cmax. If colors components in the input image are quantized to k-bit
709 % precision, so that Cmax= 2k-1, the tree would need k levels below the
710 % root node to allow representing each possible input color in a leaf.
711 % This becomes prohibitive because the tree's total number of nodes is
714 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
715 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
716 % Initializes data structures for nodes only as they are needed; (2)
717 % Chooses a maximum depth for the tree as a function of the desired
718 % number of colors in the output image (currently log2(colormap size)).
720 % For each pixel in the input image, storage_class scans downward from
721 % the root of the color description tree. At each level of the tree it
722 % identifies the single node which represents a cube in RGB space
723 % containing It updates the following data for each such node:
725 % n1 : Number of pixels whose color is contained in the RGB cube
726 % which this node represents;
728 % n2 : Number of pixels whose color is not represented in a node at
729 % lower depth in the tree; initially, n2 = 0 for all nodes except
730 % leaves of the tree.
732 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
733 % all pixels not classified at a lower depth. The combination of
734 % these sums and n2 will ultimately characterize the mean color of a
735 % set of pixels represented by this node.
737 % E: the distance squared in RGB space between each pixel contained
738 % within a node and the nodes' center. This represents the quantization
741 % The format of the ClassifyImageColors() method is:
743 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
744 % const Image *image,ExceptionInfo *exception)
746 % A description of each parameter follows.
748 % o cube_info: A pointer to the Cube structure.
750 % o image: the image.
754 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
759 associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
761 if ((cube_info->quantize_info->number_colors == 2) &&
762 (cube_info->quantize_info->colorspace == GRAYColorspace))
763 associate_alpha=MagickFalse;
764 cube_info->associate_alpha=associate_alpha;
767 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
768 const Image *image,ExceptionInfo *exception)
770 #define ClassifyImageTag "Classify/Image"
800 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
802 SetAssociatedAlpha(image,cube_info);
803 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
804 (cube_info->quantize_info->colorspace != CMYKColorspace))
805 (void) TransformImageColorspace((Image *) image,
806 cube_info->quantize_info->colorspace,exception);
808 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
809 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
810 midpoint.red=(double) QuantumRange/2.0;
811 midpoint.green=(double) QuantumRange/2.0;
812 midpoint.blue=(double) QuantumRange/2.0;
813 midpoint.alpha=(double) QuantumRange/2.0;
815 image_view=AcquireVirtualCacheView(image,exception);
816 for (y=0; y < (ssize_t) image->rows; y++)
818 register const Quantum
824 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
825 if (p == (const Quantum *) NULL)
827 if (cube_info->nodes > MaxNodes)
830 Prune one level if the color tree is too large.
832 PruneLevel(image,cube_info,cube_info->root);
835 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
838 Start at the root and descend the color cube tree.
840 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
845 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
846 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
849 AssociateAlphaPixel(image,cube_info,p,&pixel);
850 index=MaxTreeDepth-1;
851 bisect=((double) QuantumRange+1.0)/2.0;
853 node_info=cube_info->root;
854 for (level=1; level <= MaxTreeDepth; level++)
857 id=ColorToNodeId(cube_info,&pixel,index);
858 mid.red+=(id & 1) != 0 ? bisect : -bisect;
859 mid.green+=(id & 2) != 0 ? bisect : -bisect;
860 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
861 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
862 if (node_info->child[id] == (NodeInfo *) NULL)
865 Set colors of new node to contain pixel.
867 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
868 if (node_info->child[id] == (NodeInfo *) NULL)
870 (void) ThrowMagickException(exception,GetMagickModule(),
871 ResourceLimitError,"MemoryAllocationFailed","`%s'",
875 if (level == MaxTreeDepth)
879 Approximate the quantization error represented by this node.
881 node_info=node_info->child[id];
882 error.red=QuantumScale*(pixel.red-mid.red);
883 error.green=QuantumScale*(pixel.green-mid.green);
884 error.blue=QuantumScale*(pixel.blue-mid.blue);
885 if (cube_info->associate_alpha != MagickFalse)
886 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
887 node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
888 error.green*error.green+error.blue*error.blue+
889 error.alpha*error.alpha));
890 cube_info->root->quantize_error+=node_info->quantize_error;
894 Sum RGB for this leaf for later derivation of the mean cube color.
896 node_info->number_unique+=count;
897 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
898 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
899 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
900 if (cube_info->associate_alpha != MagickFalse)
901 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
903 p+=count*GetPixelChannels(image);
905 if (cube_info->colors > cube_info->maximum_colors)
907 PruneToCubeDepth(image,cube_info,cube_info->root);
910 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
912 if (proceed == MagickFalse)
915 for (y++; y < (ssize_t) image->rows; y++)
917 register const Quantum
923 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
924 if (p == (const Quantum *) NULL)
926 if (cube_info->nodes > MaxNodes)
929 Prune one level if the color tree is too large.
931 PruneLevel(image,cube_info,cube_info->root);
934 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
937 Start at the root and descend the color cube tree.
939 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
944 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
945 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
948 AssociateAlphaPixel(image,cube_info,p,&pixel);
949 index=MaxTreeDepth-1;
950 bisect=((double) QuantumRange+1.0)/2.0;
952 node_info=cube_info->root;
953 for (level=1; level <= cube_info->depth; level++)
956 id=ColorToNodeId(cube_info,&pixel,index);
957 mid.red+=(id & 1) != 0 ? bisect : -bisect;
958 mid.green+=(id & 2) != 0 ? bisect : -bisect;
959 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
960 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
961 if (node_info->child[id] == (NodeInfo *) NULL)
964 Set colors of new node to contain pixel.
966 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
967 if (node_info->child[id] == (NodeInfo *) NULL)
969 (void) ThrowMagickException(exception,GetMagickModule(),
970 ResourceLimitError,"MemoryAllocationFailed","%s",
974 if (level == cube_info->depth)
978 Approximate the quantization error represented by this node.
980 node_info=node_info->child[id];
981 error.red=QuantumScale*(pixel.red-mid.red);
982 error.green=QuantumScale*(pixel.green-mid.green);
983 error.blue=QuantumScale*(pixel.blue-mid.blue);
984 if (cube_info->associate_alpha != MagickFalse)
985 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
986 node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
987 error.green*error.green+error.blue*error.blue+
988 error.alpha*error.alpha));
989 cube_info->root->quantize_error+=node_info->quantize_error;
993 Sum RGB for this leaf for later derivation of the mean cube color.
995 node_info->number_unique+=count;
996 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
997 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
998 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
999 if (cube_info->associate_alpha != MagickFalse)
1000 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
1002 p+=count*GetPixelChannels(image);
1004 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1006 if (proceed == MagickFalse)
1009 image_view=DestroyCacheView(image_view);
1010 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1011 (cube_info->quantize_info->colorspace != CMYKColorspace))
1012 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1013 return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1021 % C l o n e Q u a n t i z e I n f o %
1025 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1027 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1028 % or if quantize info is NULL, a new one.
1030 % The format of the CloneQuantizeInfo method is:
1032 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1034 % A description of each parameter follows:
1036 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1037 % quantize info, or if image info is NULL a new one.
1039 % o quantize_info: a structure of type info.
1042 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1047 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1048 if (clone_info == (QuantizeInfo *) NULL)
1049 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1050 GetQuantizeInfo(clone_info);
1051 if (quantize_info == (QuantizeInfo *) NULL)
1053 clone_info->number_colors=quantize_info->number_colors;
1054 clone_info->tree_depth=quantize_info->tree_depth;
1055 clone_info->dither_method=quantize_info->dither_method;
1056 clone_info->colorspace=quantize_info->colorspace;
1057 clone_info->measure_error=quantize_info->measure_error;
1062 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1066 + C l o s e s t C o l o r %
1070 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1072 % ClosestColor() traverses the color cube tree at a particular node and
1073 % determines which colormap entry best represents the input color.
1075 % The format of the ClosestColor method is:
1077 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1078 % const NodeInfo *node_info)
1080 % A description of each parameter follows.
1082 % o image: the image.
1084 % o cube_info: A pointer to the Cube structure.
1086 % o node_info: the address of a structure of type NodeInfo which points to a
1087 % node in the color cube tree that is to be pruned.
1090 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1091 const NodeInfo *node_info)
1100 Traverse any children.
1102 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1103 for (i=0; i < (ssize_t) number_children; i++)
1104 if (node_info->child[i] != (NodeInfo *) NULL)
1105 ClosestColor(image,cube_info,node_info->child[i]);
1106 if (node_info->number_unique != 0)
1119 register RealPixelInfo
1123 Determine if this color is "closest".
1125 p=image->colormap+node_info->color_number;
1126 q=(&cube_info->target);
1129 if (cube_info->associate_alpha != MagickFalse)
1131 alpha=(double) (QuantumScale*p->alpha);
1132 beta=(double) (QuantumScale*q->alpha);
1134 pixel=alpha*p->red-beta*q->red;
1135 distance=pixel*pixel;
1136 if (distance <= cube_info->distance)
1138 pixel=alpha*p->green-beta*q->green;
1139 distance+=pixel*pixel;
1140 if (distance <= cube_info->distance)
1142 pixel=alpha*p->blue-beta*q->blue;
1143 distance+=pixel*pixel;
1144 if (distance <= cube_info->distance)
1147 distance+=pixel*pixel;
1148 if (distance <= cube_info->distance)
1150 cube_info->distance=distance;
1151 cube_info->color_number=node_info->color_number;
1160 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1164 % C o m p r e s s I m a g e C o l o r m a p %
1168 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1170 % CompressImageColormap() compresses an image colormap by removing any
1171 % duplicate or unused color entries.
1173 % The format of the CompressImageColormap method is:
1175 % MagickBooleanType CompressImageColormap(Image *image,
1176 % ExceptionInfo *exception)
1178 % A description of each parameter follows:
1180 % o image: the image.
1182 % o exception: return any errors or warnings in this structure.
1185 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1186 ExceptionInfo *exception)
1191 assert(image != (Image *) NULL);
1192 assert(image->signature == MagickSignature);
1193 if (image->debug != MagickFalse)
1194 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1195 if (IsPaletteImage(image,exception) == MagickFalse)
1196 return(MagickFalse);
1197 GetQuantizeInfo(&quantize_info);
1198 quantize_info.number_colors=image->colors;
1199 quantize_info.tree_depth=MaxTreeDepth;
1200 return(QuantizeImage(&quantize_info,image,exception));
1204 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1208 + D e f i n e I m a g e C o l o r m a p %
1212 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1214 % DefineImageColormap() traverses the color cube tree and notes each colormap
1215 % entry. A colormap entry is any node in the color cube tree where the
1216 % of unique colors is not zero. DefineImageColormap() returns the number of
1217 % colors in the image colormap.
1219 % The format of the DefineImageColormap method is:
1221 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1222 % NodeInfo *node_info)
1224 % A description of each parameter follows.
1226 % o image: the image.
1228 % o cube_info: A pointer to the Cube structure.
1230 % o node_info: the address of a structure of type NodeInfo which points to a
1231 % node in the color cube tree that is to be pruned.
1234 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1235 NodeInfo *node_info)
1244 Traverse any children.
1246 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1247 for (i=0; i < (ssize_t) number_children; i++)
1248 if (node_info->child[i] != (NodeInfo *) NULL)
1249 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1250 if (node_info->number_unique != 0)
1259 Colormap entry is defined by the mean color in this cube.
1261 q=image->colormap+image->colors;
1262 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1263 alpha=PerceptibleReciprocal(alpha);
1264 if (cube_info->associate_alpha == MagickFalse)
1266 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1267 node_info->total_color.red);
1268 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1269 node_info->total_color.green);
1270 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1271 node_info->total_color.blue);
1272 q->alpha=(double) OpaqueAlpha;
1279 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1280 q->alpha=(double) ClampToQuantum((opacity));
1281 if (q->alpha == OpaqueAlpha)
1283 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1284 node_info->total_color.red);
1285 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1286 node_info->total_color.green);
1287 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1288 node_info->total_color.blue);
1295 gamma=(double) (QuantumScale*q->alpha);
1296 gamma=PerceptibleReciprocal(gamma);
1297 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1298 node_info->total_color.red);
1299 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1300 node_info->total_color.green);
1301 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1302 node_info->total_color.blue);
1303 if (node_info->number_unique > cube_info->transparent_pixels)
1305 cube_info->transparent_pixels=node_info->number_unique;
1306 cube_info->transparent_index=(ssize_t) image->colors;
1310 node_info->color_number=image->colors++;
1312 return(image->colors);
1316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1320 + D e s t r o y C u b e I n f o %
1324 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1326 % DestroyCubeInfo() deallocates memory associated with an image.
1328 % The format of the DestroyCubeInfo method is:
1330 % DestroyCubeInfo(CubeInfo *cube_info)
1332 % A description of each parameter follows:
1334 % o cube_info: the address of a structure of type CubeInfo.
1337 static void DestroyCubeInfo(CubeInfo *cube_info)
1343 Release color cube tree storage.
1347 nodes=cube_info->node_queue->next;
1348 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1349 cube_info->node_queue->nodes);
1350 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1351 cube_info->node_queue);
1352 cube_info->node_queue=nodes;
1353 } while (cube_info->node_queue != (Nodes *) NULL);
1354 if (cube_info->memory_info != (MemoryInfo *) NULL)
1355 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1356 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1357 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1361 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1365 % D e s t r o y Q u a n t i z e I n f o %
1369 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1371 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1374 % The format of the DestroyQuantizeInfo method is:
1376 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1378 % A description of each parameter follows:
1380 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1383 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1385 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1386 assert(quantize_info != (QuantizeInfo *) NULL);
1387 assert(quantize_info->signature == MagickSignature);
1388 quantize_info->signature=(~MagickSignature);
1389 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1390 return(quantize_info);
1394 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1398 + D i t h e r I m a g e %
1402 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1404 % DitherImage() distributes the difference between an original image and
1405 % the corresponding color reduced algorithm to neighboring pixels using
1406 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1407 % MagickTrue if the image is dithered otherwise MagickFalse.
1409 % The format of the DitherImage method is:
1411 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1412 % ExceptionInfo *exception)
1414 % A description of each parameter follows.
1416 % o image: the image.
1418 % o cube_info: A pointer to the Cube structure.
1420 % o exception: return any errors or warnings in this structure.
1424 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1429 assert(pixels != (RealPixelInfo **) NULL);
1430 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1431 if (pixels[i] != (RealPixelInfo *) NULL)
1432 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1433 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1437 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1448 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1449 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1451 if (pixels == (RealPixelInfo **) NULL)
1452 return((RealPixelInfo **) NULL);
1453 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1454 for (i=0; i < (ssize_t) number_threads; i++)
1456 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1457 if (pixels[i] == (RealPixelInfo *) NULL)
1458 return(DestroyPixelThreadSet(pixels));
1463 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1464 const RealPixelInfo *pixel)
1466 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1467 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1468 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1469 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1474 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1475 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1476 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1477 if (cube_info->associate_alpha != MagickFalse)
1478 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1482 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1483 ExceptionInfo *exception)
1485 #define DitherImageTag "Dither/Image"
1500 Distribute quantization error using Floyd-Steinberg.
1502 pixels=AcquirePixelThreadSet(image->columns);
1503 if (pixels == (RealPixelInfo **) NULL)
1504 return(MagickFalse);
1506 image_view=AcquireAuthenticCacheView(image,exception);
1507 for (y=0; y < (ssize_t) image->rows; y++)
1510 id = GetOpenMPThreadId();
1531 if (status == MagickFalse)
1533 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1534 if (q == (Quantum *) NULL)
1539 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
1541 current=pixels[id]+(y & 0x01)*image->columns;
1542 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1543 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1544 for (x=0; x < (ssize_t) image->columns; x++)
1556 q-=(y & 0x01)*GetPixelChannels(image);
1557 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1558 AssociateAlphaPixel(image,&cube,q,&pixel);
1561 pixel.red+=7*current[u-v].red/16;
1562 pixel.green+=7*current[u-v].green/16;
1563 pixel.blue+=7*current[u-v].blue/16;
1564 if (cube.associate_alpha != MagickFalse)
1565 pixel.alpha+=7*current[u-v].alpha/16;
1569 if (x < (ssize_t) (image->columns-1))
1571 pixel.red+=previous[u+v].red/16;
1572 pixel.green+=previous[u+v].green/16;
1573 pixel.blue+=previous[u+v].blue/16;
1574 if (cube.associate_alpha != MagickFalse)
1575 pixel.alpha+=previous[u+v].alpha/16;
1577 pixel.red+=5*previous[u].red/16;
1578 pixel.green+=5*previous[u].green/16;
1579 pixel.blue+=5*previous[u].blue/16;
1580 if (cube.associate_alpha != MagickFalse)
1581 pixel.alpha+=5*previous[u].alpha/16;
1584 pixel.red+=3*previous[u-v].red/16;
1585 pixel.green+=3*previous[u-v].green/16;
1586 pixel.blue+=3*previous[u-v].blue/16;
1587 if (cube.associate_alpha != MagickFalse)
1588 pixel.alpha+=3*previous[u-v].alpha/16;
1591 pixel.red=(double) ClampPixel(pixel.red);
1592 pixel.green=(double) ClampPixel(pixel.green);
1593 pixel.blue=(double) ClampPixel(pixel.blue);
1594 if (cube.associate_alpha != MagickFalse)
1595 pixel.alpha=(double) ClampPixel(pixel.alpha);
1596 i=CacheOffset(&cube,&pixel);
1597 if (cube.cache[i] < 0)
1606 Identify the deepest node containing the pixel's color.
1608 node_info=cube.root;
1609 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1611 id=ColorToNodeId(&cube,&pixel,index);
1612 if (node_info->child[id] == (NodeInfo *) NULL)
1614 node_info=node_info->child[id];
1617 Find closest color among siblings and their children.
1620 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1622 ClosestColor(image,&cube,node_info->parent);
1623 cube.cache[i]=(ssize_t) cube.color_number;
1626 Assign pixel to closest colormap entry.
1628 index=(size_t) cube.cache[i];
1629 if (image->storage_class == PseudoClass)
1630 SetPixelIndex(image,(Quantum) index,q);
1631 if (cube.quantize_info->measure_error == MagickFalse)
1633 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1634 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1635 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1636 if (cube.associate_alpha != MagickFalse)
1637 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1639 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1644 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1645 current[u].red=pixel.red-color.red;
1646 current[u].green=pixel.green-color.green;
1647 current[u].blue=pixel.blue-color.blue;
1648 if (cube.associate_alpha != MagickFalse)
1649 current[u].alpha=pixel.alpha-color.alpha;
1650 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1655 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1657 if (proceed == MagickFalse)
1660 q+=((y+1) & 0x01)*GetPixelChannels(image);
1663 image_view=DestroyCacheView(image_view);
1664 pixels=DestroyPixelThreadSet(pixels);
1668 static MagickBooleanType
1669 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1670 ExceptionInfo *exception);
1672 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1673 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1680 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1682 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1684 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1690 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1692 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1694 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1700 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1702 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1704 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1710 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1712 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1714 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1726 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1728 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1730 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1732 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1734 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1736 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1738 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1744 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1746 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1748 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1750 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1752 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1754 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1756 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1762 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1764 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1766 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1768 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1770 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1772 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1774 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1780 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1782 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1784 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1786 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1788 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1790 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1792 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1801 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1802 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1804 #define DitherImageTag "Dither/Image"
1820 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1821 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1832 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1833 if (q == (Quantum *) NULL)
1834 return(MagickFalse);
1835 AssociateAlphaPixel(image,cube_info,q,&pixel);
1836 for (i=0; i < ErrorQueueLength; i++)
1838 pixel.red+=p->weights[i]*p->error[i].red;
1839 pixel.green+=p->weights[i]*p->error[i].green;
1840 pixel.blue+=p->weights[i]*p->error[i].blue;
1841 if (cube_info->associate_alpha != MagickFalse)
1842 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1844 pixel.red=(double) ClampPixel(pixel.red);
1845 pixel.green=(double) ClampPixel(pixel.green);
1846 pixel.blue=(double) ClampPixel(pixel.blue);
1847 if (cube_info->associate_alpha != MagickFalse)
1848 pixel.alpha=(double) ClampPixel(pixel.alpha);
1849 i=CacheOffset(cube_info,&pixel);
1850 if (p->cache[i] < 0)
1859 Identify the deepest node containing the pixel's color.
1862 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1864 id=ColorToNodeId(cube_info,&pixel,index);
1865 if (node_info->child[id] == (NodeInfo *) NULL)
1867 node_info=node_info->child[id];
1870 Find closest color among siblings and their children.
1873 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1874 QuantumRange+1.0)+1.0);
1875 ClosestColor(image,p,node_info->parent);
1876 p->cache[i]=(ssize_t) p->color_number;
1879 Assign pixel to closest colormap entry.
1881 index=(size_t) p->cache[i];
1882 if (image->storage_class == PseudoClass)
1883 SetPixelIndex(image,(Quantum) index,q);
1884 if (cube_info->quantize_info->measure_error == MagickFalse)
1886 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1887 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1888 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1889 if (cube_info->associate_alpha != MagickFalse)
1890 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1892 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1893 return(MagickFalse);
1895 Propagate the error as the last entry of the error queue.
1897 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1898 sizeof(p->error[0]));
1899 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1900 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1901 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1902 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1903 if (cube_info->associate_alpha != MagickFalse)
1904 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1905 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1906 if (proceed == MagickFalse)
1907 return(MagickFalse);
1912 case WestGravity: p->x--; break;
1913 case EastGravity: p->x++; break;
1914 case NorthGravity: p->y--; break;
1915 case SouthGravity: p->y++; break;
1920 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1927 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1934 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1935 ExceptionInfo *exception)
1949 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1950 return(FloydSteinbergDither(image,cube_info,exception));
1952 Distribute quantization error along a Hilbert curve.
1954 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1955 sizeof(*cube_info->error));
1958 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1959 for (depth=1; i != 0; depth++)
1961 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1963 cube_info->offset=0;
1964 cube_info->span=(MagickSizeType) image->columns*image->rows;
1965 image_view=AcquireAuthenticCacheView(image,exception);
1967 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1968 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1969 image_view=DestroyCacheView(image_view);
1974 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1978 + G e t C u b e I n f o %
1982 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1984 % GetCubeInfo() initialize the Cube data structure.
1986 % The format of the GetCubeInfo method is:
1988 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1989 % const size_t depth,const size_t maximum_colors)
1991 % A description of each parameter follows.
1993 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1995 % o depth: Normally, this integer value is zero or one. A zero or
1996 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1997 % A tree of this depth generally allows the best representation of the
1998 % reference image with the least amount of memory and the fastest
1999 % computational speed. In some cases, such as an image with low color
2000 % dispersion (a few number of colors), a value other than
2001 % Log4(number_colors) is required. To expand the color tree completely,
2004 % o maximum_colors: maximum colors.
2007 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2008 const size_t depth,const size_t maximum_colors)
2024 Initialize tree to describe color cube_info.
2026 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2027 if (cube_info == (CubeInfo *) NULL)
2028 return((CubeInfo *) NULL);
2029 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2030 cube_info->depth=depth;
2031 if (cube_info->depth > MaxTreeDepth)
2032 cube_info->depth=MaxTreeDepth;
2033 if (cube_info->depth < 2)
2035 cube_info->maximum_colors=maximum_colors;
2037 Initialize root node.
2039 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2040 if (cube_info->root == (NodeInfo *) NULL)
2041 return((CubeInfo *) NULL);
2042 cube_info->root->parent=cube_info->root;
2043 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2044 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2047 Initialize dither resources.
2049 length=(size_t) (1UL << (4*(8-CacheShift)));
2050 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2051 if (cube_info->memory_info == (MemoryInfo *) NULL)
2052 return((CubeInfo *) NULL);
2053 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2055 Initialize color cache.
2057 for (i=0; i < (ssize_t) length; i++)
2058 cube_info->cache[i]=(-1);
2060 Distribute weights along a curve of exponential decay.
2063 for (i=0; i < ErrorQueueLength; i++)
2065 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2066 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2069 Normalize the weighting factors.
2072 for (i=0; i < ErrorQueueLength; i++)
2073 weight+=cube_info->weights[i];
2075 for (i=0; i < ErrorQueueLength; i++)
2077 cube_info->weights[i]/=weight;
2078 sum+=cube_info->weights[i];
2080 cube_info->weights[0]+=1.0-sum;
2085 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2089 + G e t N o d e I n f o %
2093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2095 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2096 % presets all fields to zero.
2098 % The format of the GetNodeInfo method is:
2100 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2101 % const size_t level,NodeInfo *parent)
2103 % A description of each parameter follows.
2105 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2107 % o id: Specifies the child number of the node.
2109 % o level: Specifies the level in the storage_class the node resides.
2112 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2113 const size_t level,NodeInfo *parent)
2118 if (cube_info->free_nodes == 0)
2124 Allocate a new queue of nodes.
2126 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2127 if (nodes == (Nodes *) NULL)
2128 return((NodeInfo *) NULL);
2129 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2130 sizeof(*nodes->nodes));
2131 if (nodes->nodes == (NodeInfo *) NULL)
2132 return((NodeInfo *) NULL);
2133 nodes->next=cube_info->node_queue;
2134 cube_info->node_queue=nodes;
2135 cube_info->next_node=nodes->nodes;
2136 cube_info->free_nodes=NodesInAList;
2139 cube_info->free_nodes--;
2140 node_info=cube_info->next_node++;
2141 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2142 node_info->parent=parent;
2144 node_info->level=level;
2149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2153 % G e t I m a g e Q u a n t i z e E r r o r %
2157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2159 % GetImageQuantizeError() measures the difference between the original
2160 % and quantized images. This difference is the total quantization error.
2161 % The error is computed by summing over all pixels in an image the distance
2162 % squared in RGB space between each reference pixel value and its quantized
2163 % value. These values are computed:
2165 % o mean_error_per_pixel: This value is the mean error for any single
2166 % pixel in the image.
2168 % o normalized_mean_square_error: This value is the normalized mean
2169 % quantization error for any single pixel in the image. This distance
2170 % measure is normalized to a range between 0 and 1. It is independent
2171 % of the range of red, green, and blue values in the image.
2173 % o normalized_maximum_square_error: Thsi value is the normalized
2174 % maximum quantization error for any single pixel in the image. This
2175 % distance measure is normalized to a range between 0 and 1. It is
2176 % independent of the range of red, green, and blue values in your image.
2178 % The format of the GetImageQuantizeError method is:
2180 % MagickBooleanType GetImageQuantizeError(Image *image,
2181 % ExceptionInfo *exception)
2183 % A description of each parameter follows.
2185 % o image: the image.
2187 % o exception: return any errors or warnings in this structure.
2190 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2191 ExceptionInfo *exception)
2203 mean_error_per_pixel;
2211 assert(image != (Image *) NULL);
2212 assert(image->signature == MagickSignature);
2213 if (image->debug != MagickFalse)
2214 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2215 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2216 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2217 if (image->storage_class == DirectClass)
2221 area=3.0*image->columns*image->rows;
2223 mean_error_per_pixel=0.0;
2225 image_view=AcquireVirtualCacheView(image,exception);
2226 for (y=0; y < (ssize_t) image->rows; y++)
2228 register const Quantum
2234 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2235 if (p == (const Quantum *) NULL)
2237 for (x=0; x < (ssize_t) image->columns; x++)
2239 index=1UL*GetPixelIndex(image,p);
2240 if (image->alpha_trait == BlendPixelTrait)
2242 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2243 beta=(double) (QuantumScale*image->colormap[index].alpha);
2245 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2246 image->colormap[index].red);
2247 mean_error_per_pixel+=distance;
2248 mean_error+=distance*distance;
2249 if (distance > maximum_error)
2250 maximum_error=distance;
2251 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2252 image->colormap[index].green);
2253 mean_error_per_pixel+=distance;
2254 mean_error+=distance*distance;
2255 if (distance > maximum_error)
2256 maximum_error=distance;
2257 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2258 image->colormap[index].blue);
2259 mean_error_per_pixel+=distance;
2260 mean_error+=distance*distance;
2261 if (distance > maximum_error)
2262 maximum_error=distance;
2263 p+=GetPixelChannels(image);
2266 image_view=DestroyCacheView(image_view);
2267 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2268 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2270 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2275 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2279 % G e t Q u a n t i z e I n f o %
2283 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2285 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2287 % The format of the GetQuantizeInfo method is:
2289 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2291 % A description of each parameter follows:
2293 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2296 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2298 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2299 assert(quantize_info != (QuantizeInfo *) NULL);
2300 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2301 quantize_info->number_colors=256;
2302 quantize_info->dither_method=RiemersmaDitherMethod;
2303 quantize_info->colorspace=UndefinedColorspace;
2304 quantize_info->measure_error=MagickFalse;
2305 quantize_info->signature=MagickSignature;
2309 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2313 % P o s t e r i z e I m a g e %
2317 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2319 % PosterizeImage() reduces the image to a limited number of colors for a
2322 % The format of the PosterizeImage method is:
2324 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2325 % const DitherMethod dither_method,ExceptionInfo *exception)
2327 % A description of each parameter follows:
2329 % o image: Specifies a pointer to an Image structure.
2331 % o levels: Number of color levels allowed in each channel. Very low values
2332 % (2, 3, or 4) have the most visible effect.
2334 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2335 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2337 % o exception: return any errors or warnings in this structure.
2341 static inline double MagickRound(double x)
2344 Round the fraction to nearest integer.
2346 if ((x-floor(x)) < (ceil(x)-x))
2351 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2352 const DitherMethod dither_method,ExceptionInfo *exception)
2354 #define PosterizeImageTag "Posterize/Image"
2355 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2356 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2376 assert(image != (Image *) NULL);
2377 assert(image->signature == MagickSignature);
2378 if (image->debug != MagickFalse)
2379 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2380 if (image->storage_class == PseudoClass)
2381 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2382 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2383 magick_threads(image,image,1,1)
2385 for (i=0; i < (ssize_t) image->colors; i++)
2390 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2391 image->colormap[i].red=(double)
2392 PosterizePixel(image->colormap[i].red);
2393 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2394 image->colormap[i].green=(double)
2395 PosterizePixel(image->colormap[i].green);
2396 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2397 image->colormap[i].blue=(double)
2398 PosterizePixel(image->colormap[i].blue);
2399 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2400 image->colormap[i].alpha=(double)
2401 PosterizePixel(image->colormap[i].alpha);
2408 image_view=AcquireAuthenticCacheView(image,exception);
2409 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2410 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2411 magick_threads(image,image,image->rows,1)
2413 for (y=0; y < (ssize_t) image->rows; y++)
2421 if (status == MagickFalse)
2423 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2424 if (q == (Quantum *) NULL)
2429 for (x=0; x < (ssize_t) image->columns; x++)
2431 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2432 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2433 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2434 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2435 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2436 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2437 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2438 (image->colorspace == CMYKColorspace))
2439 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2440 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2441 (image->alpha_trait == BlendPixelTrait))
2442 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2443 q+=GetPixelChannels(image);
2445 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2447 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2452 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2453 #pragma omp critical (MagickCore_PosterizeImage)
2455 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2457 if (proceed == MagickFalse)
2461 image_view=DestroyCacheView(image_view);
2462 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2463 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2464 levels,MaxColormapSize+1);
2465 quantize_info->dither_method=dither_method;
2466 quantize_info->tree_depth=MaxTreeDepth;
2467 status=QuantizeImage(quantize_info,image,exception);
2468 quantize_info=DestroyQuantizeInfo(quantize_info);
2473 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2477 + P r u n e C h i l d %
2481 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2483 % PruneChild() deletes the given node and merges its statistics into its
2486 % The format of the PruneSubtree method is:
2488 % PruneChild(const Image *image,CubeInfo *cube_info,
2489 % const NodeInfo *node_info)
2491 % A description of each parameter follows.
2493 % o image: the image.
2495 % o cube_info: A pointer to the Cube structure.
2497 % o node_info: pointer to node in color cube tree that is to be pruned.
2500 static void PruneChild(const Image *image,CubeInfo *cube_info,
2501 const NodeInfo *node_info)
2513 Traverse any children.
2515 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2516 for (i=0; i < (ssize_t) number_children; i++)
2517 if (node_info->child[i] != (NodeInfo *) NULL)
2518 PruneChild(image,cube_info,node_info->child[i]);
2520 Merge color statistics into parent.
2522 parent=node_info->parent;
2523 parent->number_unique+=node_info->number_unique;
2524 parent->total_color.red+=node_info->total_color.red;
2525 parent->total_color.green+=node_info->total_color.green;
2526 parent->total_color.blue+=node_info->total_color.blue;
2527 parent->total_color.alpha+=node_info->total_color.alpha;
2528 parent->child[node_info->id]=(NodeInfo *) NULL;
2533 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2537 + P r u n e L e v e l %
2541 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2543 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2544 % their color statistics into their parent node.
2546 % The format of the PruneLevel method is:
2548 % PruneLevel(const Image *image,CubeInfo *cube_info,
2549 % const NodeInfo *node_info)
2551 % A description of each parameter follows.
2553 % o image: the image.
2555 % o cube_info: A pointer to the Cube structure.
2557 % o node_info: pointer to node in color cube tree that is to be pruned.
2560 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2561 const NodeInfo *node_info)
2570 Traverse any children.
2572 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2573 for (i=0; i < (ssize_t) number_children; i++)
2574 if (node_info->child[i] != (NodeInfo *) NULL)
2575 PruneLevel(image,cube_info,node_info->child[i]);
2576 if (node_info->level == cube_info->depth)
2577 PruneChild(image,cube_info,node_info);
2581 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2585 + P r u n e T o C u b e D e p t h %
2589 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2591 % PruneToCubeDepth() deletes any nodes at a depth greater than
2592 % cube_info->depth while merging their color statistics into their parent
2595 % The format of the PruneToCubeDepth method is:
2597 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2598 % const NodeInfo *node_info)
2600 % A description of each parameter follows.
2602 % o cube_info: A pointer to the Cube structure.
2604 % o node_info: pointer to node in color cube tree that is to be pruned.
2607 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2608 const NodeInfo *node_info)
2617 Traverse any children.
2619 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2620 for (i=0; i < (ssize_t) number_children; i++)
2621 if (node_info->child[i] != (NodeInfo *) NULL)
2622 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2623 if (node_info->level > cube_info->depth)
2624 PruneChild(image,cube_info,node_info);
2628 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2632 % Q u a n t i z e I m a g e %
2636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2638 % QuantizeImage() analyzes the colors within a reference image and chooses a
2639 % fixed number of colors to represent the image. The goal of the algorithm
2640 % is to minimize the color difference between the input and output image while
2641 % minimizing the processing time.
2643 % The format of the QuantizeImage method is:
2645 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2646 % Image *image,ExceptionInfo *exception)
2648 % A description of each parameter follows:
2650 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2652 % o image: the image.
2654 % o exception: return any errors or warnings in this structure.
2658 static MagickBooleanType DirectToColormapImage(Image *image,
2659 ExceptionInfo *exception)
2677 number_colors=(size_t) (image->columns*image->rows);
2678 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2679 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2681 if (image->colors != number_colors)
2682 return(MagickFalse);
2684 image_view=AcquireAuthenticCacheView(image,exception);
2685 for (y=0; y < (ssize_t) image->rows; y++)
2696 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2697 if (q == (Quantum *) NULL)
2699 for (x=0; x < (ssize_t) image->columns; x++)
2701 image->colormap[i].red=(double) GetPixelRed(image,q);
2702 image->colormap[i].green=(double) GetPixelGreen(image,q);
2703 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2704 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2705 SetPixelIndex(image,(Quantum) i,q);
2707 q+=GetPixelChannels(image);
2709 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2711 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2713 if (proceed == MagickFalse)
2716 image_view=DestroyCacheView(image_view);
2720 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2721 Image *image,ExceptionInfo *exception)
2733 assert(quantize_info != (const QuantizeInfo *) NULL);
2734 assert(quantize_info->signature == MagickSignature);
2735 assert(image != (Image *) NULL);
2736 assert(image->signature == MagickSignature);
2737 if (image->debug != MagickFalse)
2738 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2739 maximum_colors=quantize_info->number_colors;
2740 if (maximum_colors == 0)
2741 maximum_colors=MaxColormapSize;
2742 if (maximum_colors > MaxColormapSize)
2743 maximum_colors=MaxColormapSize;
2744 if (image->alpha_trait != BlendPixelTrait)
2746 if ((image->columns*image->rows) <= maximum_colors)
2747 (void) DirectToColormapImage(image,exception);
2748 if (IsImageGray(image,exception) != MagickFalse)
2749 (void) SetGrayscaleImage(image,exception);
2751 if ((image->storage_class == PseudoClass) &&
2752 (image->colors <= maximum_colors))
2754 depth=quantize_info->tree_depth;
2761 Depth of color tree is: Log4(colormap size)+2.
2763 colors=maximum_colors;
2764 for (depth=1; colors != 0; depth++)
2766 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2768 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2770 if (IsImageGray(image,exception) != MagickFalse)
2774 Initialize color cube.
2776 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2777 if (cube_info == (CubeInfo *) NULL)
2778 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2780 status=ClassifyImageColors(cube_info,image,exception);
2781 if (status != MagickFalse)
2784 Reduce the number of colors in the image.
2786 ReduceImageColors(image,cube_info);
2787 status=AssignImageColors(image,cube_info,exception);
2789 DestroyCubeInfo(cube_info);
2794 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2798 % Q u a n t i z e I m a g e s %
2802 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2804 % QuantizeImages() analyzes the colors within a set of reference images and
2805 % chooses a fixed number of colors to represent the set. The goal of the
2806 % algorithm is to minimize the color difference between the input and output
2807 % images while minimizing the processing time.
2809 % The format of the QuantizeImages method is:
2811 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2812 % Image *images,ExceptionInfo *exception)
2814 % A description of each parameter follows:
2816 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2818 % o images: Specifies a pointer to a list of Image structures.
2820 % o exception: return any errors or warnings in this structure.
2823 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2824 Image *images,ExceptionInfo *exception)
2836 MagickProgressMonitor
2847 assert(quantize_info != (const QuantizeInfo *) NULL);
2848 assert(quantize_info->signature == MagickSignature);
2849 assert(images != (Image *) NULL);
2850 assert(images->signature == MagickSignature);
2851 if (images->debug != MagickFalse)
2852 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2853 if (GetNextImageInList(images) == (Image *) NULL)
2856 Handle a single image with QuantizeImage.
2858 status=QuantizeImage(quantize_info,images,exception);
2862 maximum_colors=quantize_info->number_colors;
2863 if (maximum_colors == 0)
2864 maximum_colors=MaxColormapSize;
2865 if (maximum_colors > MaxColormapSize)
2866 maximum_colors=MaxColormapSize;
2867 depth=quantize_info->tree_depth;
2874 Depth of color tree is: Log4(colormap size)+2.
2876 colors=maximum_colors;
2877 for (depth=1; colors != 0; depth++)
2879 if (quantize_info->dither_method != NoDitherMethod)
2883 Initialize color cube.
2885 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2886 if (cube_info == (CubeInfo *) NULL)
2888 (void) ThrowMagickException(exception,GetMagickModule(),
2889 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2890 return(MagickFalse);
2892 number_images=GetImageListLength(images);
2894 for (i=0; image != (Image *) NULL; i++)
2896 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2897 image->client_data);
2898 status=ClassifyImageColors(cube_info,image,exception);
2899 if (status == MagickFalse)
2901 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2902 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2904 if (proceed == MagickFalse)
2906 image=GetNextImageInList(image);
2908 if (status != MagickFalse)
2911 Reduce the number of colors in an image sequence.
2913 ReduceImageColors(images,cube_info);
2915 for (i=0; image != (Image *) NULL; i++)
2917 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2918 NULL,image->client_data);
2919 status=AssignImageColors(image,cube_info,exception);
2920 if (status == MagickFalse)
2922 (void) SetImageProgressMonitor(image,progress_monitor,
2923 image->client_data);
2924 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2926 if (proceed == MagickFalse)
2928 image=GetNextImageInList(image);
2931 DestroyCubeInfo(cube_info);
2936 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2940 + Q u a n t i z e E r r o r F l a t t e n %
2944 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2946 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2947 % error into a sorted 1D array. This accelerates the color reduction process.
2949 % Contributed by Yoya.
2951 % The format of the QuantizeImages method is:
2953 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2954 % const NodeInfo *node_info,const ssize_t offset,
2955 % MagickRealType *quantize_error)
2957 % A description of each parameter follows.
2959 % o image: the image.
2961 % o cube_info: A pointer to the Cube structure.
2963 % o node_info: pointer to node in color cube tree that is current pointer.
2965 % o offset: quantize error offset.
2967 % o quantize_error: the quantization error vector.
2970 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2971 const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
2980 if (offset >= (ssize_t) cube_info->nodes)
2982 quantize_error[offset]=node_info->quantize_error;
2984 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2985 for (i=0; i < (ssize_t) number_children ; i++)
2986 if (node_info->child[i] != (NodeInfo *) NULL)
2987 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
2993 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3001 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3003 % Reduce() traverses the color cube tree and prunes any node whose
3004 % quantization error falls below a particular threshold.
3006 % The format of the Reduce method is:
3008 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3010 % A description of each parameter follows.
3012 % o image: the image.
3014 % o cube_info: A pointer to the Cube structure.
3016 % o node_info: pointer to node in color cube tree that is to be pruned.
3019 static void Reduce(const Image *image,CubeInfo *cube_info,
3020 const NodeInfo *node_info)
3029 Traverse any children.
3031 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3032 for (i=0; i < (ssize_t) number_children; i++)
3033 if (node_info->child[i] != (NodeInfo *) NULL)
3034 Reduce(image,cube_info,node_info->child[i]);
3035 if (node_info->quantize_error <= cube_info->pruning_threshold)
3036 PruneChild(image,cube_info,node_info);
3040 Find minimum pruning threshold.
3042 if (node_info->number_unique > 0)
3043 cube_info->colors++;
3044 if (node_info->quantize_error < cube_info->next_threshold)
3045 cube_info->next_threshold=node_info->quantize_error;
3050 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3054 + R e d u c e I m a g e C o l o r s %
3058 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3060 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3061 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3062 % in the output image. On any given iteration over the tree, it selects
3063 % those nodes whose E value is minimal for pruning and merges their
3064 % color statistics upward. It uses a pruning threshold, Ep, to govern
3065 % node selection as follows:
3068 % while number of nodes with (n2 > 0) > required maximum number of colors
3069 % prune all nodes such that E <= Ep
3070 % Set Ep to minimum E in remaining nodes
3072 % This has the effect of minimizing any quantization error when merging
3073 % two nodes together.
3075 % When a node to be pruned has offspring, the pruning procedure invokes
3076 % itself recursively in order to prune the tree from the leaves upward.
3077 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3078 % corresponding data in that node's parent. This retains the pruned
3079 % node's color characteristics for later averaging.
3081 % For each node, n2 pixels exist for which that node represents the
3082 % smallest volume in RGB space containing those pixel's colors. When n2
3083 % > 0 the node will uniquely define a color in the output image. At the
3084 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3085 % the tree which represent colors present in the input image.
3087 % The other pixel count, n1, indicates the total number of colors
3088 % within the cubic volume which the node represents. This includes n1 -
3089 % n2 pixels whose colors should be defined by nodes at a lower level in
3092 % The format of the ReduceImageColors method is:
3094 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3096 % A description of each parameter follows.
3098 % o image: the image.
3100 % o cube_info: A pointer to the Cube structure.
3104 static int MagickRealTypeCompare(const void *error_p,const void *error_q)
3110 p=(MagickRealType *) error_p;
3111 q=(MagickRealType *) error_q;
3114 if (fabs((double) (*q-*p)) <= MagickEpsilon)
3119 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3121 #define ReduceImageTag "Reduce/Image"
3132 cube_info->next_threshold=0.0;
3133 if ((cube_info->colors > cube_info->maximum_colors) &&
3134 (cube_info->nodes > 128))
3140 Enable rapid reduction of the number of unique colors.
3142 quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
3143 sizeof(*quantize_error));
3144 if (quantize_error != (MagickRealType *) NULL)
3146 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3148 qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
3149 MagickRealTypeCompare);
3150 cube_info->next_threshold=quantize_error[MagickMax(cube_info->nodes-
3151 110*(cube_info->maximum_colors+1)/100,0)];
3152 quantize_error=(MagickRealType *) RelinquishMagickMemory(
3156 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3158 cube_info->pruning_threshold=cube_info->next_threshold;
3159 cube_info->next_threshold=cube_info->root->quantize_error-1;
3160 cube_info->colors=0;
3161 Reduce(image,cube_info,cube_info->root);
3162 offset=(MagickOffsetType) span-cube_info->colors;
3163 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3164 cube_info->maximum_colors+1);
3165 if (proceed == MagickFalse)
3171 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3175 % R e m a p I m a g e %
3179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3181 % RemapImage() replaces the colors of an image with a dither of the colors
3184 % The format of the RemapImage method is:
3186 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3187 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3189 % A description of each parameter follows:
3191 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3193 % o image: the image.
3195 % o remap_image: the reference image.
3197 % o exception: return any errors or warnings in this structure.
3200 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3201 Image *image,const Image *remap_image,ExceptionInfo *exception)
3210 Initialize color cube.
3212 assert(image != (Image *) NULL);
3213 assert(image->signature == MagickSignature);
3214 if (image->debug != MagickFalse)
3215 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3216 assert(remap_image != (Image *) NULL);
3217 assert(remap_image->signature == MagickSignature);
3218 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3219 quantize_info->number_colors);
3220 if (cube_info == (CubeInfo *) NULL)
3221 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3223 status=ClassifyImageColors(cube_info,remap_image,exception);
3224 if (status != MagickFalse)
3227 Classify image colors from the reference image.
3229 cube_info->quantize_info->number_colors=cube_info->colors;
3230 status=AssignImageColors(image,cube_info,exception);
3232 DestroyCubeInfo(cube_info);
3237 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3241 % R e m a p I m a g e s %
3245 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3247 % RemapImages() replaces the colors of a sequence of images with the
3248 % closest color from a reference image.
3250 % The format of the RemapImage method is:
3252 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3253 % Image *images,Image *remap_image,ExceptionInfo *exception)
3255 % A description of each parameter follows:
3257 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3259 % o images: the image sequence.
3261 % o remap_image: the reference image.
3263 % o exception: return any errors or warnings in this structure.
3266 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3267 Image *images,const Image *remap_image,ExceptionInfo *exception)
3278 assert(images != (Image *) NULL);
3279 assert(images->signature == MagickSignature);
3280 if (images->debug != MagickFalse)
3281 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3283 if (remap_image == (Image *) NULL)
3286 Create a global colormap for an image sequence.
3288 status=QuantizeImages(quantize_info,images,exception);
3292 Classify image colors from the reference image.
3294 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3295 quantize_info->number_colors);
3296 if (cube_info == (CubeInfo *) NULL)
3297 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3299 status=ClassifyImageColors(cube_info,remap_image,exception);
3300 if (status != MagickFalse)
3303 Classify image colors from the reference image.
3305 cube_info->quantize_info->number_colors=cube_info->colors;
3307 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3309 status=AssignImageColors(image,cube_info,exception);
3310 if (status == MagickFalse)
3314 DestroyCubeInfo(cube_info);
3319 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3323 % S e t G r a y s c a l e I m a g e %
3327 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3329 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3331 % The format of the SetGrayscaleImage method is:
3333 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3335 % A description of each parameter follows:
3337 % o image: The image.
3339 % o exception: return any errors or warnings in this structure.
3343 #if defined(__cplusplus) || defined(c_plusplus)
3347 static int IntensityCompare(const void *x,const void *y)
3356 color_1=(PixelInfo *) x;
3357 color_2=(PixelInfo *) y;
3358 intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
3359 GetPixelInfoIntensity(color_2));
3360 return((int) intensity);
3363 #if defined(__cplusplus) || defined(c_plusplus)
3367 static MagickBooleanType SetGrayscaleImage(Image *image,
3368 ExceptionInfo *exception)
3387 assert(image != (Image *) NULL);
3388 assert(image->signature == MagickSignature);
3389 if (image->type != GrayscaleType)
3390 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3391 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3392 sizeof(*colormap_index));
3393 if (colormap_index == (ssize_t *) NULL)
3394 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3396 if (image->storage_class != PseudoClass)
3398 for (i=0; i <= (ssize_t) MaxMap; i++)
3399 colormap_index[i]=(-1);
3400 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3401 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3405 image_view=AcquireAuthenticCacheView(image,exception);
3406 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3407 #pragma omp parallel for schedule(static,4) shared(status) \
3408 magick_threads(image,image,image->rows,1)
3410 for (y=0; y < (ssize_t) image->rows; y++)
3418 if (status == MagickFalse)
3420 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3422 if (q == (Quantum *) NULL)
3427 for (x=0; x < (ssize_t) image->columns; x++)
3432 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3433 if (colormap_index[intensity] < 0)
3435 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3436 #pragma omp critical (MagickCore_SetGrayscaleImage)
3438 if (colormap_index[intensity] < 0)
3440 colormap_index[intensity]=(ssize_t) image->colors;
3441 image->colormap[image->colors].red=(double)
3442 GetPixelRed(image,q);
3443 image->colormap[image->colors].green=(double)
3444 GetPixelGreen(image,q);
3445 image->colormap[image->colors].blue=(double)
3446 GetPixelBlue(image,q);
3450 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3451 q+=GetPixelChannels(image);
3453 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3456 image_view=DestroyCacheView(image_view);
3458 for (i=0; i < (ssize_t) image->colors; i++)
3459 image->colormap[i].alpha=(double) i;
3460 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3462 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3463 if (colormap == (PixelInfo *) NULL)
3464 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3467 colormap[j]=image->colormap[0];
3468 for (i=0; i < (ssize_t) image->colors; i++)
3470 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3473 colormap[j]=image->colormap[i];
3475 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3477 image->colors=(size_t) (j+1);
3478 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3479 image->colormap=colormap;
3481 image_view=AcquireAuthenticCacheView(image,exception);
3482 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3483 #pragma omp parallel for schedule(static,4) shared(status) \
3484 magick_threads(image,image,image->rows,1)
3486 for (y=0; y < (ssize_t) image->rows; y++)
3494 if (status == MagickFalse)
3496 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3497 if (q == (Quantum *) NULL)
3502 for (x=0; x < (ssize_t) image->columns; x++)
3504 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3505 GetPixelIndex(image,q))],q);
3506 q+=GetPixelChannels(image);
3508 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3511 image_view=DestroyCacheView(image_view);
3512 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3513 image->type=GrayscaleType;
3514 if (IsImageMonochrome(image,exception) != MagickFalse)
3515 image->type=BilevelType;