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