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