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 size_t ColorToNodeId(const CubeInfo *cube_info,
482 const RealPixelInfo *pixel,size_t index)
487 id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
488 ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
489 ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
490 if (cube_info->associate_alpha != MagickFalse)
491 id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
495 static inline MagickBooleanType PreAssignImageColors(Image *image,
496 CubeInfo *cube_info,ExceptionInfo *exception)
499 Allocate image colormap.
501 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
502 (cube_info->quantize_info->colorspace != CMYKColorspace))
503 (void) TransformImageColorspace((Image *) image,
504 cube_info->quantize_info->colorspace,exception);
506 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
507 (void) TransformImageColorspace((Image *) image,sRGBColorspace,
509 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
512 cube_info->transparent_pixels=0;
513 cube_info->transparent_index=(-1);
514 (void) DefineImageColormap(image,cube_info,cube_info->root);
518 static inline void PostAssignImageColors(Image *image,CubeInfo *cube_info,
519 ExceptionInfo *exception)
521 if (cube_info->quantize_info->measure_error != MagickFalse)
522 (void) GetImageQuantizeError(image,exception);
523 if ((cube_info->quantize_info->number_colors == 2) &&
524 (cube_info->quantize_info->colorspace == GRAYColorspace))
539 for (i=0; i < (ssize_t) image->colors; i++)
541 intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
551 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
552 ExceptionInfo *exception)
554 #define AssignImageTag "Assign/Image"
559 if (PreAssignImageColors(image,cube_info,exception) == MagickFalse)
560 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
563 Create a reduced color image.
565 if (cube_info->quantize_info->dither_method != NoDitherMethod)
566 (void) DitherImage(image,cube_info,exception);
576 image_view=AcquireAuthenticCacheView(image,exception);
577 #if defined(MAGICKCORE_OPENMP_SUPPORT)
578 #pragma omp parallel for schedule(static,4) shared(status) \
579 magick_threads(image,image,image->rows,1)
581 for (y=0; y < (ssize_t) image->rows; y++)
595 if (status == MagickFalse)
597 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
599 if (q == (Quantum *) NULL)
605 for (x=0; x < (ssize_t) image->columns; x+=count)
610 register const NodeInfo
621 Identify the deepest node containing the pixel's color.
623 for (count=1; (x+count) < (ssize_t) image->columns; count++)
628 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
629 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
632 AssociateAlphaPixel(image,&cube,q,&pixel);
634 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
636 id=ColorToNodeId(&cube,&pixel,index);
637 if (node_info->child[id] == (NodeInfo *) NULL)
639 node_info=node_info->child[id];
642 Find closest color among siblings and their children.
645 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
647 ClosestColor(image,&cube,node_info->parent);
648 index=cube.color_number;
649 for (i=0; i < (ssize_t) count; i++)
651 if (image->storage_class == PseudoClass)
652 SetPixelIndex(image,(Quantum) index,q);
653 if (cube.quantize_info->measure_error == MagickFalse)
655 SetPixelRed(image,ClampToQuantum(
656 image->colormap[index].red),q);
657 SetPixelGreen(image,ClampToQuantum(
658 image->colormap[index].green),q);
659 SetPixelBlue(image,ClampToQuantum(
660 image->colormap[index].blue),q);
661 if (cube.associate_alpha != MagickFalse)
662 SetPixelAlpha(image,ClampToQuantum(
663 image->colormap[index].alpha),q);
665 q+=GetPixelChannels(image);
668 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
670 if (image->progress_monitor != (MagickProgressMonitor) NULL)
675 #if defined(MAGICKCORE_OPENMP_SUPPORT)
676 #pragma omp critical (MagickCore_AssignImageColors)
678 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
680 if (proceed == MagickFalse)
684 image_view=DestroyCacheView(image_view);
686 PostAssignImageColors(image,cube_info,exception);
687 (void) SyncImage(image,exception);
688 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
689 (cube_info->quantize_info->colorspace != CMYKColorspace))
690 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
695 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
699 + C l a s s i f y I m a g e C o l o r s %
703 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
705 % ClassifyImageColors() begins by initializing a color description tree
706 % of sufficient depth to represent each possible input color in a leaf.
707 % However, it is impractical to generate a fully-formed color
708 % description tree in the storage_class phase for realistic values of
709 % Cmax. If colors components in the input image are quantized to k-bit
710 % precision, so that Cmax= 2k-1, the tree would need k levels below the
711 % root node to allow representing each possible input color in a leaf.
712 % This becomes prohibitive because the tree's total number of nodes is
715 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
716 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
717 % Initializes data structures for nodes only as they are needed; (2)
718 % Chooses a maximum depth for the tree as a function of the desired
719 % number of colors in the output image (currently log2(colormap size)).
721 % For each pixel in the input image, storage_class scans downward from
722 % the root of the color description tree. At each level of the tree it
723 % identifies the single node which represents a cube in RGB space
724 % containing It updates the following data for each such node:
726 % n1 : Number of pixels whose color is contained in the RGB cube
727 % which this node represents;
729 % n2 : Number of pixels whose color is not represented in a node at
730 % lower depth in the tree; initially, n2 = 0 for all nodes except
731 % leaves of the tree.
733 % Sr, Sg, Sb : Sums of the red, green, and blue component values for
734 % all pixels not classified at a lower depth. The combination of
735 % these sums and n2 will ultimately characterize the mean color of a
736 % set of pixels represented by this node.
738 % E: the distance squared in RGB space between each pixel contained
739 % within a node and the nodes' center. This represents the quantization
742 % The format of the ClassifyImageColors() method is:
744 % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
745 % const Image *image,ExceptionInfo *exception)
747 % A description of each parameter follows.
749 % o cube_info: A pointer to the Cube structure.
751 % o image: the image.
755 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
760 associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
762 if ((cube_info->quantize_info->number_colors == 2) &&
763 (cube_info->quantize_info->colorspace == GRAYColorspace))
764 associate_alpha=MagickFalse;
765 cube_info->associate_alpha=associate_alpha;
768 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
769 const Image *image,ExceptionInfo *exception)
771 #define ClassifyImageTag "Classify/Image"
801 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
803 SetAssociatedAlpha(image,cube_info);
804 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
805 (cube_info->quantize_info->colorspace != CMYKColorspace))
806 (void) TransformImageColorspace((Image *) image,
807 cube_info->quantize_info->colorspace,exception);
809 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
810 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
811 midpoint.red=(double) QuantumRange/2.0;
812 midpoint.green=(double) QuantumRange/2.0;
813 midpoint.blue=(double) QuantumRange/2.0;
814 midpoint.alpha=(double) QuantumRange/2.0;
816 image_view=AcquireVirtualCacheView(image,exception);
817 for (y=0; y < (ssize_t) image->rows; y++)
819 register const Quantum
825 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
826 if (p == (const Quantum *) NULL)
828 if (cube_info->nodes > MaxNodes)
831 Prune one level if the color tree is too large.
833 PruneLevel(image,cube_info,cube_info->root);
836 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
839 Start at the root and descend the color cube tree.
841 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
846 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
847 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
850 AssociateAlphaPixel(image,cube_info,p,&pixel);
851 index=MaxTreeDepth-1;
852 bisect=((double) QuantumRange+1.0)/2.0;
854 node_info=cube_info->root;
855 for (level=1; level <= MaxTreeDepth; level++)
861 id=ColorToNodeId(cube_info,&pixel,index);
862 mid.red+=(id & 1) != 0 ? bisect : -bisect;
863 mid.green+=(id & 2) != 0 ? bisect : -bisect;
864 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
865 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
866 if (node_info->child[id] == (NodeInfo *) NULL)
869 Set colors of new node to contain pixel.
871 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
872 if (node_info->child[id] == (NodeInfo *) NULL)
874 (void) ThrowMagickException(exception,GetMagickModule(),
875 ResourceLimitError,"MemoryAllocationFailed","`%s'",
879 if (level == MaxTreeDepth)
883 Approximate the quantization error represented by this node.
885 node_info=node_info->child[id];
886 error.red=QuantumScale*(pixel.red-mid.red);
887 error.green=QuantumScale*(pixel.green-mid.green);
888 error.blue=QuantumScale*(pixel.blue-mid.blue);
889 if (cube_info->associate_alpha != MagickFalse)
890 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
891 distance=(double) (error.red*error.red+error.green*error.green+
892 error.blue*error.blue+error.alpha*error.alpha);
893 if (IsNaN(distance) != MagickFalse)
895 node_info->quantize_error+=count*sqrt(distance);
896 cube_info->root->quantize_error+=node_info->quantize_error;
900 Sum RGB for this leaf for later derivation of the mean cube color.
902 node_info->number_unique+=count;
903 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
904 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
905 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
906 if (cube_info->associate_alpha != MagickFalse)
907 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
909 p+=count*GetPixelChannels(image);
911 if (cube_info->colors > cube_info->maximum_colors)
913 PruneToCubeDepth(image,cube_info,cube_info->root);
916 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
918 if (proceed == MagickFalse)
921 for (y++; y < (ssize_t) image->rows; y++)
923 register const Quantum
929 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
930 if (p == (const Quantum *) NULL)
932 if (cube_info->nodes > MaxNodes)
935 Prune one level if the color tree is too large.
937 PruneLevel(image,cube_info,cube_info->root);
940 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
943 Start at the root and descend the color cube tree.
945 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
950 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
951 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
954 AssociateAlphaPixel(image,cube_info,p,&pixel);
955 index=MaxTreeDepth-1;
956 bisect=((double) QuantumRange+1.0)/2.0;
958 node_info=cube_info->root;
959 for (level=1; level <= cube_info->depth; level++)
965 id=ColorToNodeId(cube_info,&pixel,index);
966 mid.red+=(id & 1) != 0 ? bisect : -bisect;
967 mid.green+=(id & 2) != 0 ? bisect : -bisect;
968 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
969 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
970 if (node_info->child[id] == (NodeInfo *) NULL)
973 Set colors of new node to contain pixel.
975 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
976 if (node_info->child[id] == (NodeInfo *) NULL)
978 (void) ThrowMagickException(exception,GetMagickModule(),
979 ResourceLimitError,"MemoryAllocationFailed","%s",
983 if (level == cube_info->depth)
987 Approximate the quantization error represented by this node.
989 node_info=node_info->child[id];
990 error.red=QuantumScale*(pixel.red-mid.red);
991 error.green=QuantumScale*(pixel.green-mid.green);
992 error.blue=QuantumScale*(pixel.blue-mid.blue);
993 if (cube_info->associate_alpha != MagickFalse)
994 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
995 distance=(double) (error.red*error.red+error.green*error.green+
996 error.blue*error.blue+error.alpha*error.alpha);
997 if (IsNaN(distance) != MagickFalse)
999 node_info->quantize_error+=count*sqrt(distance);
1000 cube_info->root->quantize_error+=node_info->quantize_error;
1004 Sum RGB for this leaf for later derivation of the mean cube color.
1006 node_info->number_unique+=count;
1007 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
1008 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
1009 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
1010 if (cube_info->associate_alpha != MagickFalse)
1011 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
1013 p+=count*GetPixelChannels(image);
1015 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1017 if (proceed == MagickFalse)
1020 image_view=DestroyCacheView(image_view);
1021 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1022 (cube_info->quantize_info->colorspace != CMYKColorspace))
1023 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1024 return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1028 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032 % C l o n e Q u a n t i z e I n f o %
1036 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1038 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1039 % or if quantize info is NULL, a new one.
1041 % The format of the CloneQuantizeInfo method is:
1043 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1045 % A description of each parameter follows:
1047 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1048 % quantize info, or if image info is NULL a new one.
1050 % o quantize_info: a structure of type info.
1053 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1058 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1059 if (clone_info == (QuantizeInfo *) NULL)
1060 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1061 GetQuantizeInfo(clone_info);
1062 if (quantize_info == (QuantizeInfo *) NULL)
1064 clone_info->number_colors=quantize_info->number_colors;
1065 clone_info->tree_depth=quantize_info->tree_depth;
1066 clone_info->dither_method=quantize_info->dither_method;
1067 clone_info->colorspace=quantize_info->colorspace;
1068 clone_info->measure_error=quantize_info->measure_error;
1073 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1077 + C l o s e s t C o l o r %
1081 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1083 % ClosestColor() traverses the color cube tree at a particular node and
1084 % determines which colormap entry best represents the input color.
1086 % The format of the ClosestColor method is:
1088 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1089 % const NodeInfo *node_info)
1091 % A description of each parameter follows.
1093 % o image: the image.
1095 % o cube_info: A pointer to the Cube structure.
1097 % o node_info: the address of a structure of type NodeInfo which points to a
1098 % node in the color cube tree that is to be pruned.
1101 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1102 const NodeInfo *node_info)
1111 Traverse any children.
1113 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1114 for (i=0; i < (ssize_t) number_children; i++)
1115 if (node_info->child[i] != (NodeInfo *) NULL)
1116 ClosestColor(image,cube_info,node_info->child[i]);
1117 if (node_info->number_unique != 0)
1130 register RealPixelInfo
1134 Determine if this color is "closest".
1136 p=image->colormap+node_info->color_number;
1137 q=(&cube_info->target);
1140 if (cube_info->associate_alpha != MagickFalse)
1142 alpha=(double) (QuantumScale*p->alpha);
1143 beta=(double) (QuantumScale*q->alpha);
1145 pixel=alpha*p->red-beta*q->red;
1146 distance=pixel*pixel;
1147 if (distance <= cube_info->distance)
1149 pixel=alpha*p->green-beta*q->green;
1150 distance+=pixel*pixel;
1151 if (distance <= cube_info->distance)
1153 pixel=alpha*p->blue-beta*q->blue;
1154 distance+=pixel*pixel;
1155 if (distance <= cube_info->distance)
1158 distance+=pixel*pixel;
1159 if (distance <= cube_info->distance)
1161 cube_info->distance=distance;
1162 cube_info->color_number=node_info->color_number;
1171 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1175 % C o m p r e s s I m a g e C o l o r m a p %
1179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1181 % CompressImageColormap() compresses an image colormap by removing any
1182 % duplicate or unused color entries.
1184 % The format of the CompressImageColormap method is:
1186 % MagickBooleanType CompressImageColormap(Image *image,
1187 % ExceptionInfo *exception)
1189 % A description of each parameter follows:
1191 % o image: the image.
1193 % o exception: return any errors or warnings in this structure.
1196 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1197 ExceptionInfo *exception)
1202 assert(image != (Image *) NULL);
1203 assert(image->signature == MagickCoreSignature);
1204 if (image->debug != MagickFalse)
1205 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1206 if (IsPaletteImage(image,exception) == MagickFalse)
1207 return(MagickFalse);
1208 GetQuantizeInfo(&quantize_info);
1209 quantize_info.number_colors=image->colors;
1210 quantize_info.tree_depth=MaxTreeDepth;
1211 return(QuantizeImage(&quantize_info,image,exception));
1215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1219 + D e f i n e I m a g e C o l o r m a p %
1223 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1225 % DefineImageColormap() traverses the color cube tree and notes each colormap
1226 % entry. A colormap entry is any node in the color cube tree where the
1227 % of unique colors is not zero. DefineImageColormap() returns the number of
1228 % colors in the image colormap.
1230 % The format of the DefineImageColormap method is:
1232 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1233 % NodeInfo *node_info)
1235 % A description of each parameter follows.
1237 % o image: the image.
1239 % o cube_info: A pointer to the Cube structure.
1241 % o node_info: the address of a structure of type NodeInfo which points to a
1242 % node in the color cube tree that is to be pruned.
1245 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1246 NodeInfo *node_info)
1255 Traverse any children.
1257 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1258 for (i=0; i < (ssize_t) number_children; i++)
1259 if (node_info->child[i] != (NodeInfo *) NULL)
1260 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1261 if (node_info->number_unique != 0)
1270 Colormap entry is defined by the mean color in this cube.
1272 q=image->colormap+image->colors;
1273 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1274 alpha=PerceptibleReciprocal(alpha);
1275 if (cube_info->associate_alpha == MagickFalse)
1277 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1278 node_info->total_color.red);
1279 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1280 node_info->total_color.green);
1281 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1282 node_info->total_color.blue);
1283 q->alpha=(double) OpaqueAlpha;
1290 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1291 q->alpha=(double) ClampToQuantum(opacity);
1292 if (q->alpha == OpaqueAlpha)
1294 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1295 node_info->total_color.red);
1296 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1297 node_info->total_color.green);
1298 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1299 node_info->total_color.blue);
1306 gamma=(double) (QuantumScale*q->alpha);
1307 gamma=PerceptibleReciprocal(gamma);
1308 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1309 node_info->total_color.red);
1310 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1311 node_info->total_color.green);
1312 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1313 node_info->total_color.blue);
1314 if (node_info->number_unique > cube_info->transparent_pixels)
1316 cube_info->transparent_pixels=node_info->number_unique;
1317 cube_info->transparent_index=(ssize_t) image->colors;
1321 node_info->color_number=image->colors++;
1323 return(image->colors);
1327 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1331 + D e s t r o y C u b e I n f o %
1335 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1337 % DestroyCubeInfo() deallocates memory associated with an image.
1339 % The format of the DestroyCubeInfo method is:
1341 % DestroyCubeInfo(CubeInfo *cube_info)
1343 % A description of each parameter follows:
1345 % o cube_info: the address of a structure of type CubeInfo.
1348 static void DestroyCubeInfo(CubeInfo *cube_info)
1354 Release color cube tree storage.
1358 nodes=cube_info->node_queue->next;
1359 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1360 cube_info->node_queue->nodes);
1361 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1362 cube_info->node_queue);
1363 cube_info->node_queue=nodes;
1364 } while (cube_info->node_queue != (Nodes *) NULL);
1365 if (cube_info->memory_info != (MemoryInfo *) NULL)
1366 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1367 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1368 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1372 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1376 % D e s t r o y Q u a n t i z e I n f o %
1380 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1382 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1385 % The format of the DestroyQuantizeInfo method is:
1387 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1389 % A description of each parameter follows:
1391 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1394 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1396 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1397 assert(quantize_info != (QuantizeInfo *) NULL);
1398 assert(quantize_info->signature == MagickCoreSignature);
1399 quantize_info->signature=(~MagickCoreSignature);
1400 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1401 return(quantize_info);
1405 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1409 + D i t h e r I m a g e %
1413 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1415 % DitherImage() distributes the difference between an original image and
1416 % the corresponding color reduced algorithm to neighboring pixels using
1417 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1418 % MagickTrue if the image is dithered otherwise MagickFalse.
1420 % The format of the DitherImage method is:
1422 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1423 % ExceptionInfo *exception)
1425 % A description of each parameter follows.
1427 % o image: the image.
1429 % o cube_info: A pointer to the Cube structure.
1431 % o exception: return any errors or warnings in this structure.
1435 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1440 assert(pixels != (RealPixelInfo **) NULL);
1441 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1442 if (pixels[i] != (RealPixelInfo *) NULL)
1443 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1444 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1448 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1459 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1460 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1462 if (pixels == (RealPixelInfo **) NULL)
1463 return((RealPixelInfo **) NULL);
1464 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1465 for (i=0; i < (ssize_t) number_threads; i++)
1467 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1468 if (pixels[i] == (RealPixelInfo *) NULL)
1469 return(DestroyPixelThreadSet(pixels));
1474 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1475 const RealPixelInfo *pixel)
1477 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1478 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1479 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1480 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1485 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1486 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1487 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1488 if (cube_info->associate_alpha != MagickFalse)
1489 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1493 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1494 ExceptionInfo *exception)
1496 #define DitherImageTag "Dither/Image"
1511 Distribute quantization error using Floyd-Steinberg.
1513 pixels=AcquirePixelThreadSet(image->columns);
1514 if (pixels == (RealPixelInfo **) NULL)
1515 return(MagickFalse);
1517 image_view=AcquireAuthenticCacheView(image,exception);
1518 for (y=0; y < (ssize_t) image->rows; y++)
1521 id = GetOpenMPThreadId();
1542 if (status == MagickFalse)
1544 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1545 if (q == (Quantum *) NULL)
1551 current=pixels[id]+(y & 0x01)*image->columns;
1552 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1553 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1554 for (x=0; x < (ssize_t) image->columns; x++)
1566 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1567 AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&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+u*GetPixelChannels(image));
1640 if (cube.quantize_info->measure_error == MagickFalse)
1642 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),
1643 q+u*GetPixelChannels(image));
1644 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),
1645 q+u*GetPixelChannels(image));
1646 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),
1647 q+u*GetPixelChannels(image));
1648 if (cube.associate_alpha != MagickFalse)
1649 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),
1650 q+u*GetPixelChannels(image));
1652 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1657 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1658 current[u].red=pixel.red-color.red;
1659 current[u].green=pixel.green-color.green;
1660 current[u].blue=pixel.blue-color.blue;
1661 if (cube.associate_alpha != MagickFalse)
1662 current[u].alpha=pixel.alpha-color.alpha;
1663 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1668 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1670 if (proceed == MagickFalse)
1675 image_view=DestroyCacheView(image_view);
1676 pixels=DestroyPixelThreadSet(pixels);
1680 static MagickBooleanType
1681 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1684 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1685 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1692 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1694 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1696 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1702 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1704 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1712 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1714 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1716 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1722 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1724 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1726 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1738 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1740 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1742 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1744 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1746 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1748 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1750 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1756 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1758 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1760 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1762 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1764 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1766 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1768 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1774 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1776 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1778 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1780 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1782 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1784 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1786 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1792 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1794 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1796 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1798 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1800 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1802 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1804 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1813 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1814 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1816 #define DitherImageTag "Dither/Image"
1832 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1833 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1844 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1845 if (q == (Quantum *) NULL)
1846 return(MagickFalse);
1847 AssociateAlphaPixel(image,cube_info,q,&pixel);
1848 for (i=0; i < ErrorQueueLength; i++)
1850 pixel.red+=p->weights[i]*p->error[i].red;
1851 pixel.green+=p->weights[i]*p->error[i].green;
1852 pixel.blue+=p->weights[i]*p->error[i].blue;
1853 if (cube_info->associate_alpha != MagickFalse)
1854 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1856 pixel.red=(double) ClampPixel(pixel.red);
1857 pixel.green=(double) ClampPixel(pixel.green);
1858 pixel.blue=(double) ClampPixel(pixel.blue);
1859 if (cube_info->associate_alpha != MagickFalse)
1860 pixel.alpha=(double) ClampPixel(pixel.alpha);
1861 i=CacheOffset(cube_info,&pixel);
1862 if (p->cache[i] < 0)
1871 Identify the deepest node containing the pixel's color.
1874 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1876 id=ColorToNodeId(cube_info,&pixel,index);
1877 if (node_info->child[id] == (NodeInfo *) NULL)
1879 node_info=node_info->child[id];
1882 Find closest color among siblings and their children.
1885 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1886 QuantumRange+1.0)+1.0);
1887 ClosestColor(image,p,node_info->parent);
1888 p->cache[i]=(ssize_t) p->color_number;
1891 Assign pixel to closest colormap entry.
1893 index=(size_t) p->cache[i];
1894 if (image->storage_class == PseudoClass)
1895 SetPixelIndex(image,(Quantum) index,q);
1896 if (cube_info->quantize_info->measure_error == MagickFalse)
1898 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1899 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1900 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1901 if (cube_info->associate_alpha != MagickFalse)
1902 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1904 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1905 return(MagickFalse);
1907 Propagate the error as the last entry of the error queue.
1909 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1910 sizeof(p->error[0]));
1911 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1912 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1913 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1914 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1915 if (cube_info->associate_alpha != MagickFalse)
1916 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1917 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1918 if (proceed == MagickFalse)
1919 return(MagickFalse);
1924 case WestGravity: p->x--; break;
1925 case EastGravity: p->x++; break;
1926 case NorthGravity: p->y--; break;
1927 case SouthGravity: p->y++; break;
1932 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1933 ExceptionInfo *exception)
1947 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1948 return(FloydSteinbergDither(image,cube_info,exception));
1950 Distribute quantization error along a Hilbert curve.
1952 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1953 sizeof(*cube_info->error));
1956 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1957 for (depth=1; i != 0; depth++)
1959 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1961 cube_info->offset=0;
1962 cube_info->span=(MagickSizeType) image->columns*image->rows;
1963 image_view=AcquireAuthenticCacheView(image,exception);
1965 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1966 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1967 image_view=DestroyCacheView(image_view);
1972 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1976 + G e t C u b e I n f o %
1980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1982 % GetCubeInfo() initialize the Cube data structure.
1984 % The format of the GetCubeInfo method is:
1986 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1987 % const size_t depth,const size_t maximum_colors)
1989 % A description of each parameter follows.
1991 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1993 % o depth: Normally, this integer value is zero or one. A zero or
1994 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1995 % A tree of this depth generally allows the best representation of the
1996 % reference image with the least amount of memory and the fastest
1997 % computational speed. In some cases, such as an image with low color
1998 % dispersion (a few number of colors), a value other than
1999 % Log4(number_colors) is required. To expand the color tree completely,
2002 % o maximum_colors: maximum colors.
2005 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2006 const size_t depth,const size_t maximum_colors)
2022 Initialize tree to describe color cube_info.
2024 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2025 if (cube_info == (CubeInfo *) NULL)
2026 return((CubeInfo *) NULL);
2027 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2028 cube_info->depth=depth;
2029 if (cube_info->depth > MaxTreeDepth)
2030 cube_info->depth=MaxTreeDepth;
2031 if (cube_info->depth < 2)
2033 cube_info->maximum_colors=maximum_colors;
2035 Initialize root node.
2037 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2038 if (cube_info->root == (NodeInfo *) NULL)
2039 return((CubeInfo *) NULL);
2040 cube_info->root->parent=cube_info->root;
2041 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2042 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2045 Initialize dither resources.
2047 length=(size_t) (1UL << (4*(8-CacheShift)));
2048 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2049 if (cube_info->memory_info == (MemoryInfo *) NULL)
2050 return((CubeInfo *) NULL);
2051 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2053 Initialize color cache.
2055 (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)*
2058 Distribute weights along a curve of exponential decay.
2061 for (i=0; i < ErrorQueueLength; i++)
2063 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2064 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2067 Normalize the weighting factors.
2070 for (i=0; i < ErrorQueueLength; i++)
2071 weight+=cube_info->weights[i];
2073 for (i=0; i < ErrorQueueLength; i++)
2075 cube_info->weights[i]/=weight;
2076 sum+=cube_info->weights[i];
2078 cube_info->weights[0]+=1.0-sum;
2083 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2087 + G e t N o d e I n f o %
2091 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2093 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2094 % presets all fields to zero.
2096 % The format of the GetNodeInfo method is:
2098 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2099 % const size_t level,NodeInfo *parent)
2101 % A description of each parameter follows.
2103 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2105 % o id: Specifies the child number of the node.
2107 % o level: Specifies the level in the storage_class the node resides.
2110 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2111 const size_t level,NodeInfo *parent)
2116 if (cube_info->free_nodes == 0)
2122 Allocate a new queue of nodes.
2124 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2125 if (nodes == (Nodes *) NULL)
2126 return((NodeInfo *) NULL);
2127 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2128 sizeof(*nodes->nodes));
2129 if (nodes->nodes == (NodeInfo *) NULL)
2130 return((NodeInfo *) NULL);
2131 nodes->next=cube_info->node_queue;
2132 cube_info->node_queue=nodes;
2133 cube_info->next_node=nodes->nodes;
2134 cube_info->free_nodes=NodesInAList;
2137 cube_info->free_nodes--;
2138 node_info=cube_info->next_node++;
2139 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2140 node_info->parent=parent;
2142 node_info->level=level;
2147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2151 % G e t I m a g e Q u a n t i z e E r r o r %
2155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2157 % GetImageQuantizeError() measures the difference between the original
2158 % and quantized images. This difference is the total quantization error.
2159 % The error is computed by summing over all pixels in an image the distance
2160 % squared in RGB space between each reference pixel value and its quantized
2161 % value. These values are computed:
2163 % o mean_error_per_pixel: This value is the mean error for any single
2164 % pixel in the image.
2166 % o normalized_mean_square_error: This value is the normalized mean
2167 % quantization error for any single pixel in the image. This distance
2168 % measure is normalized to a range between 0 and 1. It is independent
2169 % of the range of red, green, and blue values in the image.
2171 % o normalized_maximum_square_error: Thsi value is the normalized
2172 % maximum quantization error for any single pixel in the image. This
2173 % distance measure is normalized to a range between 0 and 1. It is
2174 % independent of the range of red, green, and blue values in your image.
2176 % The format of the GetImageQuantizeError method is:
2178 % MagickBooleanType GetImageQuantizeError(Image *image,
2179 % ExceptionInfo *exception)
2181 % A description of each parameter follows.
2183 % o image: the image.
2185 % o exception: return any errors or warnings in this structure.
2188 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2189 ExceptionInfo *exception)
2201 mean_error_per_pixel;
2209 assert(image != (Image *) NULL);
2210 assert(image->signature == MagickCoreSignature);
2211 if (image->debug != MagickFalse)
2212 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2213 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2214 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2215 if (image->storage_class == DirectClass)
2219 area=3.0*image->columns*image->rows;
2221 mean_error_per_pixel=0.0;
2223 image_view=AcquireVirtualCacheView(image,exception);
2224 for (y=0; y < (ssize_t) image->rows; y++)
2226 register const Quantum
2232 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2233 if (p == (const Quantum *) NULL)
2235 for (x=0; x < (ssize_t) image->columns; x++)
2237 index=GetPixelIndex(image,p);
2238 if (image->alpha_trait == BlendPixelTrait)
2240 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2241 beta=(double) (QuantumScale*image->colormap[index].alpha);
2243 distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
2244 image->colormap[index].red));
2245 mean_error_per_pixel+=distance;
2246 mean_error+=distance*distance;
2247 if (distance > maximum_error)
2248 maximum_error=distance;
2249 distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
2250 image->colormap[index].green));
2251 mean_error_per_pixel+=distance;
2252 mean_error+=distance*distance;
2253 if (distance > maximum_error)
2254 maximum_error=distance;
2255 distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta*
2256 image->colormap[index].blue));
2257 mean_error_per_pixel+=distance;
2258 mean_error+=distance*distance;
2259 if (distance > maximum_error)
2260 maximum_error=distance;
2261 p+=GetPixelChannels(image);
2264 image_view=DestroyCacheView(image_view);
2265 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2266 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2268 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2273 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2277 % G e t Q u a n t i z e I n f o %
2281 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2283 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2285 % The format of the GetQuantizeInfo method is:
2287 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2289 % A description of each parameter follows:
2291 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2294 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2296 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2297 assert(quantize_info != (QuantizeInfo *) NULL);
2298 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2299 quantize_info->number_colors=256;
2300 quantize_info->dither_method=RiemersmaDitherMethod;
2301 quantize_info->colorspace=UndefinedColorspace;
2302 quantize_info->measure_error=MagickFalse;
2303 quantize_info->signature=MagickCoreSignature;
2307 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2311 % P o s t e r i z e I m a g e %
2315 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2317 % PosterizeImage() reduces the image to a limited number of colors for a
2320 % The format of the PosterizeImage method is:
2322 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2323 % const DitherMethod dither_method,ExceptionInfo *exception)
2325 % A description of each parameter follows:
2327 % o image: Specifies a pointer to an Image structure.
2329 % o levels: Number of color levels allowed in each channel. Very low values
2330 % (2, 3, or 4) have the most visible effect.
2332 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2333 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2335 % o exception: return any errors or warnings in this structure.
2339 static inline double MagickRound(double x)
2342 Round the fraction to nearest integer.
2344 if ((x-floor(x)) < (ceil(x)-x))
2349 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2350 const DitherMethod dither_method,ExceptionInfo *exception)
2352 #define PosterizeImageTag "Posterize/Image"
2353 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2354 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2374 assert(image != (Image *) NULL);
2375 assert(image->signature == MagickCoreSignature);
2376 if (image->debug != MagickFalse)
2377 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2378 assert(exception != (ExceptionInfo *) NULL);
2379 assert(exception->signature == MagickCoreSignature);
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 DirectToPseudoClassImage(Image *image,
2659 CubeInfo *cube_info,ExceptionInfo *exception)
2667 if (cube_info->colors > cube_info->maximum_colors)
2668 return(MagickFalse);
2669 if (PreAssignImageColors(image,cube_info,exception) == MagickFalse)
2670 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2673 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2674 #pragma omp parallel for schedule(static,4) shared(status) \
2675 magick_threads(image,image,image->rows,1)
2677 for (y=0; y < (ssize_t) image->rows; y++)
2685 if (status == MagickFalse)
2687 q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
2688 if (q == (Quantum *) NULL)
2693 for (x=0; x < (ssize_t) image->columns; x++)
2698 for (i=0; i < (ssize_t) image->colors; i++)
2700 if (IsPixelEquivalent(image,q,&image->colormap[i]) == MagickFalse)
2702 SetPixelIndex(image,(Quantum) i,q);
2705 q+=GetPixelChannels(image);
2707 if (SyncAuthenticPixels(image,exception) == MagickFalse)
2710 image->storage_class=PseudoClass;
2711 PostAssignImageColors(image,cube_info,exception);
2715 static MagickBooleanType DirectToColormapImage(Image *image,
2716 ExceptionInfo *exception)
2734 number_colors=(size_t) (image->columns*image->rows);
2735 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2736 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2738 if (image->colors != number_colors)
2739 return(MagickFalse);
2741 image_view=AcquireAuthenticCacheView(image,exception);
2742 for (y=0; y < (ssize_t) image->rows; y++)
2753 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2754 if (q == (Quantum *) NULL)
2756 for (x=0; x < (ssize_t) image->columns; x++)
2758 image->colormap[i].red=(double) GetPixelRed(image,q);
2759 image->colormap[i].green=(double) GetPixelGreen(image,q);
2760 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2761 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2762 SetPixelIndex(image,(Quantum) i,q);
2764 q+=GetPixelChannels(image);
2766 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2768 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2770 if (proceed == MagickFalse)
2773 image_view=DestroyCacheView(image_view);
2777 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2778 Image *image,ExceptionInfo *exception)
2790 assert(quantize_info != (const QuantizeInfo *) NULL);
2791 assert(quantize_info->signature == MagickCoreSignature);
2792 assert(image != (Image *) NULL);
2793 assert(image->signature == MagickCoreSignature);
2794 if (image->debug != MagickFalse)
2795 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2796 assert(exception != (ExceptionInfo *) NULL);
2797 assert(exception->signature == MagickCoreSignature);
2798 maximum_colors=quantize_info->number_colors;
2799 if (maximum_colors == 0)
2800 maximum_colors=MaxColormapSize;
2801 if (maximum_colors > MaxColormapSize)
2802 maximum_colors=MaxColormapSize;
2803 if (image->alpha_trait != BlendPixelTrait)
2805 if ((image->columns*image->rows) <= maximum_colors)
2806 (void) DirectToColormapImage(image,exception);
2807 if (SetImageGray(image,exception) != MagickFalse)
2808 (void) SetGrayscaleImage(image,exception);
2810 if ((image->storage_class == PseudoClass) &&
2811 (image->colors <= maximum_colors))
2813 if ((quantize_info->colorspace != UndefinedColorspace) &&
2814 (quantize_info->colorspace != CMYKColorspace))
2815 (void) TransformImageColorspace(image,quantize_info->colorspace,
2819 depth=quantize_info->tree_depth;
2826 Depth of color tree is: Log4(colormap size)+2.
2828 colors=maximum_colors;
2829 for (depth=1; colors != 0; depth++)
2831 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2833 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2835 if (SetImageGray(image,exception) != MagickFalse)
2839 Initialize color cube.
2841 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2842 if (cube_info == (CubeInfo *) NULL)
2843 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2845 status=ClassifyImageColors(cube_info,image,exception);
2846 if (status != MagickFalse)
2849 Reduce the number of colors in the image.
2851 status=DirectToPseudoClassImage(image,cube_info,exception);
2852 if (status == MagickFalse)
2854 ReduceImageColors(image,cube_info);
2855 status=AssignImageColors(image,cube_info,exception);
2858 DestroyCubeInfo(cube_info);
2863 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2867 % Q u a n t i z e I m a g e s %
2871 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2873 % QuantizeImages() analyzes the colors within a set of reference images and
2874 % chooses a fixed number of colors to represent the set. The goal of the
2875 % algorithm is to minimize the color difference between the input and output
2876 % images while minimizing the processing time.
2878 % The format of the QuantizeImages method is:
2880 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2881 % Image *images,ExceptionInfo *exception)
2883 % A description of each parameter follows:
2885 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2887 % o images: Specifies a pointer to a list of Image structures.
2889 % o exception: return any errors or warnings in this structure.
2892 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2893 Image *images,ExceptionInfo *exception)
2905 MagickProgressMonitor
2916 assert(quantize_info != (const QuantizeInfo *) NULL);
2917 assert(quantize_info->signature == MagickCoreSignature);
2918 assert(images != (Image *) NULL);
2919 assert(images->signature == MagickCoreSignature);
2920 if (images->debug != MagickFalse)
2921 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2922 assert(exception != (ExceptionInfo *) NULL);
2923 assert(exception->signature == MagickCoreSignature);
2924 if (GetNextImageInList(images) == (Image *) NULL)
2927 Handle a single image with QuantizeImage.
2929 status=QuantizeImage(quantize_info,images,exception);
2933 maximum_colors=quantize_info->number_colors;
2934 if (maximum_colors == 0)
2935 maximum_colors=MaxColormapSize;
2936 if (maximum_colors > MaxColormapSize)
2937 maximum_colors=MaxColormapSize;
2938 depth=quantize_info->tree_depth;
2945 Depth of color tree is: Log4(colormap size)+2.
2947 colors=maximum_colors;
2948 for (depth=1; colors != 0; depth++)
2950 if (quantize_info->dither_method != NoDitherMethod)
2954 Initialize color cube.
2956 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2957 if (cube_info == (CubeInfo *) NULL)
2959 (void) ThrowMagickException(exception,GetMagickModule(),
2960 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2961 return(MagickFalse);
2963 number_images=GetImageListLength(images);
2965 for (i=0; image != (Image *) NULL; i++)
2967 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2968 image->client_data);
2969 status=ClassifyImageColors(cube_info,image,exception);
2970 if (status == MagickFalse)
2972 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2973 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2975 if (proceed == MagickFalse)
2977 image=GetNextImageInList(image);
2979 if (status != MagickFalse)
2982 Reduce the number of colors in an image sequence.
2984 ReduceImageColors(images,cube_info);
2986 for (i=0; image != (Image *) NULL; i++)
2988 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2989 NULL,image->client_data);
2990 status=AssignImageColors(image,cube_info,exception);
2991 if (status == MagickFalse)
2993 (void) SetImageProgressMonitor(image,progress_monitor,
2994 image->client_data);
2995 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2997 if (proceed == MagickFalse)
2999 image=GetNextImageInList(image);
3002 DestroyCubeInfo(cube_info);
3007 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3011 + Q u a n t i z e E r r o r F l a t t e n %
3015 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3017 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
3018 % error into a sorted 1D array. This accelerates the color reduction process.
3020 % Contributed by Yoya.
3022 % The format of the QuantizeErrorFlatten method is:
3024 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
3025 % const NodeInfo *node_info,const ssize_t offset,
3026 % double *quantize_error)
3028 % A description of each parameter follows.
3030 % o image: the image.
3032 % o cube_info: A pointer to the Cube structure.
3034 % o node_info: pointer to node in color cube tree that is current pointer.
3036 % o offset: quantize error offset.
3038 % o quantize_error: the quantization error vector.
3041 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
3042 const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
3051 if (offset >= (ssize_t) cube_info->nodes)
3053 quantize_error[offset]=node_info->quantize_error;
3055 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3056 for (i=0; i < (ssize_t) number_children ; i++)
3057 if (node_info->child[i] != (NodeInfo *) NULL)
3058 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
3064 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3072 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3074 % Reduce() traverses the color cube tree and prunes any node whose
3075 % quantization error falls below a particular threshold.
3077 % The format of the Reduce method is:
3079 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3081 % A description of each parameter follows.
3083 % o image: the image.
3085 % o cube_info: A pointer to the Cube structure.
3087 % o node_info: pointer to node in color cube tree that is to be pruned.
3090 static void Reduce(const Image *image,CubeInfo *cube_info,
3091 const NodeInfo *node_info)
3100 Traverse any children.
3102 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3103 for (i=0; i < (ssize_t) number_children; i++)
3104 if (node_info->child[i] != (NodeInfo *) NULL)
3105 Reduce(image,cube_info,node_info->child[i]);
3106 if (node_info->quantize_error <= cube_info->pruning_threshold)
3107 PruneChild(image,cube_info,node_info);
3111 Find minimum pruning threshold.
3113 if (node_info->number_unique > 0)
3114 cube_info->colors++;
3115 if (node_info->quantize_error < cube_info->next_threshold)
3116 cube_info->next_threshold=node_info->quantize_error;
3121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3125 + R e d u c e I m a g e C o l o r s %
3129 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3131 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3132 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3133 % in the output image. On any given iteration over the tree, it selects
3134 % those nodes whose E value is minimal for pruning and merges their
3135 % color statistics upward. It uses a pruning threshold, Ep, to govern
3136 % node selection as follows:
3139 % while number of nodes with (n2 > 0) > required maximum number of colors
3140 % prune all nodes such that E <= Ep
3141 % Set Ep to minimum E in remaining nodes
3143 % This has the effect of minimizing any quantization error when merging
3144 % two nodes together.
3146 % When a node to be pruned has offspring, the pruning procedure invokes
3147 % itself recursively in order to prune the tree from the leaves upward.
3148 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3149 % corresponding data in that node's parent. This retains the pruned
3150 % node's color characteristics for later averaging.
3152 % For each node, n2 pixels exist for which that node represents the
3153 % smallest volume in RGB space containing those pixel's colors. When n2
3154 % > 0 the node will uniquely define a color in the output image. At the
3155 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3156 % the tree which represent colors present in the input image.
3158 % The other pixel count, n1, indicates the total number of colors
3159 % within the cubic volume which the node represents. This includes n1 -
3160 % n2 pixels whose colors should be defined by nodes at a lower level in
3163 % The format of the ReduceImageColors method is:
3165 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3167 % A description of each parameter follows.
3169 % o image: the image.
3171 % o cube_info: A pointer to the Cube structure.
3175 static int QuantizeErrorCompare(const void *error_p,const void *error_q)
3181 p=(double *) error_p;
3182 q=(double *) error_q;
3185 if (fabs(*q-*p) <= MagickEpsilon)
3190 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3192 #define ReduceImageTag "Reduce/Image"
3203 cube_info->next_threshold=0.0;
3204 if (cube_info->colors > cube_info->maximum_colors)
3210 Enable rapid reduction of the number of unique colors.
3212 quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
3213 sizeof(*quantize_error));
3214 if (quantize_error != (double *) NULL)
3216 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3218 qsort(quantize_error,cube_info->nodes,sizeof(double),
3219 QuantizeErrorCompare);
3220 if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
3221 cube_info->next_threshold=quantize_error[cube_info->nodes-110*
3222 (cube_info->maximum_colors+1)/100];
3223 quantize_error=(double *) RelinquishMagickMemory(quantize_error);
3226 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3228 cube_info->pruning_threshold=cube_info->next_threshold;
3229 cube_info->next_threshold=cube_info->root->quantize_error-1;
3230 cube_info->colors=0;
3231 Reduce(image,cube_info,cube_info->root);
3232 offset=(MagickOffsetType) span-cube_info->colors;
3233 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3234 cube_info->maximum_colors+1);
3235 if (proceed == MagickFalse)
3241 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3245 % R e m a p I m a g e %
3249 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3251 % RemapImage() replaces the colors of an image with the closest of the colors
3252 % from the reference image.
3254 % The format of the RemapImage method is:
3256 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3257 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3259 % A description of each parameter follows:
3261 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3263 % o image: the image.
3265 % o remap_image: the reference image.
3267 % o exception: return any errors or warnings in this structure.
3270 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3271 Image *image,const Image *remap_image,ExceptionInfo *exception)
3280 Initialize color cube.
3282 assert(image != (Image *) NULL);
3283 assert(image->signature == MagickCoreSignature);
3284 if (image->debug != MagickFalse)
3285 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3286 assert(remap_image != (Image *) NULL);
3287 assert(remap_image->signature == MagickCoreSignature);
3288 assert(exception != (ExceptionInfo *) NULL);
3289 assert(exception->signature == MagickCoreSignature);
3290 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3291 quantize_info->number_colors);
3292 if (cube_info == (CubeInfo *) NULL)
3293 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3295 status=ClassifyImageColors(cube_info,remap_image,exception);
3296 if (status != MagickFalse)
3299 Classify image colors from the reference image.
3301 cube_info->quantize_info->number_colors=cube_info->colors;
3302 status=AssignImageColors(image,cube_info,exception);
3304 DestroyCubeInfo(cube_info);
3309 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3313 % R e m a p I m a g e s %
3317 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3319 % RemapImages() replaces the colors of a sequence of images with the
3320 % closest color from a reference image.
3322 % The format of the RemapImage method is:
3324 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3325 % Image *images,Image *remap_image,ExceptionInfo *exception)
3327 % A description of each parameter follows:
3329 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3331 % o images: the image sequence.
3333 % o remap_image: the reference image.
3335 % o exception: return any errors or warnings in this structure.
3338 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3339 Image *images,const Image *remap_image,ExceptionInfo *exception)
3350 assert(images != (Image *) NULL);
3351 assert(images->signature == MagickCoreSignature);
3352 if (images->debug != MagickFalse)
3353 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3354 assert(exception != (ExceptionInfo *) NULL);
3355 assert(exception->signature == MagickCoreSignature);
3357 if (remap_image == (Image *) NULL)
3360 Create a global colormap for an image sequence.
3362 status=QuantizeImages(quantize_info,images,exception);
3366 Classify image colors from the reference image.
3368 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3369 quantize_info->number_colors);
3370 if (cube_info == (CubeInfo *) NULL)
3371 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3373 status=ClassifyImageColors(cube_info,remap_image,exception);
3374 if (status != MagickFalse)
3377 Classify image colors from the reference image.
3379 cube_info->quantize_info->number_colors=cube_info->colors;
3381 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3383 status=AssignImageColors(image,cube_info,exception);
3384 if (status == MagickFalse)
3388 DestroyCubeInfo(cube_info);
3393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3397 % S e t G r a y s c a l e I m a g e %
3401 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3403 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3405 % The format of the SetGrayscaleImage method is:
3407 % MagickBooleanType SetGrayscaleImage(Image *image,
3408 % ExceptionInfo *exception)
3410 % A description of each parameter follows:
3412 % o image: The image.
3414 % o exception: return any errors or warnings in this structure.
3418 #if defined(__cplusplus) || defined(c_plusplus)
3422 static int IntensityCompare(const void *x,const void *y)
3431 color_1=(PixelInfo *) x;
3432 color_2=(PixelInfo *) y;
3433 intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
3434 GetPixelInfoIntensity((const Image *) NULL,color_2);
3435 return((int) intensity);
3438 #if defined(__cplusplus) || defined(c_plusplus)
3442 static MagickBooleanType SetGrayscaleImage(Image *image,
3443 ExceptionInfo *exception)
3462 assert(image != (Image *) NULL);
3463 assert(image->signature == MagickCoreSignature);
3464 if (image->type != GrayscaleType)
3465 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3466 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
3467 sizeof(*colormap_index));
3468 if (colormap_index == (ssize_t *) NULL)
3469 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3471 if (image->storage_class != PseudoClass)
3473 (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
3474 sizeof(*colormap_index));
3475 if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
3476 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3480 image_view=AcquireAuthenticCacheView(image,exception);
3481 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3482 #pragma omp parallel for schedule(static,4) shared(status) \
3483 magick_threads(image,image,image->rows,1)
3485 for (y=0; y < (ssize_t) image->rows; y++)
3493 if (status == MagickFalse)
3495 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3497 if (q == (Quantum *) NULL)
3502 for (x=0; x < (ssize_t) image->columns; x++)
3507 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3508 if (colormap_index[intensity] < 0)
3510 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3511 #pragma omp critical (MagickCore_SetGrayscaleImage)
3513 if (colormap_index[intensity] < 0)
3515 colormap_index[intensity]=(ssize_t) image->colors;
3516 image->colormap[image->colors].red=(double)
3517 GetPixelRed(image,q);
3518 image->colormap[image->colors].green=(double)
3519 GetPixelGreen(image,q);
3520 image->colormap[image->colors].blue=(double)
3521 GetPixelBlue(image,q);
3525 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3526 q+=GetPixelChannels(image);
3528 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3531 image_view=DestroyCacheView(image_view);
3533 for (i=0; i < (ssize_t) image->colors; i++)
3534 image->colormap[i].alpha=(double) i;
3535 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3537 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3538 if (colormap == (PixelInfo *) NULL)
3539 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3542 colormap[j]=image->colormap[0];
3543 for (i=0; i < (ssize_t) image->colors; i++)
3545 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3548 colormap[j]=image->colormap[i];
3550 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3552 image->colors=(size_t) (j+1);
3553 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3554 image->colormap=colormap;
3556 image_view=AcquireAuthenticCacheView(image,exception);
3557 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3558 #pragma omp parallel for schedule(static,4) shared(status) \
3559 magick_threads(image,image,image->rows,1)
3561 for (y=0; y < (ssize_t) image->rows; y++)
3569 if (status == MagickFalse)
3571 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3572 if (q == (Quantum *) NULL)
3577 for (x=0; x < (ssize_t) image->columns; x++)
3579 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3580 GetPixelIndex(image,q))],q);
3581 q+=GetPixelChannels(image);
3583 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3586 image_view=DestroyCacheView(image_view);
3587 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3588 image->type=GrayscaleType;
3589 if (SetImageMonochrome(image,exception) != MagickFalse)
3590 image->type=BilevelType;