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