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