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