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