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