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