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-2013 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) ((double) GetPixelInfoIntensity(q) <
680 ((double) QuantumRange/2.0) ? 0 : QuantumRange);
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->colorspace == TransparentColorspace)
763 associate_alpha=MagickFalse;
764 if ((cube_info->quantize_info->number_colors == 2) &&
765 (cube_info->quantize_info->colorspace == GRAYColorspace))
766 associate_alpha=MagickFalse;
767 cube_info->associate_alpha=associate_alpha;
770 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
771 const Image *image,ExceptionInfo *exception)
773 #define ClassifyImageTag "Classify/Image"
803 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
805 SetAssociatedAlpha(image,cube_info);
806 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
807 (cube_info->quantize_info->colorspace != CMYKColorspace))
808 (void) TransformImageColorspace((Image *) image,
809 cube_info->quantize_info->colorspace,exception);
811 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
812 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
813 midpoint.red=(double) QuantumRange/2.0;
814 midpoint.green=(double) QuantumRange/2.0;
815 midpoint.blue=(double) QuantumRange/2.0;
816 midpoint.alpha=(double) QuantumRange/2.0;
818 image_view=AcquireVirtualCacheView(image,exception);
819 for (y=0; y < (ssize_t) image->rows; y++)
821 register const Quantum
827 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
828 if (p == (const Quantum *) NULL)
830 if (cube_info->nodes > MaxNodes)
833 Prune one level if the color tree is too large.
835 PruneLevel(image,cube_info,cube_info->root);
838 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
841 Start at the root and descend the color cube tree.
843 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
848 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
849 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
852 AssociateAlphaPixel(image,cube_info,p,&pixel);
853 index=MaxTreeDepth-1;
854 bisect=((double) QuantumRange+1.0)/2.0;
856 node_info=cube_info->root;
857 for (level=1; level <= MaxTreeDepth; level++)
860 id=ColorToNodeId(cube_info,&pixel,index);
861 mid.red+=(id & 1) != 0 ? bisect : -bisect;
862 mid.green+=(id & 2) != 0 ? bisect : -bisect;
863 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
864 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
865 if (node_info->child[id] == (NodeInfo *) NULL)
868 Set colors of new node to contain pixel.
870 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
871 if (node_info->child[id] == (NodeInfo *) NULL)
872 (void) ThrowMagickException(exception,GetMagickModule(),
873 ResourceLimitError,"MemoryAllocationFailed","`%s'",
875 if (level == MaxTreeDepth)
879 Approximate the quantization error represented by this node.
881 node_info=node_info->child[id];
882 error.red=QuantumScale*(pixel.red-mid.red);
883 error.green=QuantumScale*(pixel.green-mid.green);
884 error.blue=QuantumScale*(pixel.blue-mid.blue);
885 if (cube_info->associate_alpha != MagickFalse)
886 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
887 node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
888 error.green*error.green+error.blue*error.blue+
889 error.alpha*error.alpha));
890 cube_info->root->quantize_error+=node_info->quantize_error;
894 Sum RGB for this leaf for later derivation of the mean cube color.
896 node_info->number_unique+=count;
897 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
898 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
899 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
900 if (cube_info->associate_alpha != MagickFalse)
901 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
903 p+=count*GetPixelChannels(image);
905 if (cube_info->colors > cube_info->maximum_colors)
907 PruneToCubeDepth(image,cube_info,cube_info->root);
910 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
912 if (proceed == MagickFalse)
915 for (y++; y < (ssize_t) image->rows; y++)
917 register const Quantum
923 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
924 if (p == (const Quantum *) NULL)
926 if (cube_info->nodes > MaxNodes)
929 Prune one level if the color tree is too large.
931 PruneLevel(image,cube_info,cube_info->root);
934 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
937 Start at the root and descend the color cube tree.
939 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
944 GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
945 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
948 AssociateAlphaPixel(image,cube_info,p,&pixel);
949 index=MaxTreeDepth-1;
950 bisect=((double) QuantumRange+1.0)/2.0;
952 node_info=cube_info->root;
953 for (level=1; level <= cube_info->depth; level++)
956 id=ColorToNodeId(cube_info,&pixel,index);
957 mid.red+=(id & 1) != 0 ? bisect : -bisect;
958 mid.green+=(id & 2) != 0 ? bisect : -bisect;
959 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
960 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
961 if (node_info->child[id] == (NodeInfo *) NULL)
964 Set colors of new node to contain pixel.
966 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
967 if (node_info->child[id] == (NodeInfo *) NULL)
968 (void) ThrowMagickException(exception,GetMagickModule(),
969 ResourceLimitError,"MemoryAllocationFailed","%s",
971 if (level == cube_info->depth)
975 Approximate the quantization error represented by this node.
977 node_info=node_info->child[id];
978 error.red=QuantumScale*(pixel.red-mid.red);
979 error.green=QuantumScale*(pixel.green-mid.green);
980 error.blue=QuantumScale*(pixel.blue-mid.blue);
981 if (cube_info->associate_alpha != MagickFalse)
982 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
983 node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
984 error.green*error.green+error.blue*error.blue+
985 error.alpha*error.alpha));
986 cube_info->root->quantize_error+=node_info->quantize_error;
990 Sum RGB for this leaf for later derivation of the mean cube color.
992 node_info->number_unique+=count;
993 node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
994 node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
995 node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
996 if (cube_info->associate_alpha != MagickFalse)
997 node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
999 p+=count*GetPixelChannels(image);
1001 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1003 if (proceed == MagickFalse)
1006 image_view=DestroyCacheView(image_view);
1007 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1008 (cube_info->quantize_info->colorspace != CMYKColorspace))
1009 (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1014 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1018 % C l o n e Q u a n t i z e I n f o %
1022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1024 % CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1025 % or if quantize info is NULL, a new one.
1027 % The format of the CloneQuantizeInfo method is:
1029 % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1031 % A description of each parameter follows:
1033 % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1034 % quantize info, or if image info is NULL a new one.
1036 % o quantize_info: a structure of type info.
1039 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1044 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1045 if (clone_info == (QuantizeInfo *) NULL)
1046 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1047 GetQuantizeInfo(clone_info);
1048 if (quantize_info == (QuantizeInfo *) NULL)
1050 clone_info->number_colors=quantize_info->number_colors;
1051 clone_info->tree_depth=quantize_info->tree_depth;
1052 clone_info->dither_method=quantize_info->dither_method;
1053 clone_info->colorspace=quantize_info->colorspace;
1054 clone_info->measure_error=quantize_info->measure_error;
1059 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1063 + C l o s e s t C o l o r %
1067 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1069 % ClosestColor() traverses the color cube tree at a particular node and
1070 % determines which colormap entry best represents the input color.
1072 % The format of the ClosestColor method is:
1074 % void ClosestColor(const Image *image,CubeInfo *cube_info,
1075 % const NodeInfo *node_info)
1077 % A description of each parameter follows.
1079 % o image: the image.
1081 % o cube_info: A pointer to the Cube structure.
1083 % o node_info: the address of a structure of type NodeInfo which points to a
1084 % node in the color cube tree that is to be pruned.
1087 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1088 const NodeInfo *node_info)
1097 Traverse any children.
1099 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1100 for (i=0; i < (ssize_t) number_children; i++)
1101 if (node_info->child[i] != (NodeInfo *) NULL)
1102 ClosestColor(image,cube_info,node_info->child[i]);
1103 if (node_info->number_unique != 0)
1116 register RealPixelInfo
1120 Determine if this color is "closest".
1122 p=image->colormap+node_info->color_number;
1123 q=(&cube_info->target);
1126 if (cube_info->associate_alpha != MagickFalse)
1128 alpha=(double) (QuantumScale*p->alpha);
1129 beta=(double) (QuantumScale*q->alpha);
1131 pixel=alpha*p->red-beta*q->red;
1132 distance=pixel*pixel;
1133 if (distance <= cube_info->distance)
1135 pixel=alpha*p->green-beta*q->green;
1136 distance+=pixel*pixel;
1137 if (distance <= cube_info->distance)
1139 pixel=alpha*p->blue-beta*q->blue;
1140 distance+=pixel*pixel;
1141 if (distance <= cube_info->distance)
1144 distance+=pixel*pixel;
1145 if (distance <= cube_info->distance)
1147 cube_info->distance=distance;
1148 cube_info->color_number=node_info->color_number;
1157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1161 % C o m p r e s s I m a g e C o l o r m a p %
1165 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1167 % CompressImageColormap() compresses an image colormap by removing any
1168 % duplicate or unused color entries.
1170 % The format of the CompressImageColormap method is:
1172 % MagickBooleanType CompressImageColormap(Image *image,
1173 % ExceptionInfo *exception)
1175 % A description of each parameter follows:
1177 % o image: the image.
1179 % o exception: return any errors or warnings in this structure.
1182 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1183 ExceptionInfo *exception)
1188 assert(image != (Image *) NULL);
1189 assert(image->signature == MagickSignature);
1190 if (image->debug != MagickFalse)
1191 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1192 if (IsPaletteImage(image,exception) == MagickFalse)
1193 return(MagickFalse);
1194 GetQuantizeInfo(&quantize_info);
1195 quantize_info.number_colors=image->colors;
1196 quantize_info.tree_depth=MaxTreeDepth;
1197 return(QuantizeImage(&quantize_info,image,exception));
1201 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1205 + D e f i n e I m a g e C o l o r m a p %
1209 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1211 % DefineImageColormap() traverses the color cube tree and notes each colormap
1212 % entry. A colormap entry is any node in the color cube tree where the
1213 % of unique colors is not zero. DefineImageColormap() returns the number of
1214 % colors in the image colormap.
1216 % The format of the DefineImageColormap method is:
1218 % size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1219 % NodeInfo *node_info)
1221 % A description of each parameter follows.
1223 % o image: the image.
1225 % o cube_info: A pointer to the Cube structure.
1227 % o node_info: the address of a structure of type NodeInfo which points to a
1228 % node in the color cube tree that is to be pruned.
1231 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1232 NodeInfo *node_info)
1241 Traverse any children.
1243 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1244 for (i=0; i < (ssize_t) number_children; i++)
1245 if (node_info->child[i] != (NodeInfo *) NULL)
1246 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1247 if (node_info->number_unique != 0)
1256 Colormap entry is defined by the mean color in this cube.
1258 q=image->colormap+image->colors;
1259 alpha=(double) ((MagickOffsetType) node_info->number_unique);
1260 alpha=PerceptibleReciprocal(alpha);
1261 if (cube_info->associate_alpha == MagickFalse)
1263 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1264 node_info->total_color.red);
1265 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1266 node_info->total_color.green);
1267 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1268 node_info->total_color.blue);
1269 q->alpha=(double) OpaqueAlpha;
1276 opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1277 q->alpha=(double) ClampToQuantum((opacity));
1278 if (q->alpha == OpaqueAlpha)
1280 q->red=(double) ClampToQuantum(alpha*QuantumRange*
1281 node_info->total_color.red);
1282 q->green=(double) ClampToQuantum(alpha*QuantumRange*
1283 node_info->total_color.green);
1284 q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1285 node_info->total_color.blue);
1292 gamma=(double) (QuantumScale*q->alpha);
1293 gamma=PerceptibleReciprocal(gamma);
1294 q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1295 node_info->total_color.red);
1296 q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1297 node_info->total_color.green);
1298 q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1299 node_info->total_color.blue);
1300 if (node_info->number_unique > cube_info->transparent_pixels)
1302 cube_info->transparent_pixels=node_info->number_unique;
1303 cube_info->transparent_index=(ssize_t) image->colors;
1307 node_info->color_number=image->colors++;
1309 return(image->colors);
1313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1317 + D e s t r o y C u b e I n f o %
1321 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1323 % DestroyCubeInfo() deallocates memory associated with an image.
1325 % The format of the DestroyCubeInfo method is:
1327 % DestroyCubeInfo(CubeInfo *cube_info)
1329 % A description of each parameter follows:
1331 % o cube_info: the address of a structure of type CubeInfo.
1334 static void DestroyCubeInfo(CubeInfo *cube_info)
1340 Release color cube tree storage.
1344 nodes=cube_info->node_queue->next;
1345 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1346 cube_info->node_queue->nodes);
1347 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1348 cube_info->node_queue);
1349 cube_info->node_queue=nodes;
1350 } while (cube_info->node_queue != (Nodes *) NULL);
1351 if (cube_info->memory_info != (MemoryInfo *) NULL)
1352 cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1353 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1354 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1358 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1362 % D e s t r o y Q u a n t i z e I n f o %
1366 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1368 % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1371 % The format of the DestroyQuantizeInfo method is:
1373 % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1375 % A description of each parameter follows:
1377 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1380 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1382 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1383 assert(quantize_info != (QuantizeInfo *) NULL);
1384 assert(quantize_info->signature == MagickSignature);
1385 quantize_info->signature=(~MagickSignature);
1386 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1387 return(quantize_info);
1391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1395 + D i t h e r I m a g e %
1399 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1401 % DitherImage() distributes the difference between an original image and
1402 % the corresponding color reduced algorithm to neighboring pixels using
1403 % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1404 % MagickTrue if the image is dithered otherwise MagickFalse.
1406 % The format of the DitherImage method is:
1408 % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1409 % ExceptionInfo *exception)
1411 % A description of each parameter follows.
1413 % o image: the image.
1415 % o cube_info: A pointer to the Cube structure.
1417 % o exception: return any errors or warnings in this structure.
1421 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1426 assert(pixels != (RealPixelInfo **) NULL);
1427 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1428 if (pixels[i] != (RealPixelInfo *) NULL)
1429 pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1430 pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1434 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1445 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1446 pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1448 if (pixels == (RealPixelInfo **) NULL)
1449 return((RealPixelInfo **) NULL);
1450 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1451 for (i=0; i < (ssize_t) number_threads; i++)
1453 pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1454 if (pixels[i] == (RealPixelInfo *) NULL)
1455 return(DestroyPixelThreadSet(pixels));
1460 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1461 const RealPixelInfo *pixel)
1463 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1464 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1465 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1466 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1471 offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1472 GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1473 BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1474 if (cube_info->associate_alpha != MagickFalse)
1475 offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1479 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1480 ExceptionInfo *exception)
1482 #define DitherImageTag "Dither/Image"
1497 Distribute quantization error using Floyd-Steinberg.
1499 pixels=AcquirePixelThreadSet(image->columns);
1500 if (pixels == (RealPixelInfo **) NULL)
1501 return(MagickFalse);
1503 image_view=AcquireAuthenticCacheView(image,exception);
1504 for (y=0; y < (ssize_t) image->rows; y++)
1507 id = GetOpenMPThreadId();
1528 if (status == MagickFalse)
1530 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1531 if (q == (Quantum *) NULL)
1536 q+=(y & 0x01)*image->columns*GetPixelChannels(image);
1538 current=pixels[id]+(y & 0x01)*image->columns;
1539 previous=pixels[id]+((y+1) & 0x01)*image->columns;
1540 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1541 for (x=0; x < (ssize_t) image->columns; x++)
1553 q-=(y & 0x01)*GetPixelChannels(image);
1554 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1555 AssociateAlphaPixel(image,&cube,q,&pixel);
1558 pixel.red+=7*current[u-v].red/16;
1559 pixel.green+=7*current[u-v].green/16;
1560 pixel.blue+=7*current[u-v].blue/16;
1561 if (cube.associate_alpha != MagickFalse)
1562 pixel.alpha+=7*current[u-v].alpha/16;
1566 if (x < (ssize_t) (image->columns-1))
1568 pixel.red+=previous[u+v].red/16;
1569 pixel.green+=previous[u+v].green/16;
1570 pixel.blue+=previous[u+v].blue/16;
1571 if (cube.associate_alpha != MagickFalse)
1572 pixel.alpha+=previous[u+v].alpha/16;
1574 pixel.red+=5*previous[u].red/16;
1575 pixel.green+=5*previous[u].green/16;
1576 pixel.blue+=5*previous[u].blue/16;
1577 if (cube.associate_alpha != MagickFalse)
1578 pixel.alpha+=5*previous[u].alpha/16;
1581 pixel.red+=3*previous[u-v].red/16;
1582 pixel.green+=3*previous[u-v].green/16;
1583 pixel.blue+=3*previous[u-v].blue/16;
1584 if (cube.associate_alpha != MagickFalse)
1585 pixel.alpha+=3*previous[u-v].alpha/16;
1588 pixel.red=(double) ClampPixel(pixel.red);
1589 pixel.green=(double) ClampPixel(pixel.green);
1590 pixel.blue=(double) ClampPixel(pixel.blue);
1591 if (cube.associate_alpha != MagickFalse)
1592 pixel.alpha=(double) ClampPixel(pixel.alpha);
1593 i=CacheOffset(&cube,&pixel);
1594 if (cube.cache[i] < 0)
1603 Identify the deepest node containing the pixel's color.
1605 node_info=cube.root;
1606 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1608 id=ColorToNodeId(&cube,&pixel,index);
1609 if (node_info->child[id] == (NodeInfo *) NULL)
1611 node_info=node_info->child[id];
1614 Find closest color among siblings and their children.
1617 cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1619 ClosestColor(image,&cube,node_info->parent);
1620 cube.cache[i]=(ssize_t) cube.color_number;
1623 Assign pixel to closest colormap entry.
1625 index=(size_t) cube.cache[i];
1626 if (image->storage_class == PseudoClass)
1627 SetPixelIndex(image,(Quantum) index,q);
1628 if (cube.quantize_info->measure_error == MagickFalse)
1630 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1631 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1632 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1633 if (cube.associate_alpha != MagickFalse)
1634 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1636 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1641 AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1642 current[u].red=pixel.red-color.red;
1643 current[u].green=pixel.green-color.green;
1644 current[u].blue=pixel.blue-color.blue;
1645 if (cube.associate_alpha != MagickFalse)
1646 current[u].alpha=pixel.alpha-color.alpha;
1647 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1652 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1653 #pragma omp critical (MagickCore_FloydSteinbergDither)
1655 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1657 if (proceed == MagickFalse)
1660 q+=((y+1) & 0x01)*GetPixelChannels(image);
1663 image_view=DestroyCacheView(image_view);
1664 pixels=DestroyPixelThreadSet(pixels);
1668 static MagickBooleanType
1669 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1670 ExceptionInfo *exception);
1672 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1673 const size_t level,const unsigned int direction,ExceptionInfo *exception)
1680 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1682 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1684 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1690 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1692 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1694 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1700 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1702 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1704 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1710 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1712 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1714 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1726 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1728 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1730 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1732 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1734 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1736 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1738 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1744 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1746 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1748 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1750 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1752 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1754 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1756 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1762 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1764 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1766 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1768 (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1770 Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1772 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1774 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1780 Riemersma(image,image_view,cube_info,level-1,EastGravity,
1782 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1784 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1786 (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1788 Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1790 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1792 Riemersma(image,image_view,cube_info,level-1,WestGravity,
1801 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1802 CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1804 #define DitherImageTag "Dither/Image"
1820 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1821 (p->y >= 0) && (p->y < (ssize_t) image->rows))
1832 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1833 if (q == (Quantum *) NULL)
1834 return(MagickFalse);
1835 AssociateAlphaPixel(image,cube_info,q,&pixel);
1836 for (i=0; i < ErrorQueueLength; i++)
1838 pixel.red+=p->weights[i]*p->error[i].red;
1839 pixel.green+=p->weights[i]*p->error[i].green;
1840 pixel.blue+=p->weights[i]*p->error[i].blue;
1841 if (cube_info->associate_alpha != MagickFalse)
1842 pixel.alpha+=p->weights[i]*p->error[i].alpha;
1844 pixel.red=(double) ClampPixel(pixel.red);
1845 pixel.green=(double) ClampPixel(pixel.green);
1846 pixel.blue=(double) ClampPixel(pixel.blue);
1847 if (cube_info->associate_alpha != MagickFalse)
1848 pixel.alpha=(double) ClampPixel(pixel.alpha);
1849 i=CacheOffset(cube_info,&pixel);
1850 if (p->cache[i] < 0)
1859 Identify the deepest node containing the pixel's color.
1862 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1864 id=ColorToNodeId(cube_info,&pixel,index);
1865 if (node_info->child[id] == (NodeInfo *) NULL)
1867 node_info=node_info->child[id];
1870 Find closest color among siblings and their children.
1873 p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1874 QuantumRange+1.0)+1.0);
1875 ClosestColor(image,p,node_info->parent);
1876 p->cache[i]=(ssize_t) p->color_number;
1879 Assign pixel to closest colormap entry.
1881 index=(size_t) p->cache[i];
1882 if (image->storage_class == PseudoClass)
1883 SetPixelIndex(image,(Quantum) index,q);
1884 if (cube_info->quantize_info->measure_error == MagickFalse)
1886 SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1887 SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1888 SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1889 if (cube_info->associate_alpha != MagickFalse)
1890 SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1892 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1893 return(MagickFalse);
1895 Propagate the error as the last entry of the error queue.
1897 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1898 sizeof(p->error[0]));
1899 AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1900 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1901 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1902 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1903 if (cube_info->associate_alpha != MagickFalse)
1904 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1905 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1906 if (proceed == MagickFalse)
1907 return(MagickFalse);
1912 case WestGravity: p->x--; break;
1913 case EastGravity: p->x++; break;
1914 case NorthGravity: p->y--; break;
1915 case SouthGravity: p->y++; break;
1920 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1927 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1934 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1935 ExceptionInfo *exception)
1949 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1950 return(FloydSteinbergDither(image,cube_info,exception));
1952 Distribute quantization error along a Hilbert curve.
1954 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1955 sizeof(*cube_info->error));
1958 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1959 for (depth=1; i != 0; depth++)
1961 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1963 cube_info->offset=0;
1964 cube_info->span=(MagickSizeType) image->columns*image->rows;
1965 image_view=AcquireAuthenticCacheView(image,exception);
1967 Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1968 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1969 image_view=DestroyCacheView(image_view);
1974 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1978 + G e t C u b e I n f o %
1982 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1984 % GetCubeInfo() initialize the Cube data structure.
1986 % The format of the GetCubeInfo method is:
1988 % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1989 % const size_t depth,const size_t maximum_colors)
1991 % A description of each parameter follows.
1993 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1995 % o depth: Normally, this integer value is zero or one. A zero or
1996 % one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1997 % A tree of this depth generally allows the best representation of the
1998 % reference image with the least amount of memory and the fastest
1999 % computational speed. In some cases, such as an image with low color
2000 % dispersion (a few number of colors), a value other than
2001 % Log4(number_colors) is required. To expand the color tree completely,
2004 % o maximum_colors: maximum colors.
2007 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2008 const size_t depth,const size_t maximum_colors)
2024 Initialize tree to describe color cube_info.
2026 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2027 if (cube_info == (CubeInfo *) NULL)
2028 return((CubeInfo *) NULL);
2029 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2030 cube_info->depth=depth;
2031 if (cube_info->depth > MaxTreeDepth)
2032 cube_info->depth=MaxTreeDepth;
2033 if (cube_info->depth < 2)
2035 cube_info->maximum_colors=maximum_colors;
2037 Initialize root node.
2039 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2040 if (cube_info->root == (NodeInfo *) NULL)
2041 return((CubeInfo *) NULL);
2042 cube_info->root->parent=cube_info->root;
2043 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2044 if (cube_info->quantize_info->dither_method == NoDitherMethod)
2047 Initialize dither resources.
2049 length=(size_t) (1UL << (4*(8-CacheShift)));
2050 cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2051 if (cube_info->memory_info == (MemoryInfo *) NULL)
2052 return((CubeInfo *) NULL);
2053 cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2055 Initialize color cache.
2057 for (i=0; i < (ssize_t) length; i++)
2058 cube_info->cache[i]=(-1);
2060 Distribute weights along a curve of exponential decay.
2063 for (i=0; i < ErrorQueueLength; i++)
2065 cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2066 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2069 Normalize the weighting factors.
2072 for (i=0; i < ErrorQueueLength; i++)
2073 weight+=cube_info->weights[i];
2075 for (i=0; i < ErrorQueueLength; i++)
2077 cube_info->weights[i]/=weight;
2078 sum+=cube_info->weights[i];
2080 cube_info->weights[0]+=1.0-sum;
2085 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2089 + G e t N o d e I n f o %
2093 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2095 % GetNodeInfo() allocates memory for a new node in the color cube tree and
2096 % presets all fields to zero.
2098 % The format of the GetNodeInfo method is:
2100 % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2101 % const size_t level,NodeInfo *parent)
2103 % A description of each parameter follows.
2105 % o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2107 % o id: Specifies the child number of the node.
2109 % o level: Specifies the level in the storage_class the node resides.
2112 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2113 const size_t level,NodeInfo *parent)
2118 if (cube_info->free_nodes == 0)
2124 Allocate a new queue of nodes.
2126 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2127 if (nodes == (Nodes *) NULL)
2128 return((NodeInfo *) NULL);
2129 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2130 sizeof(*nodes->nodes));
2131 if (nodes->nodes == (NodeInfo *) NULL)
2132 return((NodeInfo *) NULL);
2133 nodes->next=cube_info->node_queue;
2134 cube_info->node_queue=nodes;
2135 cube_info->next_node=nodes->nodes;
2136 cube_info->free_nodes=NodesInAList;
2139 cube_info->free_nodes--;
2140 node_info=cube_info->next_node++;
2141 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2142 node_info->parent=parent;
2144 node_info->level=level;
2149 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2153 % G e t I m a g e Q u a n t i z e E r r o r %
2157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2159 % GetImageQuantizeError() measures the difference between the original
2160 % and quantized images. This difference is the total quantization error.
2161 % The error is computed by summing over all pixels in an image the distance
2162 % squared in RGB space between each reference pixel value and its quantized
2163 % value. These values are computed:
2165 % o mean_error_per_pixel: This value is the mean error for any single
2166 % pixel in the image.
2168 % o normalized_mean_square_error: This value is the normalized mean
2169 % quantization error for any single pixel in the image. This distance
2170 % measure is normalized to a range between 0 and 1. It is independent
2171 % of the range of red, green, and blue values in the image.
2173 % o normalized_maximum_square_error: Thsi value is the normalized
2174 % maximum quantization error for any single pixel in the image. This
2175 % distance measure is normalized to a range between 0 and 1. It is
2176 % independent of the range of red, green, and blue values in your image.
2178 % The format of the GetImageQuantizeError method is:
2180 % MagickBooleanType GetImageQuantizeError(Image *image,
2181 % ExceptionInfo *exception)
2183 % A description of each parameter follows.
2185 % o image: the image.
2187 % o exception: return any errors or warnings in this structure.
2190 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2191 ExceptionInfo *exception)
2203 mean_error_per_pixel;
2211 assert(image != (Image *) NULL);
2212 assert(image->signature == MagickSignature);
2213 if (image->debug != MagickFalse)
2214 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2215 image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2216 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2217 if (image->storage_class == DirectClass)
2221 area=3.0*image->columns*image->rows;
2223 mean_error_per_pixel=0.0;
2225 image_view=AcquireVirtualCacheView(image,exception);
2226 for (y=0; y < (ssize_t) image->rows; y++)
2228 register const Quantum
2234 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2235 if (p == (const Quantum *) NULL)
2237 for (x=0; x < (ssize_t) image->columns; x++)
2239 index=1UL*GetPixelIndex(image,p);
2240 if (image->alpha_trait == BlendPixelTrait)
2242 alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2243 beta=(double) (QuantumScale*image->colormap[index].alpha);
2245 distance=fabs(alpha*GetPixelRed(image,p)-beta*
2246 image->colormap[index].red);
2247 mean_error_per_pixel+=distance;
2248 mean_error+=distance*distance;
2249 if (distance > maximum_error)
2250 maximum_error=distance;
2251 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
2252 image->colormap[index].green);
2253 mean_error_per_pixel+=distance;
2254 mean_error+=distance*distance;
2255 if (distance > maximum_error)
2256 maximum_error=distance;
2257 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
2258 image->colormap[index].blue);
2259 mean_error_per_pixel+=distance;
2260 mean_error+=distance*distance;
2261 if (distance > maximum_error)
2262 maximum_error=distance;
2263 p+=GetPixelChannels(image);
2266 image_view=DestroyCacheView(image_view);
2267 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2268 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2270 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2275 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2279 % G e t Q u a n t i z e I n f o %
2283 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2285 % GetQuantizeInfo() initializes the QuantizeInfo structure.
2287 % The format of the GetQuantizeInfo method is:
2289 % GetQuantizeInfo(QuantizeInfo *quantize_info)
2291 % A description of each parameter follows:
2293 % o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2296 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2298 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2299 assert(quantize_info != (QuantizeInfo *) NULL);
2300 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2301 quantize_info->number_colors=256;
2302 quantize_info->dither_method=RiemersmaDitherMethod;
2303 quantize_info->colorspace=UndefinedColorspace;
2304 quantize_info->measure_error=MagickFalse;
2305 quantize_info->signature=MagickSignature;
2309 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2313 % P o s t e r i z e I m a g e %
2317 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2319 % PosterizeImage() reduces the image to a limited number of colors for a
2322 % The format of the PosterizeImage method is:
2324 % MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2325 % const DitherMethod dither_method,ExceptionInfo *exception)
2327 % A description of each parameter follows:
2329 % o image: Specifies a pointer to an Image structure.
2331 % o levels: Number of color levels allowed in each channel. Very low values
2332 % (2, 3, or 4) have the most visible effect.
2334 % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2335 % RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2337 % o exception: return any errors or warnings in this structure.
2341 static inline double MagickRound(double x)
2344 Round the fraction to nearest integer.
2346 if ((x-floor(x)) < (ceil(x)-x))
2351 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2352 const DitherMethod dither_method,ExceptionInfo *exception)
2354 #define PosterizeImageTag "Posterize/Image"
2355 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2356 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2376 assert(image != (Image *) NULL);
2377 assert(image->signature == MagickSignature);
2378 if (image->debug != MagickFalse)
2379 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2380 if (image->storage_class == PseudoClass)
2381 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2382 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2383 magick_threads(image,image,1,1)
2385 for (i=0; i < (ssize_t) image->colors; i++)
2390 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2391 image->colormap[i].red=(double)
2392 PosterizePixel(image->colormap[i].red);
2393 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2394 image->colormap[i].green=(double)
2395 PosterizePixel(image->colormap[i].green);
2396 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2397 image->colormap[i].blue=(double)
2398 PosterizePixel(image->colormap[i].blue);
2399 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2400 image->colormap[i].alpha=(double)
2401 PosterizePixel(image->colormap[i].alpha);
2408 image_view=AcquireAuthenticCacheView(image,exception);
2409 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2410 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2411 magick_threads(image,image,image->rows,1)
2413 for (y=0; y < (ssize_t) image->rows; y++)
2421 if (status == MagickFalse)
2423 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2424 if (q == (Quantum *) NULL)
2429 for (x=0; x < (ssize_t) image->columns; x++)
2431 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2432 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
2433 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2434 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
2435 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2436 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
2437 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2438 (image->colorspace == CMYKColorspace))
2439 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
2440 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2441 (image->alpha_trait == BlendPixelTrait))
2442 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
2443 q+=GetPixelChannels(image);
2445 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2447 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2452 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2453 #pragma omp critical (MagickCore_PosterizeImage)
2455 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2457 if (proceed == MagickFalse)
2461 image_view=DestroyCacheView(image_view);
2462 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2463 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2464 levels,MaxColormapSize+1);
2465 quantize_info->dither_method=dither_method;
2466 quantize_info->tree_depth=MaxTreeDepth;
2467 status=QuantizeImage(quantize_info,image,exception);
2468 quantize_info=DestroyQuantizeInfo(quantize_info);
2473 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2477 + P r u n e C h i l d %
2481 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2483 % PruneChild() deletes the given node and merges its statistics into its
2486 % The format of the PruneSubtree method is:
2488 % PruneChild(const Image *image,CubeInfo *cube_info,
2489 % const NodeInfo *node_info)
2491 % A description of each parameter follows.
2493 % o image: the image.
2495 % o cube_info: A pointer to the Cube structure.
2497 % o node_info: pointer to node in color cube tree that is to be pruned.
2500 static void PruneChild(const Image *image,CubeInfo *cube_info,
2501 const NodeInfo *node_info)
2513 Traverse any children.
2515 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2516 for (i=0; i < (ssize_t) number_children; i++)
2517 if (node_info->child[i] != (NodeInfo *) NULL)
2518 PruneChild(image,cube_info,node_info->child[i]);
2520 Merge color statistics into parent.
2522 parent=node_info->parent;
2523 parent->number_unique+=node_info->number_unique;
2524 parent->total_color.red+=node_info->total_color.red;
2525 parent->total_color.green+=node_info->total_color.green;
2526 parent->total_color.blue+=node_info->total_color.blue;
2527 parent->total_color.alpha+=node_info->total_color.alpha;
2528 parent->child[node_info->id]=(NodeInfo *) NULL;
2533 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2537 + P r u n e L e v e l %
2541 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2543 % PruneLevel() deletes all nodes at the bottom level of the color tree merging
2544 % their color statistics into their parent node.
2546 % The format of the PruneLevel method is:
2548 % PruneLevel(const Image *image,CubeInfo *cube_info,
2549 % const NodeInfo *node_info)
2551 % A description of each parameter follows.
2553 % o image: the image.
2555 % o cube_info: A pointer to the Cube structure.
2557 % o node_info: pointer to node in color cube tree that is to be pruned.
2560 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2561 const NodeInfo *node_info)
2570 Traverse any children.
2572 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2573 for (i=0; i < (ssize_t) number_children; i++)
2574 if (node_info->child[i] != (NodeInfo *) NULL)
2575 PruneLevel(image,cube_info,node_info->child[i]);
2576 if (node_info->level == cube_info->depth)
2577 PruneChild(image,cube_info,node_info);
2581 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2585 + P r u n e T o C u b e D e p t h %
2589 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2591 % PruneToCubeDepth() deletes any nodes at a depth greater than
2592 % cube_info->depth while merging their color statistics into their parent
2595 % The format of the PruneToCubeDepth method is:
2597 % PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2598 % const NodeInfo *node_info)
2600 % A description of each parameter follows.
2602 % o cube_info: A pointer to the Cube structure.
2604 % o node_info: pointer to node in color cube tree that is to be pruned.
2607 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2608 const NodeInfo *node_info)
2617 Traverse any children.
2619 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2620 for (i=0; i < (ssize_t) number_children; i++)
2621 if (node_info->child[i] != (NodeInfo *) NULL)
2622 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2623 if (node_info->level > cube_info->depth)
2624 PruneChild(image,cube_info,node_info);
2628 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2632 % Q u a n t i z e I m a g e %
2636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2638 % QuantizeImage() analyzes the colors within a reference image and chooses a
2639 % fixed number of colors to represent the image. The goal of the algorithm
2640 % is to minimize the color difference between the input and output image while
2641 % minimizing the processing time.
2643 % The format of the QuantizeImage method is:
2645 % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2646 % Image *image,ExceptionInfo *exception)
2648 % A description of each parameter follows:
2650 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2652 % o image: the image.
2654 % o exception: return any errors or warnings in this structure.
2658 static MagickBooleanType DirectToColormapImage(Image *image,
2659 ExceptionInfo *exception)
2677 number_colors=(size_t) (image->columns*image->rows);
2678 if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2679 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2681 if (image->colors != number_colors)
2682 return(MagickFalse);
2684 image_view=AcquireAuthenticCacheView(image,exception);
2685 for (y=0; y < (ssize_t) image->rows; y++)
2696 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2697 if (q == (Quantum *) NULL)
2699 for (x=0; x < (ssize_t) image->columns; x++)
2701 image->colormap[i].red=(double) GetPixelRed(image,q);
2702 image->colormap[i].green=(double) GetPixelGreen(image,q);
2703 image->colormap[i].blue=(double) GetPixelBlue(image,q);
2704 image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2705 SetPixelIndex(image,(Quantum) i,q);
2707 q+=GetPixelChannels(image);
2709 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2711 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2713 if (proceed == MagickFalse)
2716 image_view=DestroyCacheView(image_view);
2720 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2721 Image *image,ExceptionInfo *exception)
2733 assert(quantize_info != (const QuantizeInfo *) NULL);
2734 assert(quantize_info->signature == MagickSignature);
2735 assert(image != (Image *) NULL);
2736 assert(image->signature == MagickSignature);
2737 if (image->debug != MagickFalse)
2738 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2739 maximum_colors=quantize_info->number_colors;
2740 if (maximum_colors == 0)
2741 maximum_colors=MaxColormapSize;
2742 if (maximum_colors > MaxColormapSize)
2743 maximum_colors=MaxColormapSize;
2744 if (image->alpha_trait != BlendPixelTrait)
2746 if ((image->columns*image->rows) <= maximum_colors)
2747 (void) DirectToColormapImage(image,exception);
2748 if (IsImageGray(image,exception) != MagickFalse)
2749 (void) SetGrayscaleImage(image,exception);
2751 if ((image->storage_class == PseudoClass) &&
2752 (image->colors <= maximum_colors))
2754 depth=quantize_info->tree_depth;
2761 Depth of color tree is: Log4(colormap size)+2.
2763 colors=maximum_colors;
2764 for (depth=1; colors != 0; depth++)
2766 if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2768 if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2772 Initialize color cube.
2774 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2775 if (cube_info == (CubeInfo *) NULL)
2776 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2778 status=ClassifyImageColors(cube_info,image,exception);
2779 if (status != MagickFalse)
2782 Reduce the number of colors in the image.
2784 ReduceImageColors(image,cube_info);
2785 status=AssignImageColors(image,cube_info,exception);
2787 DestroyCubeInfo(cube_info);
2792 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2796 % Q u a n t i z e I m a g e s %
2800 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2802 % QuantizeImages() analyzes the colors within a set of reference images and
2803 % chooses a fixed number of colors to represent the set. The goal of the
2804 % algorithm is to minimize the color difference between the input and output
2805 % images while minimizing the processing time.
2807 % The format of the QuantizeImages method is:
2809 % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2810 % Image *images,ExceptionInfo *exception)
2812 % A description of each parameter follows:
2814 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2816 % o images: Specifies a pointer to a list of Image structures.
2818 % o exception: return any errors or warnings in this structure.
2821 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2822 Image *images,ExceptionInfo *exception)
2834 MagickProgressMonitor
2845 assert(quantize_info != (const QuantizeInfo *) NULL);
2846 assert(quantize_info->signature == MagickSignature);
2847 assert(images != (Image *) NULL);
2848 assert(images->signature == MagickSignature);
2849 if (images->debug != MagickFalse)
2850 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2851 if (GetNextImageInList(images) == (Image *) NULL)
2854 Handle a single image with QuantizeImage.
2856 status=QuantizeImage(quantize_info,images,exception);
2860 maximum_colors=quantize_info->number_colors;
2861 if (maximum_colors == 0)
2862 maximum_colors=MaxColormapSize;
2863 if (maximum_colors > MaxColormapSize)
2864 maximum_colors=MaxColormapSize;
2865 depth=quantize_info->tree_depth;
2872 Depth of color tree is: Log4(colormap size)+2.
2874 colors=maximum_colors;
2875 for (depth=1; colors != 0; depth++)
2877 if (quantize_info->dither_method != NoDitherMethod)
2881 Initialize color cube.
2883 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2884 if (cube_info == (CubeInfo *) NULL)
2886 (void) ThrowMagickException(exception,GetMagickModule(),
2887 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2888 return(MagickFalse);
2890 number_images=GetImageListLength(images);
2892 for (i=0; image != (Image *) NULL; i++)
2894 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2895 image->client_data);
2896 status=ClassifyImageColors(cube_info,image,exception);
2897 if (status == MagickFalse)
2899 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2900 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2902 if (proceed == MagickFalse)
2904 image=GetNextImageInList(image);
2906 if (status != MagickFalse)
2909 Reduce the number of colors in an image sequence.
2911 ReduceImageColors(images,cube_info);
2913 for (i=0; image != (Image *) NULL; i++)
2915 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2916 NULL,image->client_data);
2917 status=AssignImageColors(image,cube_info,exception);
2918 if (status == MagickFalse)
2920 (void) SetImageProgressMonitor(image,progress_monitor,
2921 image->client_data);
2922 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2924 if (proceed == MagickFalse)
2926 image=GetNextImageInList(image);
2929 DestroyCubeInfo(cube_info);
2934 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2938 + Q u a n t i z e E r r o r F l a t t e n %
2942 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2944 % QuantizeErrorFlatten() traverses the color cube and flattens the quantization
2945 % error into a sorted 1D array. This accelerates the color reduction process.
2947 % Contributed by Yoya.
2949 % The format of the QuantizeImages method is:
2951 % size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2952 % const NodeInfo *node_info,const ssize_t offset,
2953 % MagickRealType *quantize_error)
2955 % A description of each parameter follows.
2957 % o image: the image.
2959 % o cube_info: A pointer to the Cube structure.
2961 % o node_info: pointer to node in color cube tree that is current pointer.
2963 % o offset: quantize error offset.
2965 % o quantize_error: the quantization error vector.
2968 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
2969 const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
2978 if (offset >= (ssize_t) cube_info->nodes)
2980 quantize_error[offset]=node_info->quantize_error;
2982 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2983 for (i=0; i < (ssize_t) number_children ; i++)
2984 if (node_info->child[i] != (NodeInfo *) NULL)
2985 n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
2991 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2999 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3001 % Reduce() traverses the color cube tree and prunes any node whose
3002 % quantization error falls below a particular threshold.
3004 % The format of the Reduce method is:
3006 % Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3008 % A description of each parameter follows.
3010 % o image: the image.
3012 % o cube_info: A pointer to the Cube structure.
3014 % o node_info: pointer to node in color cube tree that is to be pruned.
3017 static void Reduce(const Image *image,CubeInfo *cube_info,
3018 const NodeInfo *node_info)
3027 Traverse any children.
3029 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3030 for (i=0; i < (ssize_t) number_children; i++)
3031 if (node_info->child[i] != (NodeInfo *) NULL)
3032 Reduce(image,cube_info,node_info->child[i]);
3033 if (node_info->quantize_error <= cube_info->pruning_threshold)
3034 PruneChild(image,cube_info,node_info);
3038 Find minimum pruning threshold.
3040 if (node_info->number_unique > 0)
3041 cube_info->colors++;
3042 if (node_info->quantize_error < cube_info->next_threshold)
3043 cube_info->next_threshold=node_info->quantize_error;
3048 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3052 + R e d u c e I m a g e C o l o r s %
3056 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3058 % ReduceImageColors() repeatedly prunes the tree until the number of nodes
3059 % with n2 > 0 is less than or equal to the maximum number of colors allowed
3060 % in the output image. On any given iteration over the tree, it selects
3061 % those nodes whose E value is minimal for pruning and merges their
3062 % color statistics upward. It uses a pruning threshold, Ep, to govern
3063 % node selection as follows:
3066 % while number of nodes with (n2 > 0) > required maximum number of colors
3067 % prune all nodes such that E <= Ep
3068 % Set Ep to minimum E in remaining nodes
3070 % This has the effect of minimizing any quantization error when merging
3071 % two nodes together.
3073 % When a node to be pruned has offspring, the pruning procedure invokes
3074 % itself recursively in order to prune the tree from the leaves upward.
3075 % n2, Sr, Sg, and Sb in a node being pruned are always added to the
3076 % corresponding data in that node's parent. This retains the pruned
3077 % node's color characteristics for later averaging.
3079 % For each node, n2 pixels exist for which that node represents the
3080 % smallest volume in RGB space containing those pixel's colors. When n2
3081 % > 0 the node will uniquely define a color in the output image. At the
3082 % beginning of reduction, n2 = 0 for all nodes except a the leaves of
3083 % the tree which represent colors present in the input image.
3085 % The other pixel count, n1, indicates the total number of colors
3086 % within the cubic volume which the node represents. This includes n1 -
3087 % n2 pixels whose colors should be defined by nodes at a lower level in
3090 % The format of the ReduceImageColors method is:
3092 % ReduceImageColors(const Image *image,CubeInfo *cube_info)
3094 % A description of each parameter follows.
3096 % o image: the image.
3098 % o cube_info: A pointer to the Cube structure.
3102 static int MagickRealTypeCompare(const void *error_p,const void *error_q)
3108 p=(MagickRealType *) error_p;
3109 q=(MagickRealType *) error_q;
3112 if (fabs((double) (*q-*p)) <= MagickEpsilon)
3117 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3119 #define ReduceImageTag "Reduce/Image"
3130 cube_info->next_threshold=0.0;
3131 if ((cube_info->colors > cube_info->maximum_colors) && (cube_info->depth > 2))
3137 Enable rapid reduction of the number of unique colors.
3139 quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
3140 sizeof(*quantize_error));
3141 if (quantize_error != (MagickRealType *) NULL)
3143 (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3145 qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
3146 MagickRealTypeCompare);
3147 cube_info->next_threshold=quantize_error[cube_info->nodes-
3148 cube_info->maximum_colors];
3149 quantize_error=(MagickRealType *) RelinquishMagickMemory(
3153 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3155 cube_info->pruning_threshold=cube_info->next_threshold;
3156 cube_info->next_threshold=cube_info->root->quantize_error-1;
3157 cube_info->colors=0;
3158 Reduce(image,cube_info,cube_info->root);
3159 offset=(MagickOffsetType) span-cube_info->colors;
3160 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3161 cube_info->maximum_colors+1);
3162 if (proceed == MagickFalse)
3168 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3172 % R e m a p I m a g e %
3176 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3178 % RemapImage() replaces the colors of an image with a dither of the colors
3181 % The format of the RemapImage method is:
3183 % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3184 % Image *image,const Image *remap_image,ExceptionInfo *exception)
3186 % A description of each parameter follows:
3188 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3190 % o image: the image.
3192 % o remap_image: the reference image.
3194 % o exception: return any errors or warnings in this structure.
3197 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3198 Image *image,const Image *remap_image,ExceptionInfo *exception)
3207 Initialize color cube.
3209 assert(image != (Image *) NULL);
3210 assert(image->signature == MagickSignature);
3211 if (image->debug != MagickFalse)
3212 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3213 assert(remap_image != (Image *) NULL);
3214 assert(remap_image->signature == MagickSignature);
3215 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3216 quantize_info->number_colors);
3217 if (cube_info == (CubeInfo *) NULL)
3218 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3220 status=ClassifyImageColors(cube_info,remap_image,exception);
3221 if (status != MagickFalse)
3224 Classify image colors from the reference image.
3226 cube_info->quantize_info->number_colors=cube_info->colors;
3227 status=AssignImageColors(image,cube_info,exception);
3229 DestroyCubeInfo(cube_info);
3234 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3238 % R e m a p I m a g e s %
3242 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3244 % RemapImages() replaces the colors of a sequence of images with the
3245 % closest color from a reference image.
3247 % The format of the RemapImage method is:
3249 % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3250 % Image *images,Image *remap_image,ExceptionInfo *exception)
3252 % A description of each parameter follows:
3254 % o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3256 % o images: the image sequence.
3258 % o remap_image: the reference image.
3260 % o exception: return any errors or warnings in this structure.
3263 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3264 Image *images,const Image *remap_image,ExceptionInfo *exception)
3275 assert(images != (Image *) NULL);
3276 assert(images->signature == MagickSignature);
3277 if (images->debug != MagickFalse)
3278 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3280 if (remap_image == (Image *) NULL)
3283 Create a global colormap for an image sequence.
3285 status=QuantizeImages(quantize_info,images,exception);
3289 Classify image colors from the reference image.
3291 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3292 quantize_info->number_colors);
3293 if (cube_info == (CubeInfo *) NULL)
3294 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3296 status=ClassifyImageColors(cube_info,remap_image,exception);
3297 if (status != MagickFalse)
3300 Classify image colors from the reference image.
3302 cube_info->quantize_info->number_colors=cube_info->colors;
3304 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3306 status=AssignImageColors(image,cube_info,exception);
3307 if (status == MagickFalse)
3311 DestroyCubeInfo(cube_info);
3316 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3320 % S e t G r a y s c a l e I m a g e %
3324 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3326 % SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3328 % The format of the SetGrayscaleImage method is:
3330 % MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
3332 % A description of each parameter follows:
3334 % o image: The image.
3336 % o exception: return any errors or warnings in this structure.
3340 #if defined(__cplusplus) || defined(c_plusplus)
3344 static int IntensityCompare(const void *x,const void *y)
3353 color_1=(PixelInfo *) x;
3354 color_2=(PixelInfo *) y;
3355 intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
3356 GetPixelInfoIntensity(color_2));
3357 return((int) intensity);
3360 #if defined(__cplusplus) || defined(c_plusplus)
3364 static MagickBooleanType SetGrayscaleImage(Image *image,
3365 ExceptionInfo *exception)
3384 assert(image != (Image *) NULL);
3385 assert(image->signature == MagickSignature);
3386 if (image->type != GrayscaleType)
3387 (void) TransformImageColorspace(image,GRAYColorspace,exception);
3388 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3389 sizeof(*colormap_index));
3390 if (colormap_index == (ssize_t *) NULL)
3391 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3393 if (image->storage_class != PseudoClass)
3395 for (i=0; i <= (ssize_t) MaxMap; i++)
3396 colormap_index[i]=(-1);
3397 if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
3398 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3402 image_view=AcquireAuthenticCacheView(image,exception);
3403 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3404 #pragma omp parallel for schedule(static,4) shared(status) \
3405 magick_threads(image,image,image->rows,1)
3407 for (y=0; y < (ssize_t) image->rows; y++)
3415 if (status == MagickFalse)
3417 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3419 if (q == (Quantum *) NULL)
3424 for (x=0; x < (ssize_t) image->columns; x++)
3429 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3430 if (colormap_index[intensity] < 0)
3432 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3433 #pragma omp critical (MagickCore_SetGrayscaleImage)
3435 if (colormap_index[intensity] < 0)
3437 colormap_index[intensity]=(ssize_t) image->colors;
3438 image->colormap[image->colors].red=(double)
3439 GetPixelRed(image,q);
3440 image->colormap[image->colors].green=(double)
3441 GetPixelGreen(image,q);
3442 image->colormap[image->colors].blue=(double)
3443 GetPixelBlue(image,q);
3447 SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3448 q+=GetPixelChannels(image);
3450 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3453 image_view=DestroyCacheView(image_view);
3455 for (i=0; i < (ssize_t) image->colors; i++)
3456 image->colormap[i].alpha=(double) i;
3457 qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3459 colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3460 if (colormap == (PixelInfo *) NULL)
3461 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3464 colormap[j]=image->colormap[0];
3465 for (i=0; i < (ssize_t) image->colors; i++)
3467 if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3470 colormap[j]=image->colormap[i];
3472 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3474 image->colors=(size_t) (j+1);
3475 image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3476 image->colormap=colormap;
3478 image_view=AcquireAuthenticCacheView(image,exception);
3479 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3480 #pragma omp parallel for schedule(static,4) shared(status) \
3481 magick_threads(image,image,image->rows,1)
3483 for (y=0; y < (ssize_t) image->rows; y++)
3491 if (status == MagickFalse)
3493 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3494 if (q == (Quantum *) NULL)
3499 for (x=0; x < (ssize_t) image->columns; x++)
3501 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3502 GetPixelIndex(image,q))],q);
3503 q+=GetPixelChannels(image);
3505 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3508 image_view=DestroyCacheView(image_view);
3509 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3510 image->type=GrayscaleType;
3511 if (IsImageMonochrome(image,exception) != MagickFalse)
3512 image->type=BilevelType;