2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
7 % Q Q U U A A NN N T I ZZ E %
8 % Q Q U U AAAAA N N N T I ZZZ EEEEE %
9 % Q QQ U U A A N NN T I ZZ E %
10 % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
13 % MagickCore Methods to Reduce the Number of Unique Colors in an Image %
20 % Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
28 % Unless required by applicable law or agreed to in writing, software %
29 % distributed under the License is distributed on an "AS IS" BASIS, %
30 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31 % See the License for the specific language governing permissions and %
32 % limitations under the License. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Realism in computer graphics typically requires using 24 bits/pixel to
37 % generate an image. Yet many graphic display devices do not contain the
38 % amount of memory necessary to match the spatial and color resolution of
39 % the human eye. The Quantize methods takes a 24 bit image and reduces
40 % the number of colors so it can be displayed on raster device with less
41 % bits per pixel. In most instances, the quantized image closely
42 % resembles the original reference image.
44 % A reduction of colors in an image is also desirable for image
45 % transmission and real-time animation.
47 % QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 % them down to some fixed number of colors.
50 % For purposes of color allocation, an image is a set of n pixels, where
51 % each pixel is a point in RGB space. RGB space is a 3-dimensional
52 % vector space, and each pixel, Pi, is defined by an ordered triple of
53 % red, green, and blue coordinates, (Ri, Gi, Bi).
55 % Each primary color component (red, green, or blue) represents an
56 % intensity which varies linearly from 0 to a maximum value, Cmax, which
57 % corresponds to full saturation of that color. Color allocation is
58 % defined over a domain consisting of the cube in RGB space with opposite
59 % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
62 % The algorithm maps this domain onto a tree in which each node
63 % represents a cube within that domain. In the following discussion
64 % these cubes are defined by the coordinate of two opposite vertices:
65 % The vertex nearest the origin in RGB space and the vertex farthest from
68 % The tree's root node represents the entire domain, (0,0,0) through
69 % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70 % subdividing one node's cube into eight smaller cubes of equal size.
71 % This corresponds to bisecting the parent cube with planes passing
72 % through the midpoints of each edge.
74 % The basic algorithm operates in three phases: Classification,
75 % Reduction, and Assignment. Classification builds a color description
76 % tree for the image. Reduction collapses the tree until the number it
77 % represents, at most, the number of colors desired in the output image.
78 % Assignment defines the output image's color map and sets each pixel's
79 % color by restorage_class in the reduced tree. Our goal is to minimize
80 % the numerical discrepancies between the original colors and quantized
81 % colors (quantization error).
83 % Classification begins by initializing a color description tree of
84 % sufficient depth to represent each possible input color in a leaf.
85 % However, it is impractical to generate a fully-formed color description
86 % tree in the storage_class phase for realistic values of Cmax. If
87 % colors components in the input image are quantized to k-bit precision,
88 % so that Cmax= 2k-1, the tree would need k levels below the root node to
89 % allow representing each possible input color in a leaf. This becomes
90 % prohibitive because the tree's total number of nodes is 1 +
93 % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94 % Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95 % Initializes data structures for nodes only as they are needed; (2)
96 % Chooses a maximum depth for the tree as a function of the desired
97 % number of colors in the output image (currently log2(colormap size)).
99 % For each pixel in the input image, storage_class scans downward from
100 % the root of the color description tree. At each level of the tree it
101 % identifies the single node which represents a cube in RGB space
102 % containing the pixel's color. It updates the following data for each
105 % n1: Number of pixels whose color is contained in the RGB cube which
106 % this node represents;
108 % n2: Number of pixels whose color is not represented in a node at
109 % lower depth in the tree; initially, n2 = 0 for all nodes except
110 % leaves of the tree.
112 % Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113 % pixels not classified at a lower depth. The combination of these sums
114 % and n2 will ultimately characterize the mean color of a set of
115 % pixels represented by this node.
117 % E: the distance squared in RGB space between each pixel contained
118 % within a node and the nodes' center. This represents the
119 % quantization error for a node.
121 % Reduction repeatedly prunes the tree until the number of nodes with n2
122 % > 0 is less than or equal to the maximum number of colors allowed in
123 % the output image. On any given iteration over the tree, it selects
124 % those nodes whose E count is minimal for pruning and merges their color
125 % statistics upward. It uses a pruning threshold, Ep, to govern node
126 % selection as follows:
129 % while number of nodes with (n2 > 0) > required maximum number of colors
130 % prune all nodes such that E <= Ep
131 % Set Ep to minimum E in remaining nodes
133 % This has the effect of minimizing any quantization error when merging
134 % two nodes together.
136 % When a node to be pruned has offspring, the pruning procedure invokes
137 % itself recursively in order to prune the tree from the leaves upward.
138 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
139 % corresponding data in that node's parent. This retains the pruned
140 % node's color characteristics for later averaging.
142 % For each node, n2 pixels exist for which that node represents the
143 % smallest volume in RGB space containing those pixel's colors. When n2
144 % > 0 the node will uniquely define a color in the output image. At the
145 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
146 % the tree which represent colors present in the input image.
148 % The other pixel count, n1, indicates the total number of colors within
149 % the cubic volume which the node represents. This includes n1 - n2
150 % pixels whose colors should be defined by nodes at a lower level in the
153 % Assignment generates the output image from the pruned tree. The output
154 % image consists of two parts: (1) A color map, which is an array of
155 % color descriptions (RGB triples) for each color present in the output
156 % image; (2) A pixel array, which represents each pixel as an index
157 % into the color map array.
159 % First, the assignment phase makes one pass over the pruned color
160 % description tree to establish the image's color map. For each node
161 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162 % color of all pixels that classify no lower than this node. Each of
163 % these colors becomes an entry in the color map.
165 % Finally, the assignment phase reclassifies each pixel in the pruned
166 % tree to identify the deepest node containing the pixel's color. The
167 % pixel's value in the pixel array becomes the index of this node's mean
168 % color in the color map.
170 % This method is based on a similar algorithm written by Paul Raveling.
175 Include declarations.
177 #include "MagickCore/studio.h"
178 #include "MagickCore/attribute.h"
179 #include "MagickCore/cache-view.h"
180 #include "MagickCore/color.h"
181 #include "MagickCore/color-private.h"
182 #include "MagickCore/colormap.h"
183 #include "MagickCore/colorspace.h"
184 #include "MagickCore/colorspace-private.h"
185 #include "MagickCore/enhance.h"
186 #include "MagickCore/exception.h"
187 #include "MagickCore/exception-private.h"
188 #include "MagickCore/histogram.h"
189 #include "MagickCore/image.h"
190 #include "MagickCore/image-private.h"
191 #include "MagickCore/list.h"
192 #include "MagickCore/memory_.h"
193 #include "MagickCore/monitor.h"
194 #include "MagickCore/monitor-private.h"
195 #include "MagickCore/option.h"
196 #include "MagickCore/pixel-accessor.h"
197 #include "MagickCore/pixel-private.h"
198 #include "MagickCore/quantize.h"
199 #include "MagickCore/quantum.h"
200 #include "MagickCore/quantum-private.h"
201 #include "MagickCore/resource_.h"
202 #include "MagickCore/string_.h"
203 #include "MagickCore/thread-private.h"
208 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
213 #define ErrorQueueLength 16
214 #define MaxNodes 266817
215 #define MaxTreeDepth 8
216 #define NodesInAList 1920
221 typedef struct _RealPixelInfo
230 typedef struct _NodeInfo
251 typedef struct _Nodes
260 typedef struct _CubeInfo
301 error[ErrorQueueLength];
304 weights[ErrorQueueLength];
330 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
333 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
335 static MagickBooleanType
336 AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
337 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
338 DitherImage(Image *,CubeInfo *,ExceptionInfo *),
339 SetGrayscaleImage(Image *,ExceptionInfo *);
342 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
345 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
346 DestroyCubeInfo(CubeInfo *),
347 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
348 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
349 ReduceImageColors(const Image *,CubeInfo *);
352 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
356 % A c q u i r e Q u a n t i z e I n f o %
360 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
362 % AcquireQuantizeInfo() allocates the QuantizeInfo structure.
364 % The format of the AcquireQuantizeInfo method is:
366 % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
368 % A description of each parameter follows:
370 % o image_info: the image info.
373 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
378 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
379 if (quantize_info == (QuantizeInfo *) NULL)
380 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
381 GetQuantizeInfo(quantize_info);
382 if (image_info != (ImageInfo *) NULL)
387 quantize_info->dither_method=image_info->dither == MagickFalse ?
388 NoDitherMethod : RiemersmaDitherMethod;
389 option=GetImageOption(image_info,"dither");
390 if (option != (const char *) NULL)
391 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
392 MagickDitherOptions,MagickFalse,option);
393 quantize_info->measure_error=image_info->verbose;
395 return(quantize_info);
399 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
403 + A s s i g n I m a g e C o l o r s %
407 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
409 % AssignImageColors() generates the output image from the pruned tree. The
410 % output image consists of two parts: (1) A color map, which is an array
411 % of color descriptions (RGB triples) for each color present in the
412 % output image; (2) A pixel array, which represents each pixel as an
413 % index into the color map array.
415 % First, the assignment phase makes one pass over the pruned color
416 % description tree to establish the image's color map. For each node
417 % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
418 % color of all pixels that classify no lower than this node. Each of
419 % these colors becomes an entry in the color map.
421 % Finally, the assignment phase reclassifies each pixel in the pruned
422 % tree to identify the deepest node containing the pixel's color. The
423 % pixel's value in the pixel array becomes the index of this node's mean
424 % color in the color map.
426 % The format of the AssignImageColors() method is:
428 % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
430 % A description of each parameter follows.
432 % o image: the image.
434 % o cube_info: A pointer to the Cube structure.
438 static inline void AssociateAlphaPixel(const Image *image,
439 const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
444 if ((cube_info->associate_alpha == MagickFalse) ||
445 (GetPixelAlpha(image,pixel)== OpaqueAlpha))
447 alpha_pixel->red=(double) GetPixelRed(image,pixel);
448 alpha_pixel->green=(double) GetPixelGreen(image,pixel);
449 alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
450 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
453 alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
454 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
455 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
456 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
457 alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
460 static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
461 const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
466 if ((cube_info->associate_alpha == MagickFalse) ||
467 (pixel->alpha == OpaqueAlpha))
469 alpha_pixel->red=(double) pixel->red;
470 alpha_pixel->green=(double) pixel->green;
471 alpha_pixel->blue=(double) pixel->blue;
472 alpha_pixel->alpha=(double) pixel->alpha;
475 alpha=(double) (QuantumScale*pixel->alpha);
476 alpha_pixel->red=alpha*pixel->red;
477 alpha_pixel->green=alpha*pixel->green;
478 alpha_pixel->blue=alpha*pixel->blue;
479 alpha_pixel->alpha=(double) pixel->alpha;
482 static inline Quantum ClampPixel(const MagickRealType value)
486 if (value >= (MagickRealType) QuantumRange)
487 return((Quantum) QuantumRange);
488 #if !defined(MAGICKCORE_HDRI_SUPPORT)
489 return((Quantum) (value+0.5f));
495 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
496 const RealPixelInfo *pixel,size_t index)
501 id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
502 ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
503 ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
504 if (cube_info->associate_alpha != MagickFalse)
505 id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
509 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
510 ExceptionInfo *exception)
512 #define AssignImageTag "Assign/Image"
518 Allocate image colormap.
520 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
521 (cube_info->quantize_info->colorspace != CMYKColorspace))
522 (void) TransformImageColorspace((Image *) image,
523 cube_info->quantize_info->colorspace,exception);
525 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
526 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
527 if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
528 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
531 cube_info->transparent_pixels=0;
532 cube_info->transparent_index=(-1);
533 (void) DefineImageColormap(image,cube_info,cube_info->root);
535 Create a reduced color image.
537 if ((cube_info->quantize_info->dither_method != NoDitherMethod) &&
538 (cube_info->quantize_info->dither_method != NoDitherMethod))
539 (void) DitherImage(image,cube_info,exception);
549 image_view=AcquireAuthenticCacheView(image,exception);
550 #if defined(MAGICKCORE_OPENMP_SUPPORT)
551 #pragma omp parallel for schedule(static,4) shared(status) \
552 magick_threads(image,image,image->rows,1)
554 for (y=0; y < (ssize_t) image->rows; y++)
568 if (status == MagickFalse)
570 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
572 if (q == (Quantum *) NULL)
578 for (x=0; x < (ssize_t) image->columns; x+=count)
583 register const NodeInfo
594 Identify the deepest node containing the pixel's color.
596 for (count=1; (x+count) < (ssize_t) image->columns; count++)
601 GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
602 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
605 AssociateAlphaPixel(image,&cube,q,&pixel);
607 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
609 id=ColorToNodeId(&cube,&pixel,index);
610 if (node_info->child[id] == (NodeInfo *) NULL)
612 node_info=node_info->child[id];
615 Find closest color among siblings and their children.
618 cube.distance=(double) (4.0*(QuantumRange+1.0)*
619 (QuantumRange+1.0)+1.0);
620 ClosestColor(image,&cube,node_info->parent);
621 index=cube.color_number;
622 for (i=0; i < (ssize_t) count; i++)
624 if (image->storage_class == PseudoClass)
625 SetPixelIndex(image,(Quantum) index,q);
626 if (cube.quantize_info->measure_error == MagickFalse)
628 SetPixelRed(image,ClampToQuantum(
629 image->colormap[index].red),q);
630 SetPixelGreen(image,ClampToQuantum(
631 image->colormap[index].green),q);
632 SetPixelBlue(image,ClampToQuantum(
633 image->colormap[index].blue),q);
634 if (cube.associate_alpha != MagickFalse)
635 SetPixelAlpha(image,ClampToQuantum(
636 image->colormap[index].alpha),q);
638 q+=GetPixelChannels(image);
641 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
643 if (image->progress_monitor != (MagickProgressMonitor) NULL)
648 #if defined(MAGICKCORE_OPENMP_SUPPORT)
649 #pragma omp critical (MagickCore_AssignImageColors)
651 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
653 if (proceed == MagickFalse)
657 image_view=DestroyCacheView(image_view);
659 if (cube_info->quantize_info->measure_error != MagickFalse)
660 (void) GetImageQuantizeError(image,exception);
661 if ((cube_info->quantize_info->number_colors == 2) &&
662 (cube_info->quantize_info->colorspace == GRAYColorspace))
677 for (i=0; i < (ssize_t) image->colors; i++)
679 intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
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++)
858 id=ColorToNodeId(cube_info,&pixel,index);
859 mid.red+=(id & 1) != 0 ? bisect : -bisect;
860 mid.green+=(id & 2) != 0 ? bisect : -bisect;
861 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
862 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
863 if (node_info->child[id] == (NodeInfo *) NULL)
866 Set colors of new node to contain pixel.
868 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
869 if (node_info->child[id] == (NodeInfo *) NULL)
871 (void) ThrowMagickException(exception,GetMagickModule(),
872 ResourceLimitError,"MemoryAllocationFailed","`%s'",
876 if (level == MaxTreeDepth)
880 Approximate the quantization error represented by this node.
882 node_info=node_info->child[id];
883 error.red=QuantumScale*(pixel.red-mid.red);
884 error.green=QuantumScale*(pixel.green-mid.green);
885 error.blue=QuantumScale*(pixel.blue-mid.blue);
886 if (cube_info->associate_alpha != MagickFalse)
887 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
888 node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
889 error.green*error.green+error.blue*error.blue+
890 error.alpha*error.alpha));
891 cube_info->root->quantize_error+=node_info->quantize_error;
895 Sum RGB for this leaf for later derivation of the mean cube color.
897 node_info->number_unique+=count;
898 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
899 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
900 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
901 if (cube_info->associate_alpha != MagickFalse)
902 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
904 p+=count*GetPixelChannels(image);
906 if (cube_info->colors > cube_info->maximum_colors)
908 PruneToCubeDepth(image,cube_info,cube_info->root);
911 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
913 if (proceed == MagickFalse)
916 for (y++; y < (ssize_t) image->rows; y++)
918 register const Quantum
924 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
925 if (p == (const Quantum *) NULL)
927 if (cube_info->nodes > MaxNodes)
930 Prune one level if the color tree is too large.
932 PruneLevel(image,cube_info,cube_info->root);
935 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
938 Start at the root and descend the color cube tree.
940 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
945 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
946 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
949 AssociateAlphaPixel(image,cube_info,p,&pixel);
950 index=MaxTreeDepth-1;
951 bisect=((double) QuantumRange+1.0)/2.0;
953 node_info=cube_info->root;
954 for (level=1; level <= cube_info->depth; level++)
957 id=ColorToNodeId(cube_info,&pixel,index);
958 mid.red+=(id & 1) != 0 ? bisect : -bisect;
959 mid.green+=(id & 2) != 0 ? bisect : -bisect;
960 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
961 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
962 if (node_info->child[id] == (NodeInfo *) NULL)
965 Set colors of new node to contain pixel.
967 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
968 if (node_info->child[id] == (NodeInfo *) NULL)
970 (void) ThrowMagickException(exception,GetMagickModule(),
971 ResourceLimitError,"MemoryAllocationFailed","%s",
975 if (level == cube_info->depth)
979 Approximate the quantization error represented by this node.
981 node_info=node_info->child[id];
982 error.red=QuantumScale*(pixel.red-mid.red);
983 error.green=QuantumScale*(pixel.green-mid.green);
984 error.blue=QuantumScale*(pixel.blue-mid.blue);
985 if (cube_info->associate_alpha != MagickFalse)
986 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
987 node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
988 error.green*error.green+error.blue*error.blue+
989 error.alpha*error.alpha));
990 cube_info->root->quantize_error+=node_info->quantize_error;
994 Sum RGB for this leaf for later derivation of the mean cube color.
996 node_info->number_unique+=count;
997 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
998 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
999 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
1000 if (cube_info->associate_alpha != MagickFalse)
1001 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
1003 p+=count*GetPixelChannels(image);
1005 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1007 if (proceed == MagickFalse)
1010 image_view=DestroyCacheView(image_view);
1011 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1012 (cube_info->quantize_info->colorspace != CMYKColorspace))
1013 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1014 return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1018 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1022 % C l o n e Q u a n t i z e I n f o %
1026 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1028 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1029 % or if quantize info is NULL, a new one.
1031 % The format of the CloneQuantizeInfo method is:
1033 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1035 % A description of each parameter follows:
1037 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1038 % quantize info, or if image info is NULL a new one.
1040 % o quantize_info: a structure of type info.
1043 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1048 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1049 if (clone_info == (QuantizeInfo *) NULL)
1050 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1051 GetQuantizeInfo(clone_info);
1052 if (quantize_info == (QuantizeInfo *) NULL)
1054 clone_info->number_colors=quantize_info->number_colors;
1055 clone_info->tree_depth=quantize_info->tree_depth;
1056 clone_info->dither_method=quantize_info->dither_method;
1057 clone_info->colorspace=quantize_info->colorspace;
1058 clone_info->measure_error=quantize_info->measure_error;
1063 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1067 + C l o s e s t C o l o r %
1071 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1073 % ClosestColor() traverses the color cube tree at a particular node and
1074 % determines which colormap entry best represents the input color.
1076 % The format of the ClosestColor method is:
1078 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1079 % const NodeInfo *node_info)
1081 % A description of each parameter follows.
1083 % o image: the image.
1085 % o cube_info: A pointer to the Cube structure.
1087 % o node_info: the address of a structure of type NodeInfo which points to a
1088 % node in the color cube tree that is to be pruned.
1091 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1092 const NodeInfo *node_info)
1101 Traverse any children.
1103 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1104 for (i=0; i < (ssize_t) number_children; i++)
1105 if (node_info->child[i] != (NodeInfo *) NULL)
1106 ClosestColor(image,cube_info,node_info->child[i]);
1107 if (node_info->number_unique != 0)
1120 register RealPixelInfo
1124 Determine if this color is "closest".
1126 p=image->colormap+node_info->color_number;
1127 q=(&cube_info->target);
1130 if (cube_info->associate_alpha != MagickFalse)
1132 alpha=(double) (QuantumScale*p->alpha);
1133 beta=(double) (QuantumScale*q->alpha);
1135 pixel=alpha*p->red-beta*q->red;
1136 distance=pixel*pixel;
1137 if (distance <= cube_info->distance)
1139 pixel=alpha*p->green-beta*q->green;
1140 distance+=pixel*pixel;
1141 if (distance <= cube_info->distance)
1143 pixel=alpha*p->blue-beta*q->blue;
1144 distance+=pixel*pixel;
1145 if (distance <= cube_info->distance)
1148 distance+=pixel*pixel;
1149 if (distance <= cube_info->distance)
1151 cube_info->distance=distance;
1152 cube_info->color_number=node_info->color_number;
1161 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1165 % C o m p r e s s I m a g e C o l o r m a p %
1169 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1171 % CompressImageColormap() compresses an image colormap by removing any
1172 % duplicate or unused color entries.
1174 % The format of the CompressImageColormap method is:
1176 % MagickBooleanType CompressImageColormap(Image *image,
1177 % ExceptionInfo *exception)
1179 % A description of each parameter follows:
1181 % o image: the image.
1183 % o exception: return any errors or warnings in this structure.
1186 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1187 ExceptionInfo *exception)
1192 assert(image != (Image *) NULL);
1193 assert(image->signature == MagickSignature);
1194 if (image->debug != MagickFalse)
1195 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1196 if (IsPaletteImage(image,exception) == MagickFalse)
1197 return(MagickFalse);
1198 GetQuantizeInfo(&quantize_info);
1199 quantize_info.number_colors=image->colors;
1200 quantize_info.tree_depth=MaxTreeDepth;
1201 return(QuantizeImage(&quantize_info,image,exception));
1205 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1209 + D e f i n e I m a g e C o l o r m a p %
1213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1215 % DefineImageColormap() traverses the color cube tree and notes each colormap
1216 % entry. A colormap entry is any node in the color cube tree where the
1217 % of unique colors is not zero. DefineImageColormap() returns the number of
1218 % colors in the image colormap.
1220 % The format of the DefineImageColormap method is:
1222 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1223 % NodeInfo *node_info)
1225 % A description of each parameter follows.
1227 % o image: the image.
1229 % o cube_info: A pointer to the Cube structure.
1231 % o node_info: the address of a structure of type NodeInfo which points to a
1232 % node in the color cube tree that is to be pruned.
1235 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1236 NodeInfo *node_info)
1245 Traverse any children.
1247 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1248 for (i=0; i < (ssize_t) number_children; i++)
1249 if (node_info->child[i] != (NodeInfo *) NULL)
1250 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1251 if (node_info->number_unique != 0)
1260 Colormap entry is defined by the mean color in this cube.
1262 q=image->colormap+image->colors;
1263 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1264 alpha=PerceptibleReciprocal(alpha);
1265 if (cube_info->associate_alpha == MagickFalse)
1267 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1268 node_info->total_color.red);
1269 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1270 node_info->total_color.green);
1271 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1272 node_info->total_color.blue);
1273 q->alpha=(double) OpaqueAlpha;
1280 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1281 q->alpha=(double) ClampToQuantum((opacity));
1282 if (q->alpha == OpaqueAlpha)
1284 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1285 node_info->total_color.red);
1286 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1287 node_info->total_color.green);
1288 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1289 node_info->total_color.blue);
1296 gamma=(double) (QuantumScale*q->alpha);
1297 gamma=PerceptibleReciprocal(gamma);
1298 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1299 node_info->total_color.red);
1300 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1301 node_info->total_color.green);
1302 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1303 node_info->total_color.blue);
1304 if (node_info->number_unique > cube_info->transparent_pixels)
1306 cube_info->transparent_pixels=node_info->number_unique;
1307 cube_info->transparent_index=(ssize_t) image->colors;
1311 node_info->color_number=image->colors++;
1313 return(image->colors);
1317 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1321 + D e s t r o y C u b e I n f o %
1325 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1327 % DestroyCubeInfo() deallocates memory associated with an image.
1329 % The format of the DestroyCubeInfo method is:
1331 % DestroyCubeInfo(CubeInfo *cube_info)
1333 % A description of each parameter follows:
1335 % o cube_info: the address of a structure of type CubeInfo.
1338 static void DestroyCubeInfo(CubeInfo *cube_info)
1344 Release color cube tree storage.
1348 nodes=cube_info->node_queue->next;
1349 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1350 cube_info->node_queue->nodes);
1351 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1352 cube_info->node_queue);
1353 cube_info->node_queue=nodes;
1354 } while (cube_info->node_queue != (Nodes *) NULL);
1355 if (cube_info->memory_info != (MemoryInfo *) NULL)
1356 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1357 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1358 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1362 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1366 % D e s t r o y Q u a n t i z e I n f o %
1370 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1372 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1375 % The format of the DestroyQuantizeInfo method is:
1377 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1379 % A description of each parameter follows:
1381 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1384 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1386 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1387 assert(quantize_info != (QuantizeInfo *) NULL);
1388 assert(quantize_info->signature == MagickSignature);
1389 quantize_info->signature=(~MagickSignature);
1390 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1391 return(quantize_info);
1395 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1399 + D i t h e r I m a g e %
1403 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1405 % DitherImage() distributes the difference between an original image and
1406 % the corresponding color reduced algorithm to neighboring pixels using
1407 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1408 % MagickTrue if the image is dithered otherwise MagickFalse.
1410 % The format of the DitherImage method is:
1412 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1413 % ExceptionInfo *exception)
1415 % A description of each parameter follows.
1417 % o image: the image.
1419 % o cube_info: A pointer to the Cube structure.
1421 % o exception: return any errors or warnings in this structure.
1425 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1430 assert(pixels != (RealPixelInfo **) NULL);
1431 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1432 if (pixels[i] != (RealPixelInfo *) NULL)
1433 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1434 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1438 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1449 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1450 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1452 if (pixels == (RealPixelInfo **) NULL)
1453 return((RealPixelInfo **) NULL);
1454 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1455 for (i=0; i < (ssize_t) number_threads; i++)
1457 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1458 if (pixels[i] == (RealPixelInfo *) NULL)
1459 return(DestroyPixelThreadSet(pixels));
1464 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1465 const RealPixelInfo *pixel)
1467 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1468 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1469 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1470 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1475 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1476 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1477 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1478 if (cube_info->associate_alpha != MagickFalse)
1479 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1483 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1484 ExceptionInfo *exception)
1486 #define DitherImageTag "Dither/Image"
1501 Distribute quantization error using Floyd-Steinberg.
1503 pixels=AcquirePixelThreadSet(image->columns);
1504 if (pixels == (RealPixelInfo **) NULL)
1505 return(MagickFalse);
1507 image_view=AcquireAuthenticCacheView(image,exception);
1508 for (y=0; y < (ssize_t) image->rows; y++)
1511 id = GetOpenMPThreadId();
1532 if (status == MagickFalse)
1534 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1535 if (q == (Quantum *) NULL)
1540 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
1542 current=pixels[id]+(y & 0x01)*image->columns;
1543 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1544 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1545 for (x=0; x < (ssize_t) image->columns; x++)
1557 q-=(y & 0x01)*GetPixelChannels(image);
1558 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1559 AssociateAlphaPixel(image,&cube,q,&pixel);
1562 pixel.red+=7*current[u-v].red/16;
1563 pixel.green+=7*current[u-v].green/16;
1564 pixel.blue+=7*current[u-v].blue/16;
1565 if (cube.associate_alpha != MagickFalse)
1566 pixel.alpha+=7*current[u-v].alpha/16;
1570 if (x < (ssize_t) (image->columns-1))
1572 pixel.red+=previous[u+v].red/16;
1573 pixel.green+=previous[u+v].green/16;
1574 pixel.blue+=previous[u+v].blue/16;
1575 if (cube.associate_alpha != MagickFalse)
1576 pixel.alpha+=previous[u+v].alpha/16;
1578 pixel.red+=5*previous[u].red/16;
1579 pixel.green+=5*previous[u].green/16;
1580 pixel.blue+=5*previous[u].blue/16;
1581 if (cube.associate_alpha != MagickFalse)
1582 pixel.alpha+=5*previous[u].alpha/16;
1585 pixel.red+=3*previous[u-v].red/16;
1586 pixel.green+=3*previous[u-v].green/16;
1587 pixel.blue+=3*previous[u-v].blue/16;
1588 if (cube.associate_alpha != MagickFalse)
1589 pixel.alpha+=3*previous[u-v].alpha/16;
1592 pixel.red=(double) ClampPixel(pixel.red);
1593 pixel.green=(double) ClampPixel(pixel.green);
1594 pixel.blue=(double) ClampPixel(pixel.blue);
1595 if (cube.associate_alpha != MagickFalse)
1596 pixel.alpha=(double) ClampPixel(pixel.alpha);
1597 i=CacheOffset(&cube,&pixel);
1598 if (cube.cache[i] < 0)
1607 Identify the deepest node containing the pixel's color.
1609 node_info=cube.root;
1610 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1612 id=ColorToNodeId(&cube,&pixel,index);
1613 if (node_info->child[id] == (NodeInfo *) NULL)
1615 node_info=node_info->child[id];
1618 Find closest color among siblings and their children.
1621 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1623 ClosestColor(image,&cube,node_info->parent);
1624 cube.cache[i]=(ssize_t) cube.color_number;
1627 Assign pixel to closest colormap entry.
1629 index=(size_t) cube.cache[i];
1630 if (image->storage_class == PseudoClass)
1631 SetPixelIndex(image,(Quantum) index,q);
1632 if (cube.quantize_info->measure_error == MagickFalse)
1634 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1635 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1636 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1637 if (cube.associate_alpha != MagickFalse)
1638 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1640 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1645 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1646 current[u].red=pixel.red-color.red;
1647 current[u].green=pixel.green-color.green;
1648 current[u].blue=pixel.blue-color.blue;
1649 if (cube.associate_alpha != MagickFalse)
1650 current[u].alpha=pixel.alpha-color.alpha;
1651 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1656 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1657 #pragma omp critical (MagickCore_FloydSteinbergDither)
1659 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1661 if (proceed == MagickFalse)
1664 q+=((y+1) & 0x01)*GetPixelChannels(image);
1667 image_view=DestroyCacheView(image_view);
1668 pixels=DestroyPixelThreadSet(pixels);
1672 static MagickBooleanType
1673 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1674 ExceptionInfo *exception);
1676 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1677 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1684 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1686 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1688 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1694 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1696 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1698 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1704 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1714 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1716 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1718 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1730 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1732 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1734 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1736 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1738 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1740 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1742 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1748 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1750 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1752 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1754 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1756 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1758 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1760 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1766 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1768 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1770 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1772 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1774 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1776 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1778 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1784 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1786 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1788 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1790 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1792 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1794 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1796 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1805 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1806 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1808 #define DitherImageTag "Dither/Image"
1824 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1825 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1836 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1837 if (q == (Quantum *) NULL)
1838 return(MagickFalse);
1839 AssociateAlphaPixel(image,cube_info,q,&pixel);
1840 for (i=0; i < ErrorQueueLength; i++)
1842 pixel.red+=p->weights[i]*p->error[i].red;
1843 pixel.green+=p->weights[i]*p->error[i].green;
1844 pixel.blue+=p->weights[i]*p->error[i].blue;
1845 if (cube_info->associate_alpha != MagickFalse)
1846 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1848 pixel.red=(double) ClampPixel(pixel.red);
1849 pixel.green=(double) ClampPixel(pixel.green);
1850 pixel.blue=(double) ClampPixel(pixel.blue);
1851 if (cube_info->associate_alpha != MagickFalse)
1852 pixel.alpha=(double) ClampPixel(pixel.alpha);
1853 i=CacheOffset(cube_info,&pixel);
1854 if (p->cache[i] < 0)
1863 Identify the deepest node containing the pixel's color.
1866 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1868 id=ColorToNodeId(cube_info,&pixel,index);
1869 if (node_info->child[id] == (NodeInfo *) NULL)
1871 node_info=node_info->child[id];
1874 Find closest color among siblings and their children.
1877 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1878 QuantumRange+1.0)+1.0);
1879 ClosestColor(image,p,node_info->parent);
1880 p->cache[i]=(ssize_t) p->color_number;
1883 Assign pixel to closest colormap entry.
1885 index=(size_t) p->cache[i];
1886 if (image->storage_class == PseudoClass)
1887 SetPixelIndex(image,(Quantum) index,q);
1888 if (cube_info->quantize_info->measure_error == MagickFalse)
1890 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1891 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1892 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1893 if (cube_info->associate_alpha != MagickFalse)
1894 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1896 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1897 return(MagickFalse);
1899 Propagate the error as the last entry of the error queue.
1901 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1902 sizeof(p->error[0]));
1903 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1904 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1905 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1906 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1907 if (cube_info->associate_alpha != MagickFalse)
1908 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1909 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1910 if (proceed == MagickFalse)
1911 return(MagickFalse);
1916 case WestGravity: p->x--; break;
1917 case EastGravity: p->x++; break;
1918 case NorthGravity: p->y--; break;
1919 case SouthGravity: p->y++; break;
1924 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1931 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1938 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1939 ExceptionInfo *exception)
1953 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1954 return(FloydSteinbergDither(image,cube_info,exception));
1956 Distribute quantization error along a Hilbert curve.
1958 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1959 sizeof(*cube_info->error));
1962 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1963 for (depth=1; i != 0; depth++)
1965 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1967 cube_info->offset=0;
1968 cube_info->span=(MagickSizeType) image->columns*image->rows;
1969 image_view=AcquireAuthenticCacheView(image,exception);
1971 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1972 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1973 image_view=DestroyCacheView(image_view);
1978 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1982 + G e t C u b e I n f o %
1986 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1988 % GetCubeInfo() initialize the Cube data structure.
1990 % The format of the GetCubeInfo method is:
1992 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1993 % const size_t depth,const size_t maximum_colors)
1995 % A description of each parameter follows.
1997 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1999 % o depth: Normally, this integer value is zero or one. A zero or
2000 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
2001 % A tree of this depth generally allows the best representation of the
2002 % reference image with the least amount of memory and the fastest
2003 % computational speed. In some cases, such as an image with low color
2004 % dispersion (a few number of colors), a value other than
2005 % Log4(number_colors) is required. To expand the color tree completely,
2008 % o maximum_colors: maximum colors.
2011 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2012 const size_t depth,const size_t maximum_colors)
2028 Initialize tree to describe color cube_info.
2030 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2031 if (cube_info == (CubeInfo *) NULL)
2032 return((CubeInfo *) NULL);
2033 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2034 cube_info->depth=depth;
2035 if (cube_info->depth > MaxTreeDepth)
2036 cube_info->depth=MaxTreeDepth;
2037 if (cube_info->depth < 2)
2039 cube_info->maximum_colors=maximum_colors;
2041 Initialize root node.
2043 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2044 if (cube_info->root == (NodeInfo *) NULL)
2045 return((CubeInfo *) NULL);
2046 cube_info->root->parent=cube_info->root;
2047 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2048 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2051 Initialize dither resources.
2053 length=(size_t) (1UL << (4*(8-CacheShift)));
2054 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2055 if (cube_info->memory_info == (MemoryInfo *) NULL)
2056 return((CubeInfo *) NULL);
2057 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2059 Initialize color cache.
2061 for (i=0; i < (ssize_t) length; i++)
2062 cube_info->cache[i]=(-1);
2064 Distribute weights along a curve of exponential decay.
2067 for (i=0; i < ErrorQueueLength; i++)
2069 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2070 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2073 Normalize the weighting factors.
2076 for (i=0; i < ErrorQueueLength; i++)
2077 weight+=cube_info->weights[i];
2079 for (i=0; i < ErrorQueueLength; i++)
2081 cube_info->weights[i]/=weight;
2082 sum+=cube_info->weights[i];
2084 cube_info->weights[0]+=1.0-sum;
2089 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2093 + G e t N o d e I n f o %
2097 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2099 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2100 % presets all fields to zero.
2102 % The format of the GetNodeInfo method is:
2104 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2105 % const size_t level,NodeInfo *parent)
2107 % A description of each parameter follows.
2109 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2111 % o id: Specifies the child number of the node.
2113 % o level: Specifies the level in the storage_class the node resides.
2116 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2117 const size_t level,NodeInfo *parent)
2122 if (cube_info->free_nodes == 0)
2128 Allocate a new queue of nodes.
2130 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2131 if (nodes == (Nodes *) NULL)
2132 return((NodeInfo *) NULL);
2133 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2134 sizeof(*nodes->nodes));
2135 if (nodes->nodes == (NodeInfo *) NULL)
2136 return((NodeInfo *) NULL);
2137 nodes->next=cube_info->node_queue;
2138 cube_info->node_queue=nodes;
2139 cube_info->next_node=nodes->nodes;
2140 cube_info->free_nodes=NodesInAList;
2143 cube_info->free_nodes--;
2144 node_info=cube_info->next_node++;
2145 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2146 node_info->parent=parent;
2148 node_info->level=level;
2153 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2157 % G e t I m a g e Q u a n t i z e E r r o r %
2161 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2163 % GetImageQuantizeError() measures the difference between the original
2164 % and quantized images. This difference is the total quantization error.
2165 % The error is computed by summing over all pixels in an image the distance
2166 % squared in RGB space between each reference pixel value and its quantized
2167 % value. These values are computed:
2169 % o mean_error_per_pixel: This value is the mean error for any single
2170 % pixel in the image.
2172 % o normalized_mean_square_error: This value is the normalized mean
2173 % quantization error for any single pixel in the image. This distance
2174 % measure is normalized to a range between 0 and 1. It is independent
2175 % of the range of red, green, and blue values in the image.
2177 % o normalized_maximum_square_error: Thsi value is the normalized
2178 % maximum quantization error for any single pixel in the image. This
2179 % distance measure is normalized to a range between 0 and 1. It is
2180 % independent of the range of red, green, and blue values in your image.
2182 % The format of the GetImageQuantizeError method is:
2184 % MagickBooleanType GetImageQuantizeError(Image *image,
2185 % ExceptionInfo *exception)
2187 % A description of each parameter follows.
2189 % o image: the image.
2191 % o exception: return any errors or warnings in this structure.
2194 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2195 ExceptionInfo *exception)
2207 mean_error_per_pixel;
2215 assert(image != (Image *) NULL);
2216 assert(image->signature == MagickSignature);
2217 if (image->debug != MagickFalse)
2218 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2219 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2220 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2221 if (image->storage_class == DirectClass)
2225 area=3.0*image->columns*image->rows;
2227 mean_error_per_pixel=0.0;
2229 image_view=AcquireVirtualCacheView(image,exception);
2230 for (y=0; y < (ssize_t) image->rows; y++)
2232 register const Quantum
2238 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2239 if (p == (const Quantum *) NULL)
2241 for (x=0; x < (ssize_t) image->columns; x++)
2243 index=1UL*GetPixelIndex(image,p);
2244 if (image->alpha_trait == BlendPixelTrait)
2246 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2247 beta=(double) (QuantumScale*image->colormap[index].alpha);
2249 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2250 image->colormap[index].red);
2251 mean_error_per_pixel+=distance;
2252 mean_error+=distance*distance;
2253 if (distance > maximum_error)
2254 maximum_error=distance;
2255 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2256 image->colormap[index].green);
2257 mean_error_per_pixel+=distance;
2258 mean_error+=distance*distance;
2259 if (distance > maximum_error)
2260 maximum_error=distance;
2261 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2262 image->colormap[index].blue);
2263 mean_error_per_pixel+=distance;
2264 mean_error+=distance*distance;
2265 if (distance > maximum_error)
2266 maximum_error=distance;
2267 p+=GetPixelChannels(image);
2270 image_view=DestroyCacheView(image_view);
2271 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2272 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2274 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2279 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2283 % G e t Q u a n t i z e I n f o %
2287 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2289 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2291 % The format of the GetQuantizeInfo method is:
2293 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2295 % A description of each parameter follows:
2297 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2300 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2302 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2303 assert(quantize_info != (QuantizeInfo *) NULL);
2304 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2305 quantize_info->number_colors=256;
2306 quantize_info->dither_method=RiemersmaDitherMethod;
2307 quantize_info->colorspace=UndefinedColorspace;
2308 quantize_info->measure_error=MagickFalse;
2309 quantize_info->signature=MagickSignature;
2313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2317 % P o s t e r i z e I m a g e %
2321 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2323 % PosterizeImage() reduces the image to a limited number of colors for a
2326 % The format of the PosterizeImage method is:
2328 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2329 % const DitherMethod dither_method,ExceptionInfo *exception)
2331 % A description of each parameter follows:
2333 % o image: Specifies a pointer to an Image structure.
2335 % o levels: Number of color levels allowed in each channel. Very low values
2336 % (2, 3, or 4) have the most visible effect.
2338 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2339 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2341 % o exception: return any errors or warnings in this structure.
2345 static inline double MagickRound(double x)
2348 Round the fraction to nearest integer.
2350 if ((x-floor(x)) < (ceil(x)-x))
2355 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2356 const DitherMethod dither_method,ExceptionInfo *exception)
2358 #define PosterizeImageTag "Posterize/Image"
2359 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2360 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2380 assert(image != (Image *) NULL);
2381 assert(image->signature == MagickSignature);
2382 if (image->debug != MagickFalse)
2383 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2384 if (image->storage_class == PseudoClass)
2385 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2386 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2387 magick_threads(image,image,1,1)
2389 for (i=0; i < (ssize_t) image->colors; i++)
2394 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2395 image->colormap[i].red=(double)
2396 PosterizePixel(image->colormap[i].red);
2397 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2398 image->colormap[i].green=(double)
2399 PosterizePixel(image->colormap[i].green);
2400 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2401 image->colormap[i].blue=(double)
2402 PosterizePixel(image->colormap[i].blue);
2403 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2404 image->colormap[i].alpha=(double)
2405 PosterizePixel(image->colormap[i].alpha);
2412 image_view=AcquireAuthenticCacheView(image,exception);
2413 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2414 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2415 magick_threads(image,image,image->rows,1)
2417 for (y=0; y < (ssize_t) image->rows; y++)
2425 if (status == MagickFalse)
2427 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2428 if (q == (Quantum *) NULL)
2433 for (x=0; x < (ssize_t) image->columns; x++)
2435 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2436 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2437 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2438 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2439 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2440 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2441 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2442 (image->colorspace == CMYKColorspace))
2443 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2444 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2445 (image->alpha_trait == BlendPixelTrait))
2446 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2447 q+=GetPixelChannels(image);
2449 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2451 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2456 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2457 #pragma omp critical (MagickCore_PosterizeImage)
2459 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2461 if (proceed == MagickFalse)
2465 image_view=DestroyCacheView(image_view);
2466 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2467 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2468 levels,MaxColormapSize+1);
2469 quantize_info->dither_method=dither_method;
2470 quantize_info->tree_depth=MaxTreeDepth;
2471 status=QuantizeImage(quantize_info,image,exception);
2472 quantize_info=DestroyQuantizeInfo(quantize_info);
2477 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2481 + P r u n e C h i l d %
2485 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2487 % PruneChild() deletes the given node and merges its statistics into its
2490 % The format of the PruneSubtree method is:
2492 % PruneChild(const Image *image,CubeInfo *cube_info,
2493 % const NodeInfo *node_info)
2495 % A description of each parameter follows.
2497 % o image: the image.
2499 % o cube_info: A pointer to the Cube structure.
2501 % o node_info: pointer to node in color cube tree that is to be pruned.
2504 static void PruneChild(const Image *image,CubeInfo *cube_info,
2505 const NodeInfo *node_info)
2517 Traverse any children.
2519 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2520 for (i=0; i < (ssize_t) number_children; i++)
2521 if (node_info->child[i] != (NodeInfo *) NULL)
2522 PruneChild(image,cube_info,node_info->child[i]);
2524 Merge color statistics into parent.
2526 parent=node_info->parent;
2527 parent->number_unique+=node_info->number_unique;
2528 parent->total_color.red+=node_info->total_color.red;
2529 parent->total_color.green+=node_info->total_color.green;
2530 parent->total_color.blue+=node_info->total_color.blue;
2531 parent->total_color.alpha+=node_info->total_color.alpha;
2532 parent->child[node_info->id]=(NodeInfo *) NULL;
2537 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2541 + P r u n e L e v e l %
2545 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2547 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2548 % their color statistics into their parent node.
2550 % The format of the PruneLevel method is:
2552 % PruneLevel(const Image *image,CubeInfo *cube_info,
2553 % const NodeInfo *node_info)
2555 % A description of each parameter follows.
2557 % o image: the image.
2559 % o cube_info: A pointer to the Cube structure.
2561 % o node_info: pointer to node in color cube tree that is to be pruned.
2564 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2565 const NodeInfo *node_info)
2574 Traverse any children.
2576 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2577 for (i=0; i < (ssize_t) number_children; i++)
2578 if (node_info->child[i] != (NodeInfo *) NULL)
2579 PruneLevel(image,cube_info,node_info->child[i]);
2580 if (node_info->level == cube_info->depth)
2581 PruneChild(image,cube_info,node_info);
2585 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2589 + P r u n e T o C u b e D e p t h %
2593 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2595 % PruneToCubeDepth() deletes any nodes at a depth greater than
2596 % cube_info->depth while merging their color statistics into their parent
2599 % The format of the PruneToCubeDepth method is:
2601 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2602 % const NodeInfo *node_info)
2604 % A description of each parameter follows.
2606 % o cube_info: A pointer to the Cube structure.
2608 % o node_info: pointer to node in color cube tree that is to be pruned.
2611 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2612 const NodeInfo *node_info)
2621 Traverse any children.
2623 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2624 for (i=0; i < (ssize_t) number_children; i++)
2625 if (node_info->child[i] != (NodeInfo *) NULL)
2626 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2627 if (node_info->level > cube_info->depth)
2628 PruneChild(image,cube_info,node_info);
2632 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2636 % Q u a n t i z e I m a g e %
2640 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2642 % QuantizeImage() analyzes the colors within a reference image and chooses a
2643 % fixed number of colors to represent the image. The goal of the algorithm
2644 % is to minimize the color difference between the input and output image while
2645 % minimizing the processing time.
2647 % The format of the QuantizeImage method is:
2649 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2650 % Image *image,ExceptionInfo *exception)
2652 % A description of each parameter follows:
2654 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2656 % o image: the image.
2658 % o exception: return any errors or warnings in this structure.
2662 static MagickBooleanType DirectToColormapImage(Image *image,
2663 ExceptionInfo *exception)
2681 number_colors=(size_t) (image->columns*image->rows);
2682 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2683 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2685 if (image->colors != number_colors)
2686 return(MagickFalse);
2688 image_view=AcquireAuthenticCacheView(image,exception);
2689 for (y=0; y < (ssize_t) image->rows; y++)
2700 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2701 if (q == (Quantum *) NULL)
2703 for (x=0; x < (ssize_t) image->columns; x++)
2705 image->colormap[i].red=(double) GetPixelRed(image,q);
2706 image->colormap[i].green=(double) GetPixelGreen(image,q);
2707 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2708 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2709 SetPixelIndex(image,(Quantum) i,q);
2711 q+=GetPixelChannels(image);
2713 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2715 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2717 if (proceed == MagickFalse)
2720 image_view=DestroyCacheView(image_view);
2724 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2725 Image *image,ExceptionInfo *exception)
2737 assert(quantize_info != (const QuantizeInfo *) NULL);
2738 assert(quantize_info->signature == MagickSignature);
2739 assert(image != (Image *) NULL);
2740 assert(image->signature == MagickSignature);
2741 if (image->debug != MagickFalse)
2742 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2743 maximum_colors=quantize_info->number_colors;
2744 if (maximum_colors == 0)
2745 maximum_colors=MaxColormapSize;
2746 if (maximum_colors > MaxColormapSize)
2747 maximum_colors=MaxColormapSize;
2748 if (image->alpha_trait != BlendPixelTrait)
2750 if ((image->columns*image->rows) <= maximum_colors)
2751 (void) DirectToColormapImage(image,exception);
2752 if (IsImageGray(image,exception) != MagickFalse)
2753 (void) SetGrayscaleImage(image,exception);
2755 if ((image->storage_class == PseudoClass) &&
2756 (image->colors <= maximum_colors))
2758 depth=quantize_info->tree_depth;
2765 Depth of color tree is: Log4(colormap size)+2.
2767 colors=maximum_colors;
2768 for (depth=1; colors != 0; depth++)
2770 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2772 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2776 Initialize color cube.
2778 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2779 if (cube_info == (CubeInfo *) NULL)
2780 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2782 status=ClassifyImageColors(cube_info,image,exception);
2783 if (status != MagickFalse)
2786 Reduce the number of colors in the image.
2788 ReduceImageColors(image,cube_info);
2789 status=AssignImageColors(image,cube_info,exception);
2791 DestroyCubeInfo(cube_info);
2796 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2800 % Q u a n t i z e I m a g e s %
2804 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2806 % QuantizeImages() analyzes the colors within a set of reference images and
2807 % chooses a fixed number of colors to represent the set. The goal of the
2808 % algorithm is to minimize the color difference between the input and output
2809 % images while minimizing the processing time.
2811 % The format of the QuantizeImages method is:
2813 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2814 % Image *images,ExceptionInfo *exception)
2816 % A description of each parameter follows:
2818 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2820 % o images: Specifies a pointer to a list of Image structures.
2822 % o exception: return any errors or warnings in this structure.
2825 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2826 Image *images,ExceptionInfo *exception)
2838 MagickProgressMonitor
2849 assert(quantize_info != (const QuantizeInfo *) NULL);
2850 assert(quantize_info->signature == MagickSignature);
2851 assert(images != (Image *) NULL);
2852 assert(images->signature == MagickSignature);
2853 if (images->debug != MagickFalse)
2854 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2855 if (GetNextImageInList(images) == (Image *) NULL)
2858 Handle a single image with QuantizeImage.
2860 status=QuantizeImage(quantize_info,images,exception);
2864 maximum_colors=quantize_info->number_colors;
2865 if (maximum_colors == 0)
2866 maximum_colors=MaxColormapSize;
2867 if (maximum_colors > MaxColormapSize)
2868 maximum_colors=MaxColormapSize;
2869 depth=quantize_info->tree_depth;
2876 Depth of color tree is: Log4(colormap size)+2.
2878 colors=maximum_colors;
2879 for (depth=1; colors != 0; depth++)
2881 if (quantize_info->dither_method != NoDitherMethod)
2885 Initialize color cube.
2887 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2888 if (cube_info == (CubeInfo *) NULL)
2890 (void) ThrowMagickException(exception,GetMagickModule(),
2891 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2892 return(MagickFalse);
2894 number_images=GetImageListLength(images);
2896 for (i=0; image != (Image *) NULL; i++)
2898 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2899 image->client_data);
2900 status=ClassifyImageColors(cube_info,image,exception);
2901 if (status == MagickFalse)
2903 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2904 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2906 if (proceed == MagickFalse)
2908 image=GetNextImageInList(image);
2910 if (status != MagickFalse)
2913 Reduce the number of colors in an image sequence.
2915 ReduceImageColors(images,cube_info);
2917 for (i=0; image != (Image *) NULL; i++)
2919 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2920 NULL,image->client_data);
2921 status=AssignImageColors(image,cube_info,exception);
2922 if (status == MagickFalse)
2924 (void) SetImageProgressMonitor(image,progress_monitor,
2925 image->client_data);
2926 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2928 if (proceed == MagickFalse)
2930 image=GetNextImageInList(image);
2933 DestroyCubeInfo(cube_info);
2938 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2942 + Q u a n t i z e E r r o r F l a t t e n %
2946 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2948 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2949 % error into a sorted 1D array. This accelerates the color reduction process.
2951 % Contributed by Yoya.
2953 % The format of the QuantizeImages method is:
2955 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2956 % const NodeInfo *node_info,const ssize_t offset,
2957 % MagickRealType *quantize_error)
2959 % A description of each parameter follows.
2961 % o image: the image.
2963 % o cube_info: A pointer to the Cube structure.
2965 % o node_info: pointer to node in color cube tree that is current pointer.
2967 % o offset: quantize error offset.
2969 % o quantize_error: the quantization error vector.
2972 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2973 const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
2982 if (offset >= (ssize_t) cube_info->nodes)
2984 quantize_error[offset]=node_info->quantize_error;
2986 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2987 for (i=0; i < (ssize_t) number_children ; i++)
2988 if (node_info->child[i] != (NodeInfo *) NULL)
2989 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
2995 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3003 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3005 % Reduce() traverses the color cube tree and prunes any node whose
3006 % quantization error falls below a particular threshold.
3008 % The format of the Reduce method is:
3010 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3012 % A description of each parameter follows.
3014 % o image: the image.
3016 % o cube_info: A pointer to the Cube structure.
3018 % o node_info: pointer to node in color cube tree that is to be pruned.
3021 static void Reduce(const Image *image,CubeInfo *cube_info,
3022 const NodeInfo *node_info)
3031 Traverse any children.
3033 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3034 for (i=0; i < (ssize_t) number_children; i++)
3035 if (node_info->child[i] != (NodeInfo *) NULL)
3036 Reduce(image,cube_info,node_info->child[i]);
3037 if (node_info->quantize_error <= cube_info->pruning_threshold)
3038 PruneChild(image,cube_info,node_info);
3042 Find minimum pruning threshold.
3044 if (node_info->number_unique > 0)
3045 cube_info->colors++;
3046 if (node_info->quantize_error < cube_info->next_threshold)
3047 cube_info->next_threshold=node_info->quantize_error;
3052 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3056 + R e d u c e I m a g e C o l o r s %
3060 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3062 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3063 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3064 % in the output image. On any given iteration over the tree, it selects
3065 % those nodes whose E value is minimal for pruning and merges their
3066 % color statistics upward. It uses a pruning threshold, Ep, to govern
3067 % node selection as follows:
3070 % while number of nodes with (n2 > 0) > required maximum number of colors
3071 % prune all nodes such that E <= Ep
3072 % Set Ep to minimum E in remaining nodes
3074 % This has the effect of minimizing any quantization error when merging
3075 % two nodes together.
3077 % When a node to be pruned has offspring, the pruning procedure invokes
3078 % itself recursively in order to prune the tree from the leaves upward.
3079 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3080 % corresponding data in that node's parent. This retains the pruned
3081 % node's color characteristics for later averaging.
3083 % For each node, n2 pixels exist for which that node represents the
3084 % smallest volume in RGB space containing those pixel's colors. When n2
3085 % > 0 the node will uniquely define a color in the output image. At the
3086 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3087 % the tree which represent colors present in the input image.
3089 % The other pixel count, n1, indicates the total number of colors
3090 % within the cubic volume which the node represents. This includes n1 -
3091 % n2 pixels whose colors should be defined by nodes at a lower level in
3094 % The format of the ReduceImageColors method is:
3096 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3098 % A description of each parameter follows.
3100 % o image: the image.
3102 % o cube_info: A pointer to the Cube structure.
3106 static int MagickRealTypeCompare(const void *error_p,const void *error_q)
3112 p=(MagickRealType *) error_p;
3113 q=(MagickRealType *) error_q;
3116 if (fabs((double) (*q-*p)) <= MagickEpsilon)
3121 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3123 #define ReduceImageTag "Reduce/Image"
3134 cube_info->next_threshold=0.0;
3135 if ((cube_info->colors > cube_info->maximum_colors) && (cube_info->depth > 3))
3141 Enable rapid reduction of the number of unique colors.
3143 quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
3144 sizeof(*quantize_error));
3145 if (quantize_error != (MagickRealType *) NULL)
3147 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3149 qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
3150 MagickRealTypeCompare);
3151 cube_info->next_threshold=quantize_error[MagickMax(cube_info->nodes-
3152 cube_info->maximum_colors,0)];
3153 quantize_error=(MagickRealType *) RelinquishMagickMemory(
3157 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3159 cube_info->pruning_threshold=cube_info->next_threshold;
3160 cube_info->next_threshold=cube_info->root->quantize_error-1;
3161 cube_info->colors=0;
3162 Reduce(image,cube_info,cube_info->root);
3163 offset=(MagickOffsetType) span-cube_info->colors;
3164 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3165 cube_info->maximum_colors+1);
3166 if (proceed == MagickFalse)
3172 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3176 % R e m a p I m a g e %
3180 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3182 % RemapImage() replaces the colors of an image with a dither of the colors
3185 % The format of the RemapImage method is:
3187 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3188 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3190 % A description of each parameter follows:
3192 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3194 % o image: the image.
3196 % o remap_image: the reference image.
3198 % o exception: return any errors or warnings in this structure.
3201 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3202 Image *image,const Image *remap_image,ExceptionInfo *exception)
3211 Initialize color cube.
3213 assert(image != (Image *) NULL);
3214 assert(image->signature == MagickSignature);
3215 if (image->debug != MagickFalse)
3216 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3217 assert(remap_image != (Image *) NULL);
3218 assert(remap_image->signature == MagickSignature);
3219 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3220 quantize_info->number_colors);
3221 if (cube_info == (CubeInfo *) NULL)
3222 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3224 status=ClassifyImageColors(cube_info,remap_image,exception);
3225 if (status != MagickFalse)
3228 Classify image colors from the reference image.
3230 cube_info->quantize_info->number_colors=cube_info->colors;
3231 status=AssignImageColors(image,cube_info,exception);
3233 DestroyCubeInfo(cube_info);
3238 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3242 % R e m a p I m a g e s %
3246 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3248 % RemapImages() replaces the colors of a sequence of images with the
3249 % closest color from a reference image.
3251 % The format of the RemapImage method is:
3253 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3254 % Image *images,Image *remap_image,ExceptionInfo *exception)
3256 % A description of each parameter follows:
3258 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3260 % o images: the image sequence.
3262 % o remap_image: the reference image.
3264 % o exception: return any errors or warnings in this structure.
3267 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3268 Image *images,const Image *remap_image,ExceptionInfo *exception)
3279 assert(images != (Image *) NULL);
3280 assert(images->signature == MagickSignature);
3281 if (images->debug != MagickFalse)
3282 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3284 if (remap_image == (Image *) NULL)
3287 Create a global colormap for an image sequence.
3289 status=QuantizeImages(quantize_info,images,exception);
3293 Classify image colors from the reference image.
3295 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3296 quantize_info->number_colors);
3297 if (cube_info == (CubeInfo *) NULL)
3298 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3300 status=ClassifyImageColors(cube_info,remap_image,exception);
3301 if (status != MagickFalse)
3304 Classify image colors from the reference image.
3306 cube_info->quantize_info->number_colors=cube_info->colors;
3308 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3310 status=AssignImageColors(image,cube_info,exception);
3311 if (status == MagickFalse)
3315 DestroyCubeInfo(cube_info);
3320 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3324 % S e t G r a y s c a l e I m a g e %
3328 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3330 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3332 % The format of the SetGrayscaleImage method is:
3334 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3336 % A description of each parameter follows:
3338 % o image: The image.
3340 % o exception: return any errors or warnings in this structure.
3344 #if defined(__cplusplus) || defined(c_plusplus)
3348 static int IntensityCompare(const void *x,const void *y)
3357 color_1=(PixelInfo *) x;
3358 color_2=(PixelInfo *) y;
3359 intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
3360 GetPixelInfoIntensity(color_2));
3361 return((int) intensity);
3364 #if defined(__cplusplus) || defined(c_plusplus)
3368 static MagickBooleanType SetGrayscaleImage(Image *image,
3369 ExceptionInfo *exception)
3388 assert(image != (Image *) NULL);
3389 assert(image->signature == MagickSignature);
3390 if (image->type != GrayscaleType)
3391 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3392 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3393 sizeof(*colormap_index));
3394 if (colormap_index == (ssize_t *) NULL)
3395 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3397 if (image->storage_class != PseudoClass)
3399 for (i=0; i <= (ssize_t) MaxMap; i++)
3400 colormap_index[i]=(-1);
3401 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3402 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3406 image_view=AcquireAuthenticCacheView(image,exception);
3407 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3408 #pragma omp parallel for schedule(static,4) shared(status) \
3409 magick_threads(image,image,image->rows,1)
3411 for (y=0; y < (ssize_t) image->rows; y++)
3419 if (status == MagickFalse)
3421 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3423 if (q == (Quantum *) NULL)
3428 for (x=0; x < (ssize_t) image->columns; x++)
3433 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3434 if (colormap_index[intensity] < 0)
3436 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3437 #pragma omp critical (MagickCore_SetGrayscaleImage)
3439 if (colormap_index[intensity] < 0)
3441 colormap_index[intensity]=(ssize_t) image->colors;
3442 image->colormap[image->colors].red=(double)
3443 GetPixelRed(image,q);
3444 image->colormap[image->colors].green=(double)
3445 GetPixelGreen(image,q);
3446 image->colormap[image->colors].blue=(double)
3447 GetPixelBlue(image,q);
3451 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3452 q+=GetPixelChannels(image);
3454 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3457 image_view=DestroyCacheView(image_view);
3459 for (i=0; i < (ssize_t) image->colors; i++)
3460 image->colormap[i].alpha=(double) i;
3461 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3463 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3464 if (colormap == (PixelInfo *) NULL)
3465 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3468 colormap[j]=image->colormap[0];
3469 for (i=0; i < (ssize_t) image->colors; i++)
3471 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3474 colormap[j]=image->colormap[i];
3476 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3478 image->colors=(size_t) (j+1);
3479 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3480 image->colormap=colormap;
3482 image_view=AcquireAuthenticCacheView(image,exception);
3483 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3484 #pragma omp parallel for schedule(static,4) shared(status) \
3485 magick_threads(image,image,image->rows,1)
3487 for (y=0; y < (ssize_t) image->rows; y++)
3495 if (status == MagickFalse)
3497 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3498 if (q == (Quantum *) NULL)
3503 for (x=0; x < (ssize_t) image->columns; x++)
3505 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3506 GetPixelIndex(image,q))],q);
3507 q+=GetPixelChannels(image);
3509 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3512 image_view=DestroyCacheView(image_view);
3513 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3514 image->type=GrayscaleType;
3515 if (IsImageMonochrome(image,exception) != MagickFalse)
3516 image->type=BilevelType;