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