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