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