]> granicus.if.org Git - imagemagick/blob - MagickCore/quantize.c
Fixed initialization of array.
[imagemagick] / MagickCore / quantize.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
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            %
11 %                                                                             %
12 %                                                                             %
13 %    MagickCore Methods to Reduce the Number of Unique Colors in an Image     %
14 %                                                                             %
15 %                           Software Design                                   %
16 %                                Cristy                                       %
17 %                              July 1992                                      %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
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.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
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.
43 %
44 %  A reduction of colors in an image is also desirable for image
45 %  transmission and real-time animation.
46 %
47 %  QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 %  them down to some fixed number of colors.
49 %
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).
54 %
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 =
60 %  255.
61 %
62 %  The algorithm maps this domain onto a tree in which each node
63 %  represents a cube within that domain.  In the following discussion
64 %  these cubes are defined by the coordinate of two opposite vertices (vertex
65 %  nearest the origin in RGB space and the vertex farthest from the origin).
66 %
67 %  The tree's root node represents the entire domain, (0,0,0) through
68 %  (Cmax,Cmax,Cmax).  Each lower level in the tree is generated by
69 %  subdividing one node's cube into eight smaller cubes of equal size.
70 %  This corresponds to bisecting the parent cube with planes passing
71 %  through the midpoints of each edge.
72 %
73 %  The basic algorithm operates in three phases: Classification,
74 %  Reduction, and Assignment.  Classification builds a color description
75 %  tree for the image.  Reduction collapses the tree until the number it
76 %  represents, at most, the number of colors desired in the output image.
77 %  Assignment defines the output image's color map and sets each pixel's
78 %  color by restorage_class in the reduced tree.  Our goal is to minimize
79 %  the numerical discrepancies between the original colors and quantized
80 %  colors (quantization error).
81 %
82 %  Classification begins by initializing a color description tree of
83 %  sufficient depth to represent each possible input color in a leaf.
84 %  However, it is impractical to generate a fully-formed color description
85 %  tree in the storage_class phase for realistic values of Cmax.  If
86 %  colors components in the input image are quantized to k-bit precision,
87 %  so that Cmax= 2k-1, the tree would need k levels below the root node to
88 %  allow representing each possible input color in a leaf.  This becomes
89 %  prohibitive because the tree's total number of nodes is 1 +
90 %  sum(i=1, k, 8k).
91 %
92 %  A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
93 %  Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
94 %  Initializes data structures for nodes only as they are needed;  (2)
95 %  Chooses a maximum depth for the tree as a function of the desired
96 %  number of colors in the output image (currently log2(colormap size)).
97 %
98 %  For each pixel in the input image, storage_class scans downward from
99 %  the root of the color description tree.  At each level of the tree it
100 %  identifies the single node which represents a cube in RGB space
101 %  containing the pixel's color.  It updates the following data for each
102 %  such node:
103 %
104 %    n1: Number of pixels whose color is contained in the RGB cube which
105 %    this node represents;
106 %
107 %    n2: Number of pixels whose color is not represented in a node at
108 %    lower depth in the tree;  initially,  n2 = 0 for all nodes except
109 %    leaves of the tree.
110 %
111 %    Sr, Sg, Sb: Sums of the red, green, and blue component values for all
112 %    pixels not classified at a lower depth. The combination of these sums
113 %    and n2 will ultimately characterize the mean color of a set of
114 %    pixels represented by this node.
115 %
116 %    E: the distance squared in RGB space between each pixel contained
117 %    within a node and the nodes' center.  This represents the
118 %    quantization error for a node.
119 %
120 %  Reduction repeatedly prunes the tree until the number of nodes with n2
121 %  > 0 is less than or equal to the maximum number of colors allowed in
122 %  the output image.  On any given iteration over the tree, it selects
123 %  those nodes whose E count is minimal for pruning and merges their color
124 %  statistics upward. It uses a pruning threshold, Ep, to govern node
125 %  selection as follows:
126 %
127 %    Ep = 0
128 %    while number of nodes with (n2 > 0) > required maximum number of colors
129 %      prune all nodes such that E <= Ep
130 %      Set Ep to minimum E in remaining nodes
131 %
132 %  This has the effect of minimizing any quantization error when merging
133 %  two nodes together.
134 %
135 %  When a node to be pruned has offspring, the pruning procedure invokes
136 %  itself recursively in order to prune the tree from the leaves upward.
137 %  n2,  Sr, Sg,  and  Sb in a node being pruned are always added to the
138 %  corresponding data in that node's parent.  This retains the pruned
139 %  node's color characteristics for later averaging.
140 %
141 %  For each node, n2 pixels exist for which that node represents the
142 %  smallest volume in RGB space containing those pixel's colors.  When n2
143 %  > 0 the node will uniquely define a color in the output image. At the
144 %  beginning of reduction,  n2 = 0  for all nodes except a the leaves of
145 %  the tree which represent colors present in the input image.
146 %
147 %  The other pixel count, n1, indicates the total number of colors within
148 %  the cubic volume which the node represents.  This includes n1 - n2
149 %  pixels whose colors should be defined by nodes at a lower level in the
150 %  tree.
151 %
152 %  Assignment generates the output image from the pruned tree.  The output
153 %  image consists of two parts: (1)  A color map, which is an array of
154 %  color descriptions (RGB triples) for each color present in the output
155 %  image;  (2)  A pixel array, which represents each pixel as an index
156 %  into the color map array.
157 %
158 %  First, the assignment phase makes one pass over the pruned color
159 %  description tree to establish the image's color map.  For each node
160 %  with n2  > 0, it divides Sr, Sg, and Sb by n2 .  This produces the mean
161 %  color of all pixels that classify no lower than this node.  Each of
162 %  these colors becomes an entry in the color map.
163 %
164 %  Finally,  the assignment phase reclassifies each pixel in the pruned
165 %  tree to identify the deepest node containing the pixel's color.  The
166 %  pixel's value in the pixel array becomes the index of this node's mean
167 %  color in the color map.
168 %
169 %  This method is based on a similar algorithm written by Paul Raveling.
170 %
171 */
172 \f
173 /*
174   Include declarations.
175 */
176 #include "MagickCore/studio.h"
177 #include "MagickCore/attribute.h"
178 #include "MagickCore/cache-view.h"
179 #include "MagickCore/color.h"
180 #include "MagickCore/color-private.h"
181 #include "MagickCore/colormap.h"
182 #include "MagickCore/colorspace.h"
183 #include "MagickCore/colorspace-private.h"
184 #include "MagickCore/enhance.h"
185 #include "MagickCore/exception.h"
186 #include "MagickCore/exception-private.h"
187 #include "MagickCore/histogram.h"
188 #include "MagickCore/image.h"
189 #include "MagickCore/image-private.h"
190 #include "MagickCore/list.h"
191 #include "MagickCore/memory_.h"
192 #include "MagickCore/monitor.h"
193 #include "MagickCore/monitor-private.h"
194 #include "MagickCore/option.h"
195 #include "MagickCore/pixel-accessor.h"
196 #include "MagickCore/pixel-private.h"
197 #include "MagickCore/quantize.h"
198 #include "MagickCore/quantum.h"
199 #include "MagickCore/quantum-private.h"
200 #include "MagickCore/resource_.h"
201 #include "MagickCore/string_.h"
202 #include "MagickCore/thread-private.h"
203 \f
204 /*
205   Define declarations.
206 */
207 #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
208 #define CacheShift  2
209 #else
210 #define CacheShift  3
211 #endif
212 #define ErrorQueueLength  16
213 #define MaxNodes  266817
214 #define MaxTreeDepth  8
215 #define NodesInAList  1920
216 \f
217 /*
218   Typdef declarations.
219 */
220 typedef struct _RealPixelInfo
221 {
222   double
223     red,
224     green,
225     blue,
226     alpha;
227 } RealPixelInfo;
228
229 typedef struct _NodeInfo
230 {
231   struct _NodeInfo
232     *parent,
233     *child[16];
234
235   MagickSizeType
236     number_unique;
237
238   RealPixelInfo
239     total_color;
240
241   double
242     quantize_error;
243
244   size_t
245     color_number,
246     id,
247     level;
248 } NodeInfo;
249
250 typedef struct _Nodes
251 {
252   NodeInfo
253     *nodes;
254
255   struct _Nodes
256     *next;
257 } Nodes;
258
259 typedef struct _CubeInfo
260 {
261   NodeInfo
262     *root;
263
264   size_t
265     colors,
266     maximum_colors;
267
268   ssize_t
269     transparent_index;
270
271   MagickSizeType
272     transparent_pixels;
273
274   RealPixelInfo
275     target;
276
277   double
278     distance,
279     pruning_threshold,
280     next_threshold;
281
282   size_t
283     nodes,
284     free_nodes,
285     color_number;
286
287   NodeInfo
288     *next_node;
289
290   Nodes
291     *node_queue;
292
293   MemoryInfo
294     *memory_info;
295
296   ssize_t
297     *cache;
298
299   RealPixelInfo
300     error[ErrorQueueLength];
301
302   double
303     weights[ErrorQueueLength];
304
305   QuantizeInfo
306     *quantize_info;
307
308   MagickBooleanType
309     associate_alpha;
310
311   ssize_t
312     x,
313     y;
314
315   size_t
316     depth;
317
318   MagickOffsetType
319     offset;
320
321   MagickSizeType
322     span;
323 } CubeInfo;
324 \f
325 /*
326   Method prototypes.
327 */
328 static CubeInfo
329   *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
330
331 static NodeInfo
332   *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
333
334 static MagickBooleanType
335   AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
336   ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
337   DitherImage(Image *,CubeInfo *,ExceptionInfo *),
338   SetGrayscaleImage(Image *,ExceptionInfo *);
339
340 static size_t
341   DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
342
343 static void
344   ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
345   DestroyCubeInfo(CubeInfo *),
346   PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
347   PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
348   ReduceImageColors(const Image *,CubeInfo *);
349 \f
350 /*
351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
352 %                                                                             %
353 %                                                                             %
354 %                                                                             %
355 %   A c q u i r e Q u a n t i z e I n f o                                     %
356 %                                                                             %
357 %                                                                             %
358 %                                                                             %
359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
360 %
361 %  AcquireQuantizeInfo() allocates the QuantizeInfo structure.
362 %
363 %  The format of the AcquireQuantizeInfo method is:
364 %
365 %      QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
366 %
367 %  A description of each parameter follows:
368 %
369 %    o image_info: the image info.
370 %
371 */
372 MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
373 {
374   QuantizeInfo
375     *quantize_info;
376
377   quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
378   if (quantize_info == (QuantizeInfo *) NULL)
379     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
380   GetQuantizeInfo(quantize_info);
381   if (image_info != (ImageInfo *) NULL)
382     {
383       const char
384         *option;
385
386       quantize_info->dither_method=image_info->dither == MagickFalse ?
387         NoDitherMethod : RiemersmaDitherMethod;
388       option=GetImageOption(image_info,"dither");
389       if (option != (const char *) NULL)
390         quantize_info->dither_method=(DitherMethod) ParseCommandOption(
391           MagickDitherOptions,MagickFalse,option);
392       quantize_info->measure_error=image_info->verbose;
393     }
394   return(quantize_info);
395 }
396 \f
397 /*
398 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399 %                                                                             %
400 %                                                                             %
401 %                                                                             %
402 +   A s s i g n I m a g e C o l o r s                                         %
403 %                                                                             %
404 %                                                                             %
405 %                                                                             %
406 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
407 %
408 %  AssignImageColors() generates the output image from the pruned tree.  The
409 %  output image consists of two parts: (1)  A color map, which is an array
410 %  of color descriptions (RGB triples) for each color present in the
411 %  output image;  (2)  A pixel array, which represents each pixel as an
412 %  index into the color map array.
413 %
414 %  First, the assignment phase makes one pass over the pruned color
415 %  description tree to establish the image's color map.  For each node
416 %  with n2  > 0, it divides Sr, Sg, and Sb by n2 .  This produces the mean
417 %  color of all pixels that classify no lower than this node.  Each of
418 %  these colors becomes an entry in the color map.
419 %
420 %  Finally,  the assignment phase reclassifies each pixel in the pruned
421 %  tree to identify the deepest node containing the pixel's color.  The
422 %  pixel's value in the pixel array becomes the index of this node's mean
423 %  color in the color map.
424 %
425 %  The format of the AssignImageColors() method is:
426 %
427 %      MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
428 %
429 %  A description of each parameter follows.
430 %
431 %    o image: the image.
432 %
433 %    o cube_info: A pointer to the Cube structure.
434 %
435 */
436
437 static inline void AssociateAlphaPixel(const Image *image,
438   const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
439 {
440   double
441     alpha;
442
443   if ((cube_info->associate_alpha == MagickFalse) ||
444       (GetPixelAlpha(image,pixel) == OpaqueAlpha))
445     {
446       alpha_pixel->red=(double) GetPixelRed(image,pixel);
447       alpha_pixel->green=(double) GetPixelGreen(image,pixel);
448       alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
449       alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
450       return;
451     }
452   alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
453   alpha_pixel->red=alpha*GetPixelRed(image,pixel);
454   alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
455   alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
456   alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
457 }
458
459 static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
460   const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
461 {
462   double
463     alpha;
464
465   if ((cube_info->associate_alpha == MagickFalse) ||
466       (pixel->alpha == OpaqueAlpha))
467     {
468       alpha_pixel->red=(double) pixel->red;
469       alpha_pixel->green=(double) pixel->green;
470       alpha_pixel->blue=(double) pixel->blue;
471       alpha_pixel->alpha=(double) pixel->alpha;
472       return;
473     }
474   alpha=(double) (QuantumScale*pixel->alpha);
475   alpha_pixel->red=alpha*pixel->red;
476   alpha_pixel->green=alpha*pixel->green;
477   alpha_pixel->blue=alpha*pixel->blue;
478   alpha_pixel->alpha=(double) pixel->alpha;
479 }
480
481 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
482   const RealPixelInfo *pixel,size_t index)
483 {
484   size_t
485     id;
486
487   id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
488     ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
489     ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
490   if (cube_info->associate_alpha != MagickFalse)
491     id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
492   return(id);
493 }
494
495 static inline MagickBooleanType PreAssignImageColors(Image *image,
496   CubeInfo *cube_info,ExceptionInfo *exception)
497 {
498   /*
499     Allocate image colormap.
500   */
501   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
502       (cube_info->quantize_info->colorspace != CMYKColorspace))
503     (void) TransformImageColorspace((Image *) image,
504       cube_info->quantize_info->colorspace,exception);
505   else
506     if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
507       (void) TransformImageColorspace((Image *) image,sRGBColorspace,
508          exception);
509   if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
510     return(MagickFalse);
511   image->colors=0;
512   cube_info->transparent_pixels=0;
513   cube_info->transparent_index=(-1);
514   (void) DefineImageColormap(image,cube_info,cube_info->root);
515   return(MagickTrue);
516 }
517
518 static inline void PostAssignImageColors(Image *image,CubeInfo *cube_info,
519   ExceptionInfo *exception)
520 {
521   if (cube_info->quantize_info->measure_error != MagickFalse)
522     (void) GetImageQuantizeError(image,exception);
523   if ((cube_info->quantize_info->number_colors == 2) &&
524       (cube_info->quantize_info->colorspace == GRAYColorspace))
525     {
526       double
527         intensity;
528
529       register PixelInfo
530         *restrict q;
531
532       register ssize_t
533         i;
534
535       /*
536         Monochrome image.
537       */
538       q=image->colormap;
539       for (i=0; i < (ssize_t) image->colors; i++)
540       {
541         intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
542           QuantumRange);
543         q->red=intensity;
544         q->green=q->red;
545         q->blue=q->red;
546         q++;
547       }
548     }
549 }
550
551 static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
552   ExceptionInfo *exception)
553 {
554 #define AssignImageTag  "Assign/Image"
555
556   ssize_t
557     y;
558
559   if (PreAssignImageColors(image,cube_info,exception) == MagickFalse)
560     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
561       image->filename);
562   /*
563     Create a reduced color image.
564   */
565   if (cube_info->quantize_info->dither_method != NoDitherMethod)
566     (void) DitherImage(image,cube_info,exception);
567   else
568     {
569       CacheView
570         *image_view;
571
572       MagickBooleanType
573         status;
574
575       status=MagickTrue;
576       image_view=AcquireAuthenticCacheView(image,exception);
577 #if defined(MAGICKCORE_OPENMP_SUPPORT)
578       #pragma omp parallel for schedule(static,4) shared(status) \
579         magick_threads(image,image,image->rows,1)
580 #endif
581       for (y=0; y < (ssize_t) image->rows; y++)
582       {
583         CubeInfo
584           cube;
585
586         register Quantum
587           *restrict q;
588
589         register ssize_t
590           x;
591
592         ssize_t
593           count;
594
595         if (status == MagickFalse)
596           continue;
597         q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
598           exception);
599         if (q == (Quantum *) NULL)
600           {
601             status=MagickFalse;
602             continue;
603           }
604         cube=(*cube_info);
605         for (x=0; x < (ssize_t) image->columns; x+=count)
606         {
607           RealPixelInfo
608             pixel;
609
610           register const NodeInfo
611             *node_info;
612
613           register ssize_t
614             i;
615
616           size_t
617             id,
618             index;
619
620           /*
621             Identify the deepest node containing the pixel's color.
622           */
623           for (count=1; (x+count) < (ssize_t) image->columns; count++)
624           {
625             PixelInfo
626               packet;
627
628             GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
629             if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
630               break;
631           }
632           AssociateAlphaPixel(image,&cube,q,&pixel);
633           node_info=cube.root;
634           for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
635           {
636             id=ColorToNodeId(&cube,&pixel,index);
637             if (node_info->child[id] == (NodeInfo *) NULL)
638               break;
639             node_info=node_info->child[id];
640           }
641           /*
642             Find closest color among siblings and their children.
643           */
644           cube.target=pixel;
645           cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
646             1.0);
647           ClosestColor(image,&cube,node_info->parent);
648           index=cube.color_number;
649           for (i=0; i < (ssize_t) count; i++)
650           {
651             if (image->storage_class == PseudoClass)
652               SetPixelIndex(image,(Quantum) index,q);
653             if (cube.quantize_info->measure_error == MagickFalse)
654               {
655                 SetPixelRed(image,ClampToQuantum(
656                   image->colormap[index].red),q);
657                 SetPixelGreen(image,ClampToQuantum(
658                   image->colormap[index].green),q);
659                 SetPixelBlue(image,ClampToQuantum(
660                   image->colormap[index].blue),q);
661                 if (cube.associate_alpha != MagickFalse)
662                   SetPixelAlpha(image,ClampToQuantum(
663                     image->colormap[index].alpha),q);
664               }
665             q+=GetPixelChannels(image);
666           }
667         }
668         if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
669           status=MagickFalse;
670         if (image->progress_monitor != (MagickProgressMonitor) NULL)
671           {
672             MagickBooleanType
673               proceed;
674
675 #if defined(MAGICKCORE_OPENMP_SUPPORT)
676             #pragma omp critical (MagickCore_AssignImageColors)
677 #endif
678             proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
679               image->rows);
680             if (proceed == MagickFalse)
681               status=MagickFalse;
682           }
683       }
684       image_view=DestroyCacheView(image_view);
685     }
686   PostAssignImageColors(image,cube_info,exception);
687   (void) SyncImage(image,exception);
688   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
689       (cube_info->quantize_info->colorspace != CMYKColorspace))
690     (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
691   return(MagickTrue);
692 }
693 \f
694 /*
695 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
696 %                                                                             %
697 %                                                                             %
698 %                                                                             %
699 +   C l a s s i f y I m a g e C o l o r s                                     %
700 %                                                                             %
701 %                                                                             %
702 %                                                                             %
703 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
704 %
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
713 %  1 + sum(i=1,k,8k).
714 %
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)).
720 %
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:
725 %
726 %    n1 : Number of pixels whose color is contained in the RGB cube
727 %    which this node represents;
728 %
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.
732 %
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.
737 %
738 %    E: the distance squared in RGB space between each pixel contained
739 %    within a node and the nodes' center.  This represents the quantization
740 %    error for a node.
741 %
742 %  The format of the ClassifyImageColors() method is:
743 %
744 %      MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
745 %        const Image *image,ExceptionInfo *exception)
746 %
747 %  A description of each parameter follows.
748 %
749 %    o cube_info: A pointer to the Cube structure.
750 %
751 %    o image: the image.
752 %
753 */
754
755 static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
756 {
757   MagickBooleanType
758     associate_alpha;
759
760   associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
761     MagickFalse;
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;
766 }
767
768 static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
769   const Image *image,ExceptionInfo *exception)
770 {
771 #define ClassifyImageTag  "Classify/Image"
772
773   CacheView
774     *image_view;
775
776   MagickBooleanType
777     proceed;
778
779   double
780     bisect;
781
782   NodeInfo
783     *node_info;
784
785   RealPixelInfo
786     error,
787     mid,
788     midpoint,
789     pixel;
790
791   size_t
792     count,
793     id,
794     index,
795     level;
796
797   ssize_t
798     y;
799
800   /*
801     Classify the first cube_info->maximum_colors colors to a tree depth of 8.
802   */
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);
808   else
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;
815   error.alpha=0.0;
816   image_view=AcquireVirtualCacheView(image,exception);
817   for (y=0; y < (ssize_t) image->rows; y++)
818   {
819     register const Quantum
820       *restrict p;
821
822     register ssize_t
823       x;
824
825     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
826     if (p == (const Quantum *) NULL)
827       break;
828     if (cube_info->nodes > MaxNodes)
829       {
830         /*
831           Prune one level if the color tree is too large.
832         */
833         PruneLevel(image,cube_info,cube_info->root);
834         cube_info->depth--;
835       }
836     for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
837     {
838       /*
839         Start at the root and descend the color cube tree.
840       */
841       for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
842       {
843         PixelInfo
844           packet;
845
846         GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
847         if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
848           break;
849       }
850       AssociateAlphaPixel(image,cube_info,p,&pixel);
851       index=MaxTreeDepth-1;
852       bisect=((double) QuantumRange+1.0)/2.0;
853       mid=midpoint;
854       node_info=cube_info->root;
855       for (level=1; level <= MaxTreeDepth; level++)
856       {
857         double
858           distance;
859
860         bisect*=0.5;
861         id=ColorToNodeId(cube_info,&pixel,index);
862         mid.red+=(id & 1) != 0 ? bisect : -bisect;
863         mid.green+=(id & 2) != 0 ? bisect : -bisect;
864         mid.blue+=(id & 4) != 0 ? bisect : -bisect;
865         mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
866         if (node_info->child[id] == (NodeInfo *) NULL)
867           {
868             /*
869               Set colors of new node to contain pixel.
870             */
871             node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
872             if (node_info->child[id] == (NodeInfo *) NULL)
873               {
874                 (void) ThrowMagickException(exception,GetMagickModule(),
875                   ResourceLimitError,"MemoryAllocationFailed","`%s'",
876                   image->filename);
877                 continue;
878               }
879             if (level == MaxTreeDepth)
880               cube_info->colors++;
881           }
882         /*
883           Approximate the quantization error represented by this node.
884         */
885         node_info=node_info->child[id];
886         error.red=QuantumScale*(pixel.red-mid.red);
887         error.green=QuantumScale*(pixel.green-mid.green);
888         error.blue=QuantumScale*(pixel.blue-mid.blue);
889         if (cube_info->associate_alpha != MagickFalse)
890           error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
891         distance=(double) (error.red*error.red+error.green*error.green+
892           error.blue*error.blue+error.alpha*error.alpha);
893         if (IsNaN(distance) != MagickFalse)
894           distance=0.0;
895         node_info->quantize_error+=count*sqrt(distance);
896         cube_info->root->quantize_error+=node_info->quantize_error;
897         index--;
898       }
899       /*
900         Sum RGB for this leaf for later derivation of the mean cube color.
901       */
902       node_info->number_unique+=count;
903       node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
904       node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
905       node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
906       if (cube_info->associate_alpha != MagickFalse)
907         node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
908           pixel.alpha);
909       p+=count*GetPixelChannels(image);
910     }
911     if (cube_info->colors > cube_info->maximum_colors)
912       {
913         PruneToCubeDepth(image,cube_info,cube_info->root);
914         break;
915       }
916     proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
917       image->rows);
918     if (proceed == MagickFalse)
919       break;
920   }
921   for (y++; y < (ssize_t) image->rows; y++)
922   {
923     register const Quantum
924       *restrict p;
925
926     register ssize_t
927       x;
928
929     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
930     if (p == (const Quantum *) NULL)
931       break;
932     if (cube_info->nodes > MaxNodes)
933       {
934         /*
935           Prune one level if the color tree is too large.
936         */
937         PruneLevel(image,cube_info,cube_info->root);
938         cube_info->depth--;
939       }
940     for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
941     {
942       /*
943         Start at the root and descend the color cube tree.
944       */
945       for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
946       {
947         PixelInfo
948           packet;
949
950         GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
951         if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
952           break;
953       }
954       AssociateAlphaPixel(image,cube_info,p,&pixel);
955       index=MaxTreeDepth-1;
956       bisect=((double) QuantumRange+1.0)/2.0;
957       mid=midpoint;
958       node_info=cube_info->root;
959       for (level=1; level <= cube_info->depth; level++)
960       {
961         double
962           distance;
963
964         bisect*=0.5;
965         id=ColorToNodeId(cube_info,&pixel,index);
966         mid.red+=(id & 1) != 0 ? bisect : -bisect;
967         mid.green+=(id & 2) != 0 ? bisect : -bisect;
968         mid.blue+=(id & 4) != 0 ? bisect : -bisect;
969         mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
970         if (node_info->child[id] == (NodeInfo *) NULL)
971           {
972             /*
973               Set colors of new node to contain pixel.
974             */
975             node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
976             if (node_info->child[id] == (NodeInfo *) NULL)
977               {
978                 (void) ThrowMagickException(exception,GetMagickModule(),
979                   ResourceLimitError,"MemoryAllocationFailed","%s",
980                   image->filename);
981                 continue;
982               }
983             if (level == cube_info->depth)
984               cube_info->colors++;
985           }
986         /*
987           Approximate the quantization error represented by this node.
988         */
989         node_info=node_info->child[id];
990         error.red=QuantumScale*(pixel.red-mid.red);
991         error.green=QuantumScale*(pixel.green-mid.green);
992         error.blue=QuantumScale*(pixel.blue-mid.blue);
993         if (cube_info->associate_alpha != MagickFalse)
994           error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
995         distance=(double) (error.red*error.red+error.green*error.green+
996           error.blue*error.blue+error.alpha*error.alpha);
997         if (IsNaN(distance) != MagickFalse)
998           distance=0.0;
999         node_info->quantize_error+=count*sqrt(distance);
1000         cube_info->root->quantize_error+=node_info->quantize_error;
1001         index--;
1002       }
1003       /*
1004         Sum RGB for this leaf for later derivation of the mean cube color.
1005       */
1006       node_info->number_unique+=count;
1007       node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
1008       node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
1009       node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
1010       if (cube_info->associate_alpha != MagickFalse)
1011         node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
1012           pixel.alpha);
1013       p+=count*GetPixelChannels(image);
1014     }
1015     proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
1016       image->rows);
1017     if (proceed == MagickFalse)
1018       break;
1019   }
1020   image_view=DestroyCacheView(image_view);
1021   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
1022       (cube_info->quantize_info->colorspace != CMYKColorspace))
1023     (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
1024   return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
1025 }
1026 \f
1027 /*
1028 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1029 %                                                                             %
1030 %                                                                             %
1031 %                                                                             %
1032 %   C l o n e Q u a n t i z e I n f o                                         %
1033 %                                                                             %
1034 %                                                                             %
1035 %                                                                             %
1036 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1037 %
1038 %  CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1039 %  or if quantize info is NULL, a new one.
1040 %
1041 %  The format of the CloneQuantizeInfo method is:
1042 %
1043 %      QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1044 %
1045 %  A description of each parameter follows:
1046 %
1047 %    o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1048 %      quantize info, or if image info is NULL a new one.
1049 %
1050 %    o quantize_info: a structure of type info.
1051 %
1052 */
1053 MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1054 {
1055   QuantizeInfo
1056     *clone_info;
1057
1058   clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
1059   if (clone_info == (QuantizeInfo *) NULL)
1060     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1061   GetQuantizeInfo(clone_info);
1062   if (quantize_info == (QuantizeInfo *) NULL)
1063     return(clone_info);
1064   clone_info->number_colors=quantize_info->number_colors;
1065   clone_info->tree_depth=quantize_info->tree_depth;
1066   clone_info->dither_method=quantize_info->dither_method;
1067   clone_info->colorspace=quantize_info->colorspace;
1068   clone_info->measure_error=quantize_info->measure_error;
1069   return(clone_info);
1070 }
1071 \f
1072 /*
1073 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1074 %                                                                             %
1075 %                                                                             %
1076 %                                                                             %
1077 +   C l o s e s t C o l o r                                                   %
1078 %                                                                             %
1079 %                                                                             %
1080 %                                                                             %
1081 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1082 %
1083 %  ClosestColor() traverses the color cube tree at a particular node and
1084 %  determines which colormap entry best represents the input color.
1085 %
1086 %  The format of the ClosestColor method is:
1087 %
1088 %      void ClosestColor(const Image *image,CubeInfo *cube_info,
1089 %        const NodeInfo *node_info)
1090 %
1091 %  A description of each parameter follows.
1092 %
1093 %    o image: the image.
1094 %
1095 %    o cube_info: A pointer to the Cube structure.
1096 %
1097 %    o node_info: the address of a structure of type NodeInfo which points to a
1098 %      node in the color cube tree that is to be pruned.
1099 %
1100 */
1101 static void ClosestColor(const Image *image,CubeInfo *cube_info,
1102   const NodeInfo *node_info)
1103 {
1104   register ssize_t
1105     i;
1106
1107   size_t
1108     number_children;
1109
1110   /*
1111     Traverse any children.
1112   */
1113   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1114   for (i=0; i < (ssize_t) number_children; i++)
1115     if (node_info->child[i] != (NodeInfo *) NULL)
1116       ClosestColor(image,cube_info,node_info->child[i]);
1117   if (node_info->number_unique != 0)
1118     {
1119       double
1120         pixel;
1121
1122       register double
1123         alpha,
1124         beta,
1125         distance;
1126
1127       register PixelInfo
1128         *restrict p;
1129
1130       register RealPixelInfo
1131         *restrict q;
1132
1133       /*
1134         Determine if this color is "closest".
1135       */
1136       p=image->colormap+node_info->color_number;
1137       q=(&cube_info->target);
1138       alpha=1.0;
1139       beta=1.0;
1140       if (cube_info->associate_alpha != MagickFalse)
1141         {
1142           alpha=(double) (QuantumScale*p->alpha);
1143           beta=(double) (QuantumScale*q->alpha);
1144         }
1145       pixel=alpha*p->red-beta*q->red;
1146       distance=pixel*pixel;
1147       if (distance <= cube_info->distance)
1148         {
1149           pixel=alpha*p->green-beta*q->green;
1150           distance+=pixel*pixel;
1151           if (distance <= cube_info->distance)
1152             {
1153               pixel=alpha*p->blue-beta*q->blue;
1154               distance+=pixel*pixel;
1155               if (distance <= cube_info->distance)
1156                 {
1157                   pixel=alpha-beta;
1158                   distance+=pixel*pixel;
1159                   if (distance <= cube_info->distance)
1160                     {
1161                       cube_info->distance=distance;
1162                       cube_info->color_number=node_info->color_number;
1163                     }
1164                 }
1165             }
1166         }
1167     }
1168 }
1169 \f
1170 /*
1171 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1172 %                                                                             %
1173 %                                                                             %
1174 %                                                                             %
1175 %   C o m p r e s s I m a g e C o l o r m a p                                 %
1176 %                                                                             %
1177 %                                                                             %
1178 %                                                                             %
1179 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1180 %
1181 %  CompressImageColormap() compresses an image colormap by removing any
1182 %  duplicate or unused color entries.
1183 %
1184 %  The format of the CompressImageColormap method is:
1185 %
1186 %      MagickBooleanType CompressImageColormap(Image *image,
1187 %        ExceptionInfo *exception)
1188 %
1189 %  A description of each parameter follows:
1190 %
1191 %    o image: the image.
1192 %
1193 %    o exception: return any errors or warnings in this structure.
1194 %
1195 */
1196 MagickExport MagickBooleanType CompressImageColormap(Image *image,
1197   ExceptionInfo *exception)
1198 {
1199   QuantizeInfo
1200     quantize_info;
1201
1202   assert(image != (Image *) NULL);
1203   assert(image->signature == MagickCoreSignature);
1204   if (image->debug != MagickFalse)
1205     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1206   if (IsPaletteImage(image,exception) == MagickFalse)
1207     return(MagickFalse);
1208   GetQuantizeInfo(&quantize_info);
1209   quantize_info.number_colors=image->colors;
1210   quantize_info.tree_depth=MaxTreeDepth;
1211   return(QuantizeImage(&quantize_info,image,exception));
1212 }
1213 \f
1214 /*
1215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1216 %                                                                             %
1217 %                                                                             %
1218 %                                                                             %
1219 +   D e f i n e I m a g e C o l o r m a p                                     %
1220 %                                                                             %
1221 %                                                                             %
1222 %                                                                             %
1223 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1224 %
1225 %  DefineImageColormap() traverses the color cube tree and notes each colormap
1226 %  entry.  A colormap entry is any node in the color cube tree where the
1227 %  of unique colors is not zero.  DefineImageColormap() returns the number of
1228 %  colors in the image colormap.
1229 %
1230 %  The format of the DefineImageColormap method is:
1231 %
1232 %      size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1233 %        NodeInfo *node_info)
1234 %
1235 %  A description of each parameter follows.
1236 %
1237 %    o image: the image.
1238 %
1239 %    o cube_info: A pointer to the Cube structure.
1240 %
1241 %    o node_info: the address of a structure of type NodeInfo which points to a
1242 %      node in the color cube tree that is to be pruned.
1243 %
1244 */
1245 static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
1246   NodeInfo *node_info)
1247 {
1248   register ssize_t
1249     i;
1250
1251   size_t
1252     number_children;
1253
1254   /*
1255     Traverse any children.
1256   */
1257   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
1258   for (i=0; i < (ssize_t) number_children; i++)
1259     if (node_info->child[i] != (NodeInfo *) NULL)
1260       (void) DefineImageColormap(image,cube_info,node_info->child[i]);
1261   if (node_info->number_unique != 0)
1262     {
1263       register double
1264         alpha;
1265
1266       register PixelInfo
1267         *restrict q;
1268
1269       /*
1270         Colormap entry is defined by the mean color in this cube.
1271       */
1272       q=image->colormap+image->colors;
1273       alpha=(double) ((MagickOffsetType) node_info->number_unique);
1274       alpha=PerceptibleReciprocal(alpha);
1275       if (cube_info->associate_alpha == MagickFalse)
1276         {
1277           q->red=(double) ClampToQuantum(alpha*QuantumRange*
1278             node_info->total_color.red);
1279           q->green=(double) ClampToQuantum(alpha*QuantumRange*
1280             node_info->total_color.green);
1281           q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1282             node_info->total_color.blue);
1283           q->alpha=(double) OpaqueAlpha;
1284         }
1285       else
1286         {
1287           double
1288             opacity;
1289
1290           opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
1291           q->alpha=(double) ClampToQuantum(opacity);
1292           if (q->alpha == OpaqueAlpha)
1293             {
1294               q->red=(double) ClampToQuantum(alpha*QuantumRange*
1295                 node_info->total_color.red);
1296               q->green=(double) ClampToQuantum(alpha*QuantumRange*
1297                 node_info->total_color.green);
1298               q->blue=(double) ClampToQuantum(alpha*QuantumRange*
1299                 node_info->total_color.blue);
1300             }
1301           else
1302             {
1303               double
1304                 gamma;
1305
1306               gamma=(double) (QuantumScale*q->alpha);
1307               gamma=PerceptibleReciprocal(gamma);
1308               q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1309                 node_info->total_color.red);
1310               q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1311                 node_info->total_color.green);
1312               q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
1313                 node_info->total_color.blue);
1314               if (node_info->number_unique > cube_info->transparent_pixels)
1315                 {
1316                   cube_info->transparent_pixels=node_info->number_unique;
1317                   cube_info->transparent_index=(ssize_t) image->colors;
1318                 }
1319             }
1320         }
1321       node_info->color_number=image->colors++;
1322     }
1323   return(image->colors);
1324 }
1325 \f
1326 /*
1327 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1328 %                                                                             %
1329 %                                                                             %
1330 %                                                                             %
1331 +   D e s t r o y C u b e I n f o                                             %
1332 %                                                                             %
1333 %                                                                             %
1334 %                                                                             %
1335 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1336 %
1337 %  DestroyCubeInfo() deallocates memory associated with an image.
1338 %
1339 %  The format of the DestroyCubeInfo method is:
1340 %
1341 %      DestroyCubeInfo(CubeInfo *cube_info)
1342 %
1343 %  A description of each parameter follows:
1344 %
1345 %    o cube_info: the address of a structure of type CubeInfo.
1346 %
1347 */
1348 static void DestroyCubeInfo(CubeInfo *cube_info)
1349 {
1350   register Nodes
1351     *nodes;
1352
1353   /*
1354     Release color cube tree storage.
1355   */
1356   do
1357   {
1358     nodes=cube_info->node_queue->next;
1359     cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1360       cube_info->node_queue->nodes);
1361     cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1362       cube_info->node_queue);
1363     cube_info->node_queue=nodes;
1364   } while (cube_info->node_queue != (Nodes *) NULL);
1365   if (cube_info->memory_info != (MemoryInfo *) NULL)
1366     cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
1367   cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1368   cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1369 }
1370 \f
1371 /*
1372 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1373 %                                                                             %
1374 %                                                                             %
1375 %                                                                             %
1376 %   D e s t r o y Q u a n t i z e I n f o                                     %
1377 %                                                                             %
1378 %                                                                             %
1379 %                                                                             %
1380 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1381 %
1382 %  DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1383 %  structure.
1384 %
1385 %  The format of the DestroyQuantizeInfo method is:
1386 %
1387 %      QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1388 %
1389 %  A description of each parameter follows:
1390 %
1391 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1392 %
1393 */
1394 MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1395 {
1396   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1397   assert(quantize_info != (QuantizeInfo *) NULL);
1398   assert(quantize_info->signature == MagickCoreSignature);
1399   quantize_info->signature=(~MagickCoreSignature);
1400   quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1401   return(quantize_info);
1402 }
1403 \f
1404 /*
1405 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1406 %                                                                             %
1407 %                                                                             %
1408 %                                                                             %
1409 +   D i t h e r I m a g e                                                     %
1410 %                                                                             %
1411 %                                                                             %
1412 %                                                                             %
1413 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1414 %
1415 %  DitherImage() distributes the difference between an original image and
1416 %  the corresponding color reduced algorithm to neighboring pixels using
1417 %  serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1418 %  MagickTrue if the image is dithered otherwise MagickFalse.
1419 %
1420 %  The format of the DitherImage method is:
1421 %
1422 %      MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1423 %        ExceptionInfo *exception)
1424 %
1425 %  A description of each parameter follows.
1426 %
1427 %    o image: the image.
1428 %
1429 %    o cube_info: A pointer to the Cube structure.
1430 %
1431 %    o exception: return any errors or warnings in this structure.
1432 %
1433 */
1434
1435 static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
1436 {
1437   register ssize_t
1438     i;
1439
1440   assert(pixels != (RealPixelInfo **) NULL);
1441   for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
1442     if (pixels[i] != (RealPixelInfo *) NULL)
1443       pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
1444   pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
1445   return(pixels);
1446 }
1447
1448 static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
1449 {
1450   RealPixelInfo
1451     **pixels;
1452
1453   register ssize_t
1454     i;
1455
1456   size_t
1457     number_threads;
1458
1459   number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
1460   pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
1461     sizeof(*pixels));
1462   if (pixels == (RealPixelInfo **) NULL)
1463     return((RealPixelInfo **) NULL);
1464   (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1465   for (i=0; i < (ssize_t) number_threads; i++)
1466   {
1467     pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
1468     if (pixels[i] == (RealPixelInfo *) NULL)
1469       return(DestroyPixelThreadSet(pixels));
1470   }
1471   return(pixels);
1472 }
1473
1474 static inline ssize_t CacheOffset(CubeInfo *cube_info,
1475   const RealPixelInfo *pixel)
1476 {
1477 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1478 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1479 #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1480 #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1481
1482   ssize_t
1483     offset;
1484
1485   offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
1486     GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
1487     BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
1488   if (cube_info->associate_alpha != MagickFalse)
1489     offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
1490   return(offset);
1491 }
1492
1493 static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
1494   ExceptionInfo *exception)
1495 {
1496 #define DitherImageTag  "Dither/Image"
1497
1498   CacheView
1499     *image_view;
1500
1501   MagickBooleanType
1502     status;
1503
1504   RealPixelInfo
1505     **pixels;
1506
1507   ssize_t
1508     y;
1509
1510   /*
1511     Distribute quantization error using Floyd-Steinberg.
1512   */
1513   pixels=AcquirePixelThreadSet(image->columns);
1514   if (pixels == (RealPixelInfo **) NULL)
1515     return(MagickFalse);
1516   status=MagickTrue;
1517   image_view=AcquireAuthenticCacheView(image,exception);
1518   for (y=0; y < (ssize_t) image->rows; y++)
1519   {
1520     const int
1521       id = GetOpenMPThreadId();
1522
1523     CubeInfo
1524       cube;
1525
1526     RealPixelInfo
1527       *current,
1528       *previous;
1529
1530     register Quantum
1531       *restrict q;
1532
1533     register ssize_t
1534       x;
1535
1536     size_t
1537       index;
1538
1539     ssize_t
1540       v;
1541
1542     if (status == MagickFalse)
1543       continue;
1544     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1545     if (q == (Quantum *) NULL)
1546       {
1547         status=MagickFalse;
1548         continue;
1549       }
1550     cube=(*cube_info);
1551     current=pixels[id]+(y & 0x01)*image->columns;
1552     previous=pixels[id]+((y+1) & 0x01)*image->columns;
1553     v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
1554     for (x=0; x < (ssize_t) image->columns; x++)
1555     {
1556       RealPixelInfo
1557         color,
1558         pixel;
1559
1560       register ssize_t
1561         i;
1562
1563       ssize_t
1564         u;
1565
1566       u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1567       AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel);
1568       if (x > 0)
1569         {
1570           pixel.red+=7*current[u-v].red/16;
1571           pixel.green+=7*current[u-v].green/16;
1572           pixel.blue+=7*current[u-v].blue/16;
1573           if (cube.associate_alpha != MagickFalse)
1574             pixel.alpha+=7*current[u-v].alpha/16;
1575         }
1576       if (y > 0)
1577         {
1578           if (x < (ssize_t) (image->columns-1))
1579             {
1580               pixel.red+=previous[u+v].red/16;
1581               pixel.green+=previous[u+v].green/16;
1582               pixel.blue+=previous[u+v].blue/16;
1583               if (cube.associate_alpha != MagickFalse)
1584                 pixel.alpha+=previous[u+v].alpha/16;
1585             }
1586           pixel.red+=5*previous[u].red/16;
1587           pixel.green+=5*previous[u].green/16;
1588           pixel.blue+=5*previous[u].blue/16;
1589           if (cube.associate_alpha != MagickFalse)
1590             pixel.alpha+=5*previous[u].alpha/16;
1591           if (x > 0)
1592             {
1593               pixel.red+=3*previous[u-v].red/16;
1594               pixel.green+=3*previous[u-v].green/16;
1595               pixel.blue+=3*previous[u-v].blue/16;
1596               if (cube.associate_alpha != MagickFalse)
1597                 pixel.alpha+=3*previous[u-v].alpha/16;
1598             }
1599         }
1600       pixel.red=(double) ClampPixel(pixel.red);
1601       pixel.green=(double) ClampPixel(pixel.green);
1602       pixel.blue=(double) ClampPixel(pixel.blue);
1603       if (cube.associate_alpha != MagickFalse)
1604         pixel.alpha=(double) ClampPixel(pixel.alpha);
1605       i=CacheOffset(&cube,&pixel);
1606       if (cube.cache[i] < 0)
1607         {
1608           register NodeInfo
1609             *node_info;
1610
1611           register size_t
1612             id;
1613
1614           /*
1615             Identify the deepest node containing the pixel's color.
1616           */
1617           node_info=cube.root;
1618           for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1619           {
1620             id=ColorToNodeId(&cube,&pixel,index);
1621             if (node_info->child[id] == (NodeInfo *) NULL)
1622               break;
1623             node_info=node_info->child[id];
1624           }
1625           /*
1626             Find closest color among siblings and their children.
1627           */
1628           cube.target=pixel;
1629           cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1630             1.0);
1631           ClosestColor(image,&cube,node_info->parent);
1632           cube.cache[i]=(ssize_t) cube.color_number;
1633         }
1634       /*
1635         Assign pixel to closest colormap entry.
1636       */
1637       index=(size_t) cube.cache[i];
1638       if (image->storage_class == PseudoClass)
1639         SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image));
1640       if (cube.quantize_info->measure_error == MagickFalse)
1641         {
1642           SetPixelRed(image,ClampToQuantum(image->colormap[index].red),
1643             q+u*GetPixelChannels(image));
1644           SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),
1645             q+u*GetPixelChannels(image));
1646           SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),
1647             q+u*GetPixelChannels(image));
1648           if (cube.associate_alpha != MagickFalse)
1649             SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),
1650               q+u*GetPixelChannels(image));
1651         }
1652       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1653         status=MagickFalse;
1654       /*
1655         Store the error.
1656       */
1657       AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
1658       current[u].red=pixel.red-color.red;
1659       current[u].green=pixel.green-color.green;
1660       current[u].blue=pixel.blue-color.blue;
1661       if (cube.associate_alpha != MagickFalse)
1662         current[u].alpha=pixel.alpha-color.alpha;
1663       if (image->progress_monitor != (MagickProgressMonitor) NULL)
1664         {
1665           MagickBooleanType
1666             proceed;
1667
1668           proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1669             image->rows);
1670           if (proceed == MagickFalse)
1671             status=MagickFalse;
1672         }
1673     }
1674   }
1675   image_view=DestroyCacheView(image_view);
1676   pixels=DestroyPixelThreadSet(pixels);
1677   return(MagickTrue);
1678 }
1679
1680 static MagickBooleanType
1681   RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
1682     ExceptionInfo *);
1683
1684 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1685   const size_t level,const unsigned int direction,ExceptionInfo *exception)
1686 {
1687   if (level == 1)
1688     switch (direction)
1689     {
1690       case WestGravity:
1691       {
1692         (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1693           exception);
1694         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1695           exception);
1696         (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1697           exception);
1698         break;
1699       }
1700       case EastGravity:
1701       {
1702         (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1703           exception);
1704         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1705           exception);
1706         (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1707           exception);
1708         break;
1709       }
1710       case NorthGravity:
1711       {
1712         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1713           exception);
1714         (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1715           exception);
1716         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1717           exception);
1718         break;
1719       }
1720       case SouthGravity:
1721       {
1722         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1723           exception);
1724         (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1725           exception);
1726         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1727           exception);
1728         break;
1729       }
1730       default:
1731         break;
1732     }
1733   else
1734     switch (direction)
1735     {
1736       case WestGravity:
1737       {
1738         Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1739           exception);
1740         (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1741           exception);
1742         Riemersma(image,image_view,cube_info,level-1,WestGravity,
1743           exception);
1744         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1745           exception);
1746         Riemersma(image,image_view,cube_info,level-1,WestGravity,
1747           exception);
1748         (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1749           exception);
1750         Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1751           exception);
1752         break;
1753       }
1754       case EastGravity:
1755       {
1756         Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1757           exception);
1758         (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1759           exception);
1760         Riemersma(image,image_view,cube_info,level-1,EastGravity,
1761           exception);
1762         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1763           exception);
1764         Riemersma(image,image_view,cube_info,level-1,EastGravity,
1765           exception);
1766         (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1767           exception);
1768         Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1769           exception);
1770         break;
1771       }
1772       case NorthGravity:
1773       {
1774         Riemersma(image,image_view,cube_info,level-1,WestGravity,
1775           exception);
1776         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1777           exception);
1778         Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1779           exception);
1780         (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
1781           exception);
1782         Riemersma(image,image_view,cube_info,level-1,NorthGravity,
1783           exception);
1784         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1785           exception);
1786         Riemersma(image,image_view,cube_info,level-1,EastGravity,
1787           exception);
1788         break;
1789       }
1790       case SouthGravity:
1791       {
1792         Riemersma(image,image_view,cube_info,level-1,EastGravity,
1793           exception);
1794         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
1795           exception);
1796         Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1797           exception);
1798         (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
1799           exception);
1800         Riemersma(image,image_view,cube_info,level-1,SouthGravity,
1801           exception);
1802         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
1803           exception);
1804         Riemersma(image,image_view,cube_info,level-1,WestGravity,
1805           exception);
1806         break;
1807       }
1808       default:
1809         break;
1810     }
1811 }
1812
1813 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1814   CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
1815 {
1816 #define DitherImageTag  "Dither/Image"
1817
1818   MagickBooleanType
1819     proceed;
1820
1821   RealPixelInfo
1822     color,
1823     pixel;
1824
1825   register CubeInfo
1826     *p;
1827
1828   size_t
1829     index;
1830
1831   p=cube_info;
1832   if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1833       (p->y >= 0) && (p->y < (ssize_t) image->rows))
1834     {
1835       register Quantum
1836         *restrict q;
1837
1838       register ssize_t
1839         i;
1840
1841       /*
1842         Distribute error.
1843       */
1844       q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1845       if (q == (Quantum *) NULL)
1846         return(MagickFalse);
1847       AssociateAlphaPixel(image,cube_info,q,&pixel);
1848       for (i=0; i < ErrorQueueLength; i++)
1849       {
1850         pixel.red+=p->weights[i]*p->error[i].red;
1851         pixel.green+=p->weights[i]*p->error[i].green;
1852         pixel.blue+=p->weights[i]*p->error[i].blue;
1853         if (cube_info->associate_alpha != MagickFalse)
1854           pixel.alpha+=p->weights[i]*p->error[i].alpha;
1855       }
1856       pixel.red=(double) ClampPixel(pixel.red);
1857       pixel.green=(double) ClampPixel(pixel.green);
1858       pixel.blue=(double) ClampPixel(pixel.blue);
1859       if (cube_info->associate_alpha != MagickFalse)
1860         pixel.alpha=(double) ClampPixel(pixel.alpha);
1861       i=CacheOffset(cube_info,&pixel);
1862       if (p->cache[i] < 0)
1863         {
1864           register NodeInfo
1865             *node_info;
1866
1867           register size_t
1868             id;
1869
1870           /*
1871             Identify the deepest node containing the pixel's color.
1872           */
1873           node_info=p->root;
1874           for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1875           {
1876             id=ColorToNodeId(cube_info,&pixel,index);
1877             if (node_info->child[id] == (NodeInfo *) NULL)
1878               break;
1879             node_info=node_info->child[id];
1880           }
1881           /*
1882             Find closest color among siblings and their children.
1883           */
1884           p->target=pixel;
1885           p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
1886             QuantumRange+1.0)+1.0);
1887           ClosestColor(image,p,node_info->parent);
1888           p->cache[i]=(ssize_t) p->color_number;
1889         }
1890       /*
1891         Assign pixel to closest colormap entry.
1892       */
1893       index=(size_t) p->cache[i];
1894       if (image->storage_class == PseudoClass)
1895         SetPixelIndex(image,(Quantum) index,q);
1896       if (cube_info->quantize_info->measure_error == MagickFalse)
1897         {
1898           SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
1899           SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
1900           SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
1901           if (cube_info->associate_alpha != MagickFalse)
1902             SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
1903         }
1904       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1905         return(MagickFalse);
1906       /*
1907         Propagate the error as the last entry of the error queue.
1908       */
1909       (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1910         sizeof(p->error[0]));
1911       AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
1912       p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1913       p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1914       p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1915       if (cube_info->associate_alpha != MagickFalse)
1916         p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
1917       proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1918       if (proceed == MagickFalse)
1919         return(MagickFalse);
1920       p->offset++;
1921     }
1922   switch (direction)
1923   {
1924     case WestGravity: p->x--; break;
1925     case EastGravity: p->x++; break;
1926     case NorthGravity: p->y--; break;
1927     case SouthGravity: p->y++; break;
1928   }
1929   return(MagickTrue);
1930 }
1931
1932 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
1933   ExceptionInfo *exception)
1934 {
1935   CacheView
1936     *image_view;
1937
1938   MagickBooleanType
1939     status;
1940
1941   register ssize_t
1942     i;
1943
1944   size_t
1945     depth;
1946
1947   if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1948     return(FloydSteinbergDither(image,cube_info,exception));
1949   /*
1950     Distribute quantization error along a Hilbert curve.
1951   */
1952   (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1953     sizeof(*cube_info->error));
1954   cube_info->x=0;
1955   cube_info->y=0;
1956   i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1957   for (depth=1; i != 0; depth++)
1958     i>>=1;
1959   if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1960     depth++;
1961   cube_info->offset=0;
1962   cube_info->span=(MagickSizeType) image->columns*image->rows;
1963   image_view=AcquireAuthenticCacheView(image,exception);
1964   if (depth > 1)
1965     Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
1966   status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
1967   image_view=DestroyCacheView(image_view);
1968   return(status);
1969 }
1970 \f
1971 /*
1972 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1973 %                                                                             %
1974 %                                                                             %
1975 %                                                                             %
1976 +   G e t C u b e I n f o                                                     %
1977 %                                                                             %
1978 %                                                                             %
1979 %                                                                             %
1980 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1981 %
1982 %  GetCubeInfo() initialize the Cube data structure.
1983 %
1984 %  The format of the GetCubeInfo method is:
1985 %
1986 %      CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1987 %        const size_t depth,const size_t maximum_colors)
1988 %
1989 %  A description of each parameter follows.
1990 %
1991 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1992 %
1993 %    o depth: Normally, this integer value is zero or one.  A zero or
1994 %      one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1995 %      A tree of this depth generally allows the best representation of the
1996 %      reference image with the least amount of memory and the fastest
1997 %      computational speed.  In some cases, such as an image with low color
1998 %      dispersion (a few number of colors), a value other than
1999 %      Log4(number_colors) is required.  To expand the color tree completely,
2000 %      use a value of 8.
2001 %
2002 %    o maximum_colors: maximum colors.
2003 %
2004 */
2005 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
2006   const size_t depth,const size_t maximum_colors)
2007 {
2008   CubeInfo
2009     *cube_info;
2010
2011   double
2012     sum,
2013     weight;
2014
2015   register ssize_t
2016     i;
2017
2018   size_t
2019     length;
2020
2021   /*
2022     Initialize tree to describe color cube_info.
2023   */
2024   cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
2025   if (cube_info == (CubeInfo *) NULL)
2026     return((CubeInfo *) NULL);
2027   (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
2028   cube_info->depth=depth;
2029   if (cube_info->depth > MaxTreeDepth)
2030     cube_info->depth=MaxTreeDepth;
2031   if (cube_info->depth < 2)
2032     cube_info->depth=2;
2033   cube_info->maximum_colors=maximum_colors;
2034   /*
2035     Initialize root node.
2036   */
2037   cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
2038   if (cube_info->root == (NodeInfo *) NULL)
2039     return((CubeInfo *) NULL);
2040   cube_info->root->parent=cube_info->root;
2041   cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
2042   if (cube_info->quantize_info->dither_method == NoDitherMethod)
2043     return(cube_info);
2044   /*
2045     Initialize dither resources.
2046   */
2047   length=(size_t) (1UL << (4*(8-CacheShift)));
2048   cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
2049   if (cube_info->memory_info == (MemoryInfo *) NULL)
2050     return((CubeInfo *) NULL);
2051   cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
2052   /*
2053     Initialize color cache.
2054   */
2055   (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)*
2056     length);
2057   /*
2058     Distribute weights along a curve of exponential decay.
2059   */
2060   weight=1.0;
2061   for (i=0; i < ErrorQueueLength; i++)
2062   {
2063     cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
2064     weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2065   }
2066   /*
2067     Normalize the weighting factors.
2068   */
2069   weight=0.0;
2070   for (i=0; i < ErrorQueueLength; i++)
2071     weight+=cube_info->weights[i];
2072   sum=0.0;
2073   for (i=0; i < ErrorQueueLength; i++)
2074   {
2075     cube_info->weights[i]/=weight;
2076     sum+=cube_info->weights[i];
2077   }
2078   cube_info->weights[0]+=1.0-sum;
2079   return(cube_info);
2080 }
2081 \f
2082 /*
2083 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2084 %                                                                             %
2085 %                                                                             %
2086 %                                                                             %
2087 +   G e t N o d e I n f o                                                     %
2088 %                                                                             %
2089 %                                                                             %
2090 %                                                                             %
2091 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2092 %
2093 %  GetNodeInfo() allocates memory for a new node in the color cube tree and
2094 %  presets all fields to zero.
2095 %
2096 %  The format of the GetNodeInfo method is:
2097 %
2098 %      NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2099 %        const size_t level,NodeInfo *parent)
2100 %
2101 %  A description of each parameter follows.
2102 %
2103 %    o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2104 %
2105 %    o id: Specifies the child number of the node.
2106 %
2107 %    o level: Specifies the level in the storage_class the node resides.
2108 %
2109 */
2110 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2111   const size_t level,NodeInfo *parent)
2112 {
2113   NodeInfo
2114     *node_info;
2115
2116   if (cube_info->free_nodes == 0)
2117     {
2118       Nodes
2119         *nodes;
2120
2121       /*
2122         Allocate a new queue of nodes.
2123       */
2124       nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2125       if (nodes == (Nodes *) NULL)
2126         return((NodeInfo *) NULL);
2127       nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2128         sizeof(*nodes->nodes));
2129       if (nodes->nodes == (NodeInfo *) NULL)
2130         return((NodeInfo *) NULL);
2131       nodes->next=cube_info->node_queue;
2132       cube_info->node_queue=nodes;
2133       cube_info->next_node=nodes->nodes;
2134       cube_info->free_nodes=NodesInAList;
2135     }
2136   cube_info->nodes++;
2137   cube_info->free_nodes--;
2138   node_info=cube_info->next_node++;
2139   (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2140   node_info->parent=parent;
2141   node_info->id=id;
2142   node_info->level=level;
2143   return(node_info);
2144 }
2145 \f
2146 /*
2147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2148 %                                                                             %
2149 %                                                                             %
2150 %                                                                             %
2151 %  G e t I m a g e Q u a n t i z e E r r o r                                  %
2152 %                                                                             %
2153 %                                                                             %
2154 %                                                                             %
2155 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2156 %
2157 %  GetImageQuantizeError() measures the difference between the original
2158 %  and quantized images.  This difference is the total quantization error.
2159 %  The error is computed by summing over all pixels in an image the distance
2160 %  squared in RGB space between each reference pixel value and its quantized
2161 %  value.  These values are computed:
2162 %
2163 %    o mean_error_per_pixel:  This value is the mean error for any single
2164 %      pixel in the image.
2165 %
2166 %    o normalized_mean_square_error:  This value is the normalized mean
2167 %      quantization error for any single pixel in the image.  This distance
2168 %      measure is normalized to a range between 0 and 1.  It is independent
2169 %      of the range of red, green, and blue values in the image.
2170 %
2171 %    o normalized_maximum_square_error:  Thsi value is the normalized
2172 %      maximum quantization error for any single pixel in the image.  This
2173 %      distance measure is normalized to a range between 0 and 1.  It is
2174 %      independent of the range of red, green, and blue values in your image.
2175 %
2176 %  The format of the GetImageQuantizeError method is:
2177 %
2178 %      MagickBooleanType GetImageQuantizeError(Image *image,
2179 %        ExceptionInfo *exception)
2180 %
2181 %  A description of each parameter follows.
2182 %
2183 %    o image: the image.
2184 %
2185 %    o exception: return any errors or warnings in this structure.
2186 %
2187 */
2188 MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
2189   ExceptionInfo *exception)
2190 {
2191   CacheView
2192     *image_view;
2193
2194   double
2195     alpha,
2196     area,
2197     beta,
2198     distance,
2199     maximum_error,
2200     mean_error,
2201     mean_error_per_pixel;
2202
2203   size_t
2204     index;
2205
2206   ssize_t
2207     y;
2208
2209   assert(image != (Image *) NULL);
2210   assert(image->signature == MagickCoreSignature);
2211   if (image->debug != MagickFalse)
2212     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2213   image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
2214   (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2215   if (image->storage_class == DirectClass)
2216     return(MagickTrue);
2217   alpha=1.0;
2218   beta=1.0;
2219   area=3.0*image->columns*image->rows;
2220   maximum_error=0.0;
2221   mean_error_per_pixel=0.0;
2222   mean_error=0.0;
2223   image_view=AcquireVirtualCacheView(image,exception);
2224   for (y=0; y < (ssize_t) image->rows; y++)
2225   {
2226     register const Quantum
2227       *restrict p;
2228
2229     register ssize_t
2230       x;
2231
2232     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2233     if (p == (const Quantum *) NULL)
2234       break;
2235     for (x=0; x < (ssize_t) image->columns; x++)
2236     {
2237       index=GetPixelIndex(image,p);
2238       if (image->alpha_trait == BlendPixelTrait)
2239         {
2240           alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
2241           beta=(double) (QuantumScale*image->colormap[index].alpha);
2242         }
2243       distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
2244         image->colormap[index].red));
2245       mean_error_per_pixel+=distance;
2246       mean_error+=distance*distance;
2247       if (distance > maximum_error)
2248         maximum_error=distance;
2249       distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
2250         image->colormap[index].green));
2251       mean_error_per_pixel+=distance;
2252       mean_error+=distance*distance;
2253       if (distance > maximum_error)
2254         maximum_error=distance;
2255       distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta*
2256         image->colormap[index].blue));
2257       mean_error_per_pixel+=distance;
2258       mean_error+=distance*distance;
2259       if (distance > maximum_error)
2260         maximum_error=distance;
2261       p+=GetPixelChannels(image);
2262     }
2263   }
2264   image_view=DestroyCacheView(image_view);
2265   image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2266   image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2267     mean_error/area;
2268   image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2269   return(MagickTrue);
2270 }
2271 \f
2272 /*
2273 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2274 %                                                                             %
2275 %                                                                             %
2276 %                                                                             %
2277 %   G e t Q u a n t i z e I n f o                                             %
2278 %                                                                             %
2279 %                                                                             %
2280 %                                                                             %
2281 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2282 %
2283 %  GetQuantizeInfo() initializes the QuantizeInfo structure.
2284 %
2285 %  The format of the GetQuantizeInfo method is:
2286 %
2287 %      GetQuantizeInfo(QuantizeInfo *quantize_info)
2288 %
2289 %  A description of each parameter follows:
2290 %
2291 %    o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2292 %
2293 */
2294 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2295 {
2296   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2297   assert(quantize_info != (QuantizeInfo *) NULL);
2298   (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2299   quantize_info->number_colors=256;
2300   quantize_info->dither_method=RiemersmaDitherMethod;
2301   quantize_info->colorspace=UndefinedColorspace;
2302   quantize_info->measure_error=MagickFalse;
2303   quantize_info->signature=MagickCoreSignature;
2304 }
2305 \f
2306 /*
2307 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2308 %                                                                             %
2309 %                                                                             %
2310 %                                                                             %
2311 %     P o s t e r i z e I m a g e                                             %
2312 %                                                                             %
2313 %                                                                             %
2314 %                                                                             %
2315 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2316 %
2317 %  PosterizeImage() reduces the image to a limited number of colors for a
2318 %  "poster" effect.
2319 %
2320 %  The format of the PosterizeImage method is:
2321 %
2322 %      MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2323 %        const DitherMethod dither_method,ExceptionInfo *exception)
2324 %
2325 %  A description of each parameter follows:
2326 %
2327 %    o image: Specifies a pointer to an Image structure.
2328 %
2329 %    o levels: Number of color levels allowed in each channel.  Very low values
2330 %      (2, 3, or 4) have the most visible effect.
2331 %
2332 %    o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
2333 %      RiemersmaDitherMethod, FloydSteinbergDitherMethod.
2334 %
2335 %    o exception: return any errors or warnings in this structure.
2336 %
2337 */
2338
2339 static inline double MagickRound(double x)
2340 {
2341   /*
2342     Round the fraction to nearest integer.
2343   */
2344   if ((x-floor(x)) < (ceil(x)-x))
2345     return(floor(x));
2346   return(ceil(x));
2347 }
2348
2349 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2350   const DitherMethod dither_method,ExceptionInfo *exception)
2351 {
2352 #define PosterizeImageTag  "Posterize/Image"
2353 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2354   QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2355
2356   CacheView
2357     *image_view;
2358
2359   MagickBooleanType
2360     status;
2361
2362   MagickOffsetType
2363     progress;
2364
2365   QuantizeInfo
2366     *quantize_info;
2367
2368   register ssize_t
2369     i;
2370
2371   ssize_t
2372     y;
2373
2374   assert(image != (Image *) NULL);
2375   assert(image->signature == MagickCoreSignature);
2376   if (image->debug != MagickFalse)
2377     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2378   assert(exception != (ExceptionInfo *) NULL);
2379   assert(exception->signature == MagickCoreSignature);
2380   if (image->storage_class == PseudoClass)
2381 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2382     #pragma omp parallel for schedule(static,4) shared(progress,status) \
2383       magick_threads(image,image,1,1)
2384 #endif
2385     for (i=0; i < (ssize_t) image->colors; i++)
2386     {
2387       /*
2388         Posterize colormap.
2389       */
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);
2402     }
2403   /*
2404     Posterize image.
2405   */
2406   status=MagickTrue;
2407   progress=0;
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)
2412 #endif
2413   for (y=0; y < (ssize_t) image->rows; y++)
2414   {
2415     register Quantum
2416       *restrict q;
2417
2418     register ssize_t
2419       x;
2420
2421     if (status == MagickFalse)
2422       continue;
2423     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2424     if (q == (Quantum *) NULL)
2425       {
2426         status=MagickFalse;
2427         continue;
2428       }
2429     for (x=0; x < (ssize_t) image->columns; x++)
2430     {
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);
2444     }
2445     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2446       status=MagickFalse;
2447     if (image->progress_monitor != (MagickProgressMonitor) NULL)
2448       {
2449         MagickBooleanType
2450           proceed;
2451
2452 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2453         #pragma omp critical (MagickCore_PosterizeImage)
2454 #endif
2455         proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2456           image->rows);
2457         if (proceed == MagickFalse)
2458           status=MagickFalse;
2459       }
2460   }
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);
2469   return(status);
2470 }
2471 \f
2472 /*
2473 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2474 %                                                                             %
2475 %                                                                             %
2476 %                                                                             %
2477 +   P r u n e C h i l d                                                       %
2478 %                                                                             %
2479 %                                                                             %
2480 %                                                                             %
2481 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2482 %
2483 %  PruneChild() deletes the given node and merges its statistics into its
2484 %  parent.
2485 %
2486 %  The format of the PruneSubtree method is:
2487 %
2488 %      PruneChild(const Image *image,CubeInfo *cube_info,
2489 %        const NodeInfo *node_info)
2490 %
2491 %  A description of each parameter follows.
2492 %
2493 %    o image: the image.
2494 %
2495 %    o cube_info: A pointer to the Cube structure.
2496 %
2497 %    o node_info: pointer to node in color cube tree that is to be pruned.
2498 %
2499 */
2500 static void PruneChild(const Image *image,CubeInfo *cube_info,
2501   const NodeInfo *node_info)
2502 {
2503   NodeInfo
2504     *parent;
2505
2506   register ssize_t
2507     i;
2508
2509   size_t
2510     number_children;
2511
2512   /*
2513     Traverse any children.
2514   */
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]);
2519   /*
2520     Merge color statistics into parent.
2521   */
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;
2529   cube_info->nodes--;
2530 }
2531 \f
2532 /*
2533 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2534 %                                                                             %
2535 %                                                                             %
2536 %                                                                             %
2537 +  P r u n e L e v e l                                                        %
2538 %                                                                             %
2539 %                                                                             %
2540 %                                                                             %
2541 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2542 %
2543 %  PruneLevel() deletes all nodes at the bottom level of the color tree merging
2544 %  their color statistics into their parent node.
2545 %
2546 %  The format of the PruneLevel method is:
2547 %
2548 %      PruneLevel(const Image *image,CubeInfo *cube_info,
2549 %        const NodeInfo *node_info)
2550 %
2551 %  A description of each parameter follows.
2552 %
2553 %    o image: the image.
2554 %
2555 %    o cube_info: A pointer to the Cube structure.
2556 %
2557 %    o node_info: pointer to node in color cube tree that is to be pruned.
2558 %
2559 */
2560 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2561   const NodeInfo *node_info)
2562 {
2563   register ssize_t
2564     i;
2565
2566   size_t
2567     number_children;
2568
2569   /*
2570     Traverse any children.
2571   */
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);
2578 }
2579 \f
2580 /*
2581 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2582 %                                                                             %
2583 %                                                                             %
2584 %                                                                             %
2585 +  P r u n e T o C u b e D e p t h                                            %
2586 %                                                                             %
2587 %                                                                             %
2588 %                                                                             %
2589 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2590 %
2591 %  PruneToCubeDepth() deletes any nodes at a depth greater than
2592 %  cube_info->depth while merging their color statistics into their parent
2593 %  node.
2594 %
2595 %  The format of the PruneToCubeDepth method is:
2596 %
2597 %      PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2598 %        const NodeInfo *node_info)
2599 %
2600 %  A description of each parameter follows.
2601 %
2602 %    o cube_info: A pointer to the Cube structure.
2603 %
2604 %    o node_info: pointer to node in color cube tree that is to be pruned.
2605 %
2606 */
2607 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2608   const NodeInfo *node_info)
2609 {
2610   register ssize_t
2611     i;
2612
2613   size_t
2614     number_children;
2615
2616   /*
2617     Traverse any children.
2618   */
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);
2625 }
2626 \f
2627 /*
2628 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2629 %                                                                             %
2630 %                                                                             %
2631 %                                                                             %
2632 %  Q u a n t i z e I m a g e                                                  %
2633 %                                                                             %
2634 %                                                                             %
2635 %                                                                             %
2636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2637 %
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.
2642 %
2643 %  The format of the QuantizeImage method is:
2644 %
2645 %      MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2646 %        Image *image,ExceptionInfo *exception)
2647 %
2648 %  A description of each parameter follows:
2649 %
2650 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2651 %
2652 %    o image: the image.
2653 %
2654 %    o exception: return any errors or warnings in this structure.
2655 %
2656 */
2657
2658 static MagickBooleanType DirectToPseudoClassImage(Image *image,
2659   CubeInfo *cube_info,ExceptionInfo *exception)
2660 {
2661   MagickBooleanType
2662     status;
2663
2664   ssize_t
2665     y;
2666
2667   if (cube_info->colors > cube_info->maximum_colors)
2668     return(MagickFalse);
2669   if (PreAssignImageColors(image,cube_info,exception) == MagickFalse)
2670     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2671       image->filename);
2672   status=MagickTrue;
2673 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2674   #pragma omp parallel for schedule(static,4) shared(status) \
2675      magick_threads(image,image,image->rows,1)
2676 #endif
2677   for (y=0; y < (ssize_t) image->rows; y++)
2678   {
2679     register Quantum
2680       *restrict q;
2681
2682     register ssize_t
2683       x;
2684
2685     if (status == MagickFalse)
2686       continue;
2687     q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
2688     if (q == (Quantum *) NULL)
2689       {
2690         status=MagickFalse;
2691         continue;
2692       }
2693     for (x=0; x < (ssize_t) image->columns; x++)
2694     {
2695       register ssize_t
2696         i;
2697
2698       for (i=0; i < (ssize_t) image->colors; i++)
2699       {
2700         if (IsPixelEquivalent(image,q,&image->colormap[i]) == MagickFalse)
2701           continue;
2702         SetPixelIndex(image,(Quantum) i,q);
2703         break;
2704       }
2705       q+=GetPixelChannels(image);
2706     }
2707     if (SyncAuthenticPixels(image,exception) == MagickFalse)
2708       status=MagickFalse;
2709   }
2710   image->storage_class=PseudoClass;
2711   PostAssignImageColors(image,cube_info,exception);
2712   return(status);
2713 }
2714
2715 static MagickBooleanType DirectToColormapImage(Image *image,
2716   ExceptionInfo *exception)
2717 {
2718   CacheView
2719     *image_view;
2720
2721   MagickBooleanType
2722     status;
2723
2724   register ssize_t
2725     i;
2726
2727   size_t
2728     number_colors;
2729
2730   ssize_t
2731     y;
2732
2733   status=MagickTrue;
2734   number_colors=(size_t) (image->columns*image->rows);
2735   if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
2736     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2737       image->filename);
2738   if (image->colors != number_colors)
2739     return(MagickFalse);
2740   i=0;
2741   image_view=AcquireAuthenticCacheView(image,exception);
2742   for (y=0; y < (ssize_t) image->rows; y++)
2743   {
2744     MagickBooleanType
2745       proceed;
2746
2747     register Quantum
2748       *restrict q;
2749
2750     register ssize_t
2751       x;
2752
2753     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2754     if (q == (Quantum *) NULL)
2755       break;
2756     for (x=0; x < (ssize_t) image->columns; x++)
2757     {
2758       image->colormap[i].red=(double) GetPixelRed(image,q);
2759       image->colormap[i].green=(double) GetPixelGreen(image,q);
2760       image->colormap[i].blue=(double) GetPixelBlue(image,q);
2761       image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
2762       SetPixelIndex(image,(Quantum) i,q);
2763       i++;
2764       q+=GetPixelChannels(image);
2765     }
2766     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2767       break;
2768     proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2769       image->rows);
2770     if (proceed == MagickFalse)
2771       status=MagickFalse;
2772   }
2773   image_view=DestroyCacheView(image_view);
2774   return(status);
2775 }
2776
2777 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2778   Image *image,ExceptionInfo *exception)
2779 {
2780   CubeInfo
2781     *cube_info;
2782
2783   MagickBooleanType
2784     status;
2785
2786   size_t
2787     depth,
2788     maximum_colors;
2789
2790   assert(quantize_info != (const QuantizeInfo *) NULL);
2791   assert(quantize_info->signature == MagickCoreSignature);
2792   assert(image != (Image *) NULL);
2793   assert(image->signature == MagickCoreSignature);
2794   if (image->debug != MagickFalse)
2795     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2796   assert(exception != (ExceptionInfo *) NULL);
2797   assert(exception->signature == MagickCoreSignature);
2798   maximum_colors=quantize_info->number_colors;
2799   if (maximum_colors == 0)
2800     maximum_colors=MaxColormapSize;
2801   if (maximum_colors > MaxColormapSize)
2802     maximum_colors=MaxColormapSize;
2803   if (image->alpha_trait != BlendPixelTrait)
2804     {
2805       if ((image->columns*image->rows) <= maximum_colors)
2806         (void) DirectToColormapImage(image,exception);
2807       if (SetImageGray(image,exception) != MagickFalse)
2808         (void) SetGrayscaleImage(image,exception);
2809     }
2810   if ((image->storage_class == PseudoClass) &&
2811       (image->colors <= maximum_colors))
2812     {
2813       if ((quantize_info->colorspace != UndefinedColorspace) &&
2814           (quantize_info->colorspace != CMYKColorspace))
2815         (void) TransformImageColorspace(image,quantize_info->colorspace,
2816           exception);
2817       return(MagickTrue);
2818     }
2819   depth=quantize_info->tree_depth;
2820   if (depth == 0)
2821     {
2822       size_t
2823         colors;
2824
2825       /*
2826         Depth of color tree is: Log4(colormap size)+2.
2827       */
2828       colors=maximum_colors;
2829       for (depth=1; colors != 0; depth++)
2830         colors>>=2;
2831       if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
2832         depth--;
2833       if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
2834         depth--;
2835       if (SetImageGray(image,exception) != MagickFalse)
2836         depth=MaxTreeDepth;
2837     }
2838   /*
2839     Initialize color cube.
2840   */
2841   cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2842   if (cube_info == (CubeInfo *) NULL)
2843     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2844       image->filename);
2845   status=ClassifyImageColors(cube_info,image,exception);
2846   if (status != MagickFalse)
2847     {
2848       /*
2849         Reduce the number of colors in the image.
2850       */
2851       status=DirectToPseudoClassImage(image,cube_info,exception);
2852       if (status == MagickFalse)
2853       {
2854         ReduceImageColors(image,cube_info);
2855         status=AssignImageColors(image,cube_info,exception);
2856       }
2857     }
2858   DestroyCubeInfo(cube_info);
2859   return(status);
2860 }
2861 \f
2862 /*
2863 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2864 %                                                                             %
2865 %                                                                             %
2866 %                                                                             %
2867 %   Q u a n t i z e I m a g e s                                               %
2868 %                                                                             %
2869 %                                                                             %
2870 %                                                                             %
2871 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2872 %
2873 %  QuantizeImages() analyzes the colors within a set of reference images and
2874 %  chooses a fixed number of colors to represent the set.  The goal of the
2875 %  algorithm is to minimize the color difference between the input and output
2876 %  images while minimizing the processing time.
2877 %
2878 %  The format of the QuantizeImages method is:
2879 %
2880 %      MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2881 %        Image *images,ExceptionInfo *exception)
2882 %
2883 %  A description of each parameter follows:
2884 %
2885 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2886 %
2887 %    o images: Specifies a pointer to a list of Image structures.
2888 %
2889 %    o exception: return any errors or warnings in this structure.
2890 %
2891 */
2892 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2893   Image *images,ExceptionInfo *exception)
2894 {
2895   CubeInfo
2896     *cube_info;
2897
2898   Image
2899     *image;
2900
2901   MagickBooleanType
2902     proceed,
2903     status;
2904
2905   MagickProgressMonitor
2906     progress_monitor;
2907
2908   register ssize_t
2909     i;
2910
2911   size_t
2912     depth,
2913     maximum_colors,
2914     number_images;
2915
2916   assert(quantize_info != (const QuantizeInfo *) NULL);
2917   assert(quantize_info->signature == MagickCoreSignature);
2918   assert(images != (Image *) NULL);
2919   assert(images->signature == MagickCoreSignature);
2920   if (images->debug != MagickFalse)
2921     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2922   assert(exception != (ExceptionInfo *) NULL);
2923   assert(exception->signature == MagickCoreSignature);
2924   if (GetNextImageInList(images) == (Image *) NULL)
2925     {
2926       /*
2927         Handle a single image with QuantizeImage.
2928       */
2929       status=QuantizeImage(quantize_info,images,exception);
2930       return(status);
2931     }
2932   status=MagickFalse;
2933   maximum_colors=quantize_info->number_colors;
2934   if (maximum_colors == 0)
2935     maximum_colors=MaxColormapSize;
2936   if (maximum_colors > MaxColormapSize)
2937     maximum_colors=MaxColormapSize;
2938   depth=quantize_info->tree_depth;
2939   if (depth == 0)
2940     {
2941       size_t
2942         colors;
2943
2944       /*
2945         Depth of color tree is: Log4(colormap size)+2.
2946       */
2947       colors=maximum_colors;
2948       for (depth=1; colors != 0; depth++)
2949         colors>>=2;
2950       if (quantize_info->dither_method != NoDitherMethod)
2951         depth--;
2952     }
2953   /*
2954     Initialize color cube.
2955   */
2956   cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2957   if (cube_info == (CubeInfo *) NULL)
2958     {
2959       (void) ThrowMagickException(exception,GetMagickModule(),
2960         ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2961       return(MagickFalse);
2962     }
2963   number_images=GetImageListLength(images);
2964   image=images;
2965   for (i=0; image != (Image *) NULL; i++)
2966   {
2967     progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2968       image->client_data);
2969     status=ClassifyImageColors(cube_info,image,exception);
2970     if (status == MagickFalse)
2971       break;
2972     (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2973     proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2974       number_images);
2975     if (proceed == MagickFalse)
2976       break;
2977     image=GetNextImageInList(image);
2978   }
2979   if (status != MagickFalse)
2980     {
2981       /*
2982         Reduce the number of colors in an image sequence.
2983       */
2984       ReduceImageColors(images,cube_info);
2985       image=images;
2986       for (i=0; image != (Image *) NULL; i++)
2987       {
2988         progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2989           NULL,image->client_data);
2990         status=AssignImageColors(image,cube_info,exception);
2991         if (status == MagickFalse)
2992           break;
2993         (void) SetImageProgressMonitor(image,progress_monitor,
2994           image->client_data);
2995         proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2996           number_images);
2997         if (proceed == MagickFalse)
2998           break;
2999         image=GetNextImageInList(image);
3000       }
3001     }
3002   DestroyCubeInfo(cube_info);
3003   return(status);
3004 }
3005 \f
3006 /*
3007 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3008 %                                                                             %
3009 %                                                                             %
3010 %                                                                             %
3011 +   Q u a n t i z e E r r o r F l a t t e n                                   %
3012 %                                                                             %
3013 %                                                                             %
3014 %                                                                             %
3015 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3016 %
3017 %  QuantizeErrorFlatten() traverses the color cube and flattens the quantization
3018 %  error into a sorted 1D array.  This accelerates the color reduction process.
3019 %
3020 %  Contributed by Yoya.
3021 %
3022 %  The format of the QuantizeErrorFlatten method is:
3023 %
3024 %      size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
3025 %        const NodeInfo *node_info,const ssize_t offset,
3026 %        double *quantize_error)
3027 %
3028 %  A description of each parameter follows.
3029 %
3030 %    o image: the image.
3031 %
3032 %    o cube_info: A pointer to the Cube structure.
3033 %
3034 %    o node_info: pointer to node in color cube tree that is current pointer.
3035 %
3036 %    o offset: quantize error offset.
3037 %
3038 %    o quantize_error: the quantization error vector.
3039 %
3040 */
3041 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
3042   const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
3043 {
3044   register ssize_t
3045     i;
3046
3047   size_t
3048     n,
3049     number_children;
3050
3051   if (offset >= (ssize_t) cube_info->nodes)
3052     return(0);
3053   quantize_error[offset]=node_info->quantize_error;
3054   n=1;
3055   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3056   for (i=0; i < (ssize_t) number_children ; i++)
3057     if (node_info->child[i] != (NodeInfo *) NULL)
3058       n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
3059         quantize_error);
3060   return(n);
3061 }
3062 \f
3063 /*
3064 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3065 %                                                                             %
3066 %                                                                             %
3067 %                                                                             %
3068 +   R e d u c e                                                               %
3069 %                                                                             %
3070 %                                                                             %
3071 %                                                                             %
3072 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3073 %
3074 %  Reduce() traverses the color cube tree and prunes any node whose
3075 %  quantization error falls below a particular threshold.
3076 %
3077 %  The format of the Reduce method is:
3078 %
3079 %      Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
3080 %
3081 %  A description of each parameter follows.
3082 %
3083 %    o image: the image.
3084 %
3085 %    o cube_info: A pointer to the Cube structure.
3086 %
3087 %    o node_info: pointer to node in color cube tree that is to be pruned.
3088 %
3089 */
3090 static void Reduce(const Image *image,CubeInfo *cube_info,
3091   const NodeInfo *node_info)
3092 {
3093   register ssize_t
3094     i;
3095
3096   size_t
3097     number_children;
3098
3099   /*
3100     Traverse any children.
3101   */
3102   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
3103   for (i=0; i < (ssize_t) number_children; i++)
3104     if (node_info->child[i] != (NodeInfo *) NULL)
3105       Reduce(image,cube_info,node_info->child[i]);
3106   if (node_info->quantize_error <= cube_info->pruning_threshold)
3107     PruneChild(image,cube_info,node_info);
3108   else
3109     {
3110       /*
3111         Find minimum pruning threshold.
3112       */
3113       if (node_info->number_unique > 0)
3114         cube_info->colors++;
3115       if (node_info->quantize_error < cube_info->next_threshold)
3116         cube_info->next_threshold=node_info->quantize_error;
3117     }
3118 }
3119 \f
3120 /*
3121 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3122 %                                                                             %
3123 %                                                                             %
3124 %                                                                             %
3125 +   R e d u c e I m a g e C o l o r s                                         %
3126 %                                                                             %
3127 %                                                                             %
3128 %                                                                             %
3129 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3130 %
3131 %  ReduceImageColors() repeatedly prunes the tree until the number of nodes
3132 %  with n2 > 0 is less than or equal to the maximum number of colors allowed
3133 %  in the output image.  On any given iteration over the tree, it selects
3134 %  those nodes whose E value is minimal for pruning and merges their
3135 %  color statistics upward. It uses a pruning threshold, Ep, to govern
3136 %  node selection as follows:
3137 %
3138 %    Ep = 0
3139 %    while number of nodes with (n2 > 0) > required maximum number of colors
3140 %      prune all nodes such that E <= Ep
3141 %      Set Ep to minimum E in remaining nodes
3142 %
3143 %  This has the effect of minimizing any quantization error when merging
3144 %  two nodes together.
3145 %
3146 %  When a node to be pruned has offspring, the pruning procedure invokes
3147 %  itself recursively in order to prune the tree from the leaves upward.
3148 %  n2,  Sr, Sg,  and  Sb in a node being pruned are always added to the
3149 %  corresponding data in that node's parent.  This retains the pruned
3150 %  node's color characteristics for later averaging.
3151 %
3152 %  For each node, n2 pixels exist for which that node represents the
3153 %  smallest volume in RGB space containing those pixel's colors.  When n2
3154 %  > 0 the node will uniquely define a color in the output image. At the
3155 %  beginning of reduction,  n2 = 0  for all nodes except a the leaves of
3156 %  the tree which represent colors present in the input image.
3157 %
3158 %  The other pixel count, n1, indicates the total number of colors
3159 %  within the cubic volume which the node represents.  This includes n1 -
3160 %  n2  pixels whose colors should be defined by nodes at a lower level in
3161 %  the tree.
3162 %
3163 %  The format of the ReduceImageColors method is:
3164 %
3165 %      ReduceImageColors(const Image *image,CubeInfo *cube_info)
3166 %
3167 %  A description of each parameter follows.
3168 %
3169 %    o image: the image.
3170 %
3171 %    o cube_info: A pointer to the Cube structure.
3172 %
3173 */
3174
3175 static int QuantizeErrorCompare(const void *error_p,const void *error_q)
3176 {
3177   double
3178     *p,
3179     *q;
3180
3181   p=(double *) error_p;
3182   q=(double *) error_q;
3183   if (*p > *q)
3184     return(1);
3185   if (fabs(*q-*p) <= MagickEpsilon)
3186     return(0);
3187   return(-1);
3188 }
3189
3190 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
3191 {
3192 #define ReduceImageTag  "Reduce/Image"
3193
3194   MagickBooleanType
3195     proceed;
3196
3197   MagickOffsetType
3198     offset;
3199
3200   size_t
3201     span;
3202
3203   cube_info->next_threshold=0.0;
3204   if (cube_info->colors > cube_info->maximum_colors)
3205     {
3206       double
3207         *quantize_error;
3208
3209       /*
3210         Enable rapid reduction of the number of unique colors.
3211       */
3212       quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
3213         sizeof(*quantize_error));
3214       if (quantize_error != (double *) NULL)
3215         {
3216           (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
3217             quantize_error);
3218           qsort(quantize_error,cube_info->nodes,sizeof(double),
3219             QuantizeErrorCompare);
3220           if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
3221             cube_info->next_threshold=quantize_error[cube_info->nodes-110*
3222               (cube_info->maximum_colors+1)/100];
3223           quantize_error=(double *) RelinquishMagickMemory(quantize_error);
3224         }
3225   }
3226   for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
3227   {
3228     cube_info->pruning_threshold=cube_info->next_threshold;
3229     cube_info->next_threshold=cube_info->root->quantize_error-1;
3230     cube_info->colors=0;
3231     Reduce(image,cube_info,cube_info->root);
3232     offset=(MagickOffsetType) span-cube_info->colors;
3233     proceed=SetImageProgress(image,ReduceImageTag,offset,span-
3234       cube_info->maximum_colors+1);
3235     if (proceed == MagickFalse)
3236       break;
3237   }
3238 }
3239 \f
3240 /*
3241 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3242 %                                                                             %
3243 %                                                                             %
3244 %                                                                             %
3245 %   R e m a p I m a g e                                                       %
3246 %                                                                             %
3247 %                                                                             %
3248 %                                                                             %
3249 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3250 %
3251 %  RemapImage() replaces the colors of an image with the closest of the colors
3252 %  from the reference image.
3253 %
3254 %  The format of the RemapImage method is:
3255 %
3256 %      MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3257 %        Image *image,const Image *remap_image,ExceptionInfo *exception)
3258 %
3259 %  A description of each parameter follows:
3260 %
3261 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3262 %
3263 %    o image: the image.
3264 %
3265 %    o remap_image: the reference image.
3266 %
3267 %    o exception: return any errors or warnings in this structure.
3268 %
3269 */
3270 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
3271   Image *image,const Image *remap_image,ExceptionInfo *exception)
3272 {
3273   CubeInfo
3274     *cube_info;
3275
3276   MagickBooleanType
3277     status;
3278
3279   /*
3280     Initialize color cube.
3281   */
3282   assert(image != (Image *) NULL);
3283   assert(image->signature == MagickCoreSignature);
3284   if (image->debug != MagickFalse)
3285     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3286   assert(remap_image != (Image *) NULL);
3287   assert(remap_image->signature == MagickCoreSignature);
3288   assert(exception != (ExceptionInfo *) NULL);
3289   assert(exception->signature == MagickCoreSignature);
3290   cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3291     quantize_info->number_colors);
3292   if (cube_info == (CubeInfo *) NULL)
3293     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3294       image->filename);
3295   status=ClassifyImageColors(cube_info,remap_image,exception);
3296   if (status != MagickFalse)
3297     {
3298       /*
3299         Classify image colors from the reference image.
3300       */
3301       cube_info->quantize_info->number_colors=cube_info->colors;
3302       status=AssignImageColors(image,cube_info,exception);
3303     }
3304   DestroyCubeInfo(cube_info);
3305   return(status);
3306 }
3307 \f
3308 /*
3309 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3310 %                                                                             %
3311 %                                                                             %
3312 %                                                                             %
3313 %   R e m a p I m a g e s                                                     %
3314 %                                                                             %
3315 %                                                                             %
3316 %                                                                             %
3317 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3318 %
3319 %  RemapImages() replaces the colors of a sequence of images with the
3320 %  closest color from a reference image.
3321 %
3322 %  The format of the RemapImage method is:
3323 %
3324 %      MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3325 %        Image *images,Image *remap_image,ExceptionInfo *exception)
3326 %
3327 %  A description of each parameter follows:
3328 %
3329 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3330 %
3331 %    o images: the image sequence.
3332 %
3333 %    o remap_image: the reference image.
3334 %
3335 %    o exception: return any errors or warnings in this structure.
3336 %
3337 */
3338 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3339   Image *images,const Image *remap_image,ExceptionInfo *exception)
3340 {
3341   CubeInfo
3342     *cube_info;
3343
3344   Image
3345     *image;
3346
3347   MagickBooleanType
3348     status;
3349
3350   assert(images != (Image *) NULL);
3351   assert(images->signature == MagickCoreSignature);
3352   if (images->debug != MagickFalse)
3353     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3354   assert(exception != (ExceptionInfo *) NULL);
3355   assert(exception->signature == MagickCoreSignature);
3356   image=images;
3357   if (remap_image == (Image *) NULL)
3358     {
3359       /*
3360         Create a global colormap for an image sequence.
3361       */
3362       status=QuantizeImages(quantize_info,images,exception);
3363       return(status);
3364     }
3365   /*
3366     Classify image colors from the reference image.
3367   */
3368   cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3369     quantize_info->number_colors);
3370   if (cube_info == (CubeInfo *) NULL)
3371     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3372       image->filename);
3373   status=ClassifyImageColors(cube_info,remap_image,exception);
3374   if (status != MagickFalse)
3375     {
3376       /*
3377         Classify image colors from the reference image.
3378       */
3379       cube_info->quantize_info->number_colors=cube_info->colors;
3380       image=images;
3381       for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3382       {
3383         status=AssignImageColors(image,cube_info,exception);
3384         if (status == MagickFalse)
3385           break;
3386       }
3387     }
3388   DestroyCubeInfo(cube_info);
3389   return(status);
3390 }
3391 \f
3392 /*
3393 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3394 %                                                                             %
3395 %                                                                             %
3396 %                                                                             %
3397 %   S e t G r a y s c a l e I m a g e                                         %
3398 %                                                                             %
3399 %                                                                             %
3400 %                                                                             %
3401 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3402 %
3403 %  SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3404 %
3405 %  The format of the SetGrayscaleImage method is:
3406 %
3407 %      MagickBooleanType SetGrayscaleImage(Image *image,
3408 %        ExceptionInfo *exception)
3409 %
3410 %  A description of each parameter follows:
3411 %
3412 %    o image: The image.
3413 %
3414 %    o exception: return any errors or warnings in this structure.
3415 %
3416 */
3417
3418 #if defined(__cplusplus) || defined(c_plusplus)
3419 extern "C" {
3420 #endif
3421
3422 static int IntensityCompare(const void *x,const void *y)
3423 {
3424   double
3425     intensity;
3426
3427   PixelInfo
3428     *color_1,
3429     *color_2;
3430
3431   color_1=(PixelInfo *) x;
3432   color_2=(PixelInfo *) y;
3433   intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
3434     GetPixelInfoIntensity((const Image *) NULL,color_2);
3435   return((int) intensity);
3436 }
3437
3438 #if defined(__cplusplus) || defined(c_plusplus)
3439 }
3440 #endif
3441
3442 static MagickBooleanType SetGrayscaleImage(Image *image,
3443   ExceptionInfo *exception)
3444 {
3445   CacheView
3446     *image_view;
3447
3448   MagickBooleanType
3449     status;
3450
3451   PixelInfo
3452     *colormap;
3453
3454   register ssize_t
3455     i;
3456
3457   ssize_t
3458     *colormap_index,
3459     j,
3460     y;
3461
3462   assert(image != (Image *) NULL);
3463   assert(image->signature == MagickCoreSignature);
3464   if (image->type != GrayscaleType)
3465     (void) TransformImageColorspace(image,GRAYColorspace,exception);
3466   colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
3467     sizeof(*colormap_index));
3468   if (colormap_index == (ssize_t *) NULL)
3469     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3470       image->filename);
3471   if (image->storage_class != PseudoClass)
3472     {
3473       (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
3474         sizeof(*colormap_index));
3475       if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
3476         ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3477           image->filename);
3478       image->colors=0;
3479       status=MagickTrue;
3480       image_view=AcquireAuthenticCacheView(image,exception);
3481 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3482       #pragma omp parallel for schedule(static,4) shared(status) \
3483         magick_threads(image,image,image->rows,1)
3484 #endif
3485       for (y=0; y < (ssize_t) image->rows; y++)
3486       {
3487         register Quantum
3488           *restrict q;
3489
3490         register ssize_t
3491           x;
3492
3493         if (status == MagickFalse)
3494           continue;
3495         q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3496           exception);
3497         if (q == (Quantum *) NULL)
3498           {
3499             status=MagickFalse;
3500             continue;
3501           }
3502         for (x=0; x < (ssize_t) image->columns; x++)
3503         {
3504           register size_t
3505             intensity;
3506
3507           intensity=ScaleQuantumToMap(GetPixelRed(image,q));
3508           if (colormap_index[intensity] < 0)
3509             {
3510 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3511               #pragma omp critical (MagickCore_SetGrayscaleImage)
3512 #endif
3513               if (colormap_index[intensity] < 0)
3514                 {
3515                   colormap_index[intensity]=(ssize_t) image->colors;
3516                   image->colormap[image->colors].red=(double)
3517                     GetPixelRed(image,q);
3518                   image->colormap[image->colors].green=(double)
3519                     GetPixelGreen(image,q);
3520                   image->colormap[image->colors].blue=(double)
3521                     GetPixelBlue(image,q);
3522                   image->colors++;
3523                }
3524             }
3525           SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
3526           q+=GetPixelChannels(image);
3527         }
3528         if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3529           status=MagickFalse;
3530       }
3531       image_view=DestroyCacheView(image_view);
3532     }
3533   for (i=0; i < (ssize_t) image->colors; i++)
3534     image->colormap[i].alpha=(double) i;
3535   qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
3536     IntensityCompare);
3537   colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
3538   if (colormap == (PixelInfo *) NULL)
3539     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3540       image->filename);
3541   j=0;
3542   colormap[j]=image->colormap[0];
3543   for (i=0; i < (ssize_t) image->colors; i++)
3544   {
3545     if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
3546       {
3547         j++;
3548         colormap[j]=image->colormap[i];
3549       }
3550     colormap_index[(ssize_t) image->colormap[i].alpha]=j;
3551   }
3552   image->colors=(size_t) (j+1);
3553   image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
3554   image->colormap=colormap;
3555   status=MagickTrue;
3556   image_view=AcquireAuthenticCacheView(image,exception);
3557 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3558   #pragma omp parallel for schedule(static,4) shared(status) \
3559     magick_threads(image,image,image->rows,1)
3560 #endif
3561   for (y=0; y < (ssize_t) image->rows; y++)
3562   {
3563     register Quantum
3564       *restrict q;
3565
3566     register ssize_t
3567       x;
3568
3569     if (status == MagickFalse)
3570       continue;
3571     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3572     if (q == (Quantum *) NULL)
3573       {
3574         status=MagickFalse;
3575         continue;
3576       }
3577     for (x=0; x < (ssize_t) image->columns; x++)
3578     {
3579       SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3580         GetPixelIndex(image,q))],q);
3581       q+=GetPixelChannels(image);
3582     }
3583     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3584       status=MagickFalse;
3585   }
3586   image_view=DestroyCacheView(image_view);
3587   colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3588   image->type=GrayscaleType;
3589   if (SetImageMonochrome(image,exception) != MagickFalse)
3590     image->type=BilevelType;
3591   return(status);
3592 }