]> granicus.if.org Git - imagemagick/blob - magick/quantize.c
(no commit message)
[imagemagick] / magick / quantize.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %           QQQ   U   U   AAA   N   N  TTTTT  IIIII   ZZZZZ  EEEEE            %
7 %          Q   Q  U   U  A   A  NN  N    T      I        ZZ  E                %
8 %          Q   Q  U   U  AAAAA  N N N    T      I      ZZZ   EEEEE            %
9 %          Q  QQ  U   U  A   A  N  NN    T      I     ZZ     E                %
10 %           QQQQ   UUU   A   A  N   N    T    IIIII   ZZZZZ  EEEEE            %
11 %                                                                             %
12 %                                                                             %
13 %    MagickCore Methods to Reduce the Number of Unique Colors in an Image     %
14 %                                                                             %
15 %                           Software Design                                   %
16 %                             John Cristy                                     %
17 %                              July 1992                                      %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %  Realism in computer graphics typically requires using 24 bits/pixel to
37 %  generate an image.  Yet many graphic display devices do not contain the
38 %  amount of memory necessary to match the spatial and color resolution of
39 %  the human eye.  The Quantize methods takes a 24 bit image and reduces
40 %  the number of colors so it can be displayed on raster device with less
41 %  bits per pixel.  In most instances, the quantized image closely
42 %  resembles the original reference image.
43 %
44 %  A reduction of colors in an image is also desirable for image
45 %  transmission and real-time animation.
46 %
47 %  QuantizeImage() takes a standard RGB or monochrome images and quantizes
48 %  them down to some fixed number of colors.
49 %
50 %  For purposes of color allocation, an image is a set of n pixels, where
51 %  each pixel is a point in RGB space.  RGB space is a 3-dimensional
52 %  vector space, and each pixel, Pi,  is defined by an ordered triple of
53 %  red, green, and blue coordinates, (Ri, Gi, Bi).
54 %
55 %  Each primary color component (red, green, or blue) represents an
56 %  intensity which varies linearly from 0 to a maximum value, Cmax, which
57 %  corresponds to full saturation of that color.  Color allocation is
58 %  defined over a domain consisting of the cube in RGB space with opposite
59 %  vertices at (0,0,0) and (Cmax, Cmax, Cmax).  QUANTIZE requires Cmax =
60 %  255.
61 %
62 %  The algorithm maps this domain onto a tree in which each node
63 %  represents a cube within that domain.  In the following discussion
64 %  these cubes are defined by the coordinate of two opposite vertices:
65 %  The vertex nearest the origin in RGB space and the vertex farthest from
66 %  the origin.
67 %
68 %  The tree's root node represents the entire domain, (0,0,0) through
69 %  (Cmax,Cmax,Cmax).  Each lower level in the tree is generated by
70 %  subdividing one node's cube into eight smaller cubes of equal size.
71 %  This corresponds to bisecting the parent cube with planes passing
72 %  through the midpoints of each edge.
73 %
74 %  The basic algorithm operates in three phases: Classification,
75 %  Reduction, and Assignment.  Classification builds a color description
76 %  tree for the image.  Reduction collapses the tree until the number it
77 %  represents, at most, the number of colors desired in the output image.
78 %  Assignment defines the output image's color map and sets each pixel's
79 %  color by restorage_class in the reduced tree.  Our goal is to minimize
80 %  the numerical discrepancies between the original colors and quantized
81 %  colors (quantization error).
82 %
83 %  Classification begins by initializing a color description tree of
84 %  sufficient depth to represent each possible input color in a leaf.
85 %  However, it is impractical to generate a fully-formed color description
86 %  tree in the storage_class phase for realistic values of Cmax.  If
87 %  colors components in the input image are quantized to k-bit precision,
88 %  so that Cmax= 2k-1, the tree would need k levels below the root node to
89 %  allow representing each possible input color in a leaf.  This becomes
90 %  prohibitive because the tree's total number of nodes is 1 +
91 %  sum(i=1, k, 8k).
92 %
93 %  A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94 %  Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95 %  Initializes data structures for nodes only as they are needed;  (2)
96 %  Chooses a maximum depth for the tree as a function of the desired
97 %  number of colors in the output image (currently log2(colormap size)).
98 %
99 %  For each pixel in the input image, storage_class scans downward from
100 %  the root of the color description tree.  At each level of the tree it
101 %  identifies the single node which represents a cube in RGB space
102 %  containing the pixel's color.  It updates the following data for each
103 %  such node:
104 %
105 %    n1: Number of pixels whose color is contained in the RGB cube which
106 %    this node represents;
107 %
108 %    n2: Number of pixels whose color is not represented in a node at
109 %    lower depth in the tree;  initially,  n2 = 0 for all nodes except
110 %    leaves of the tree.
111 %
112 %    Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113 %    pixels not classified at a lower depth. The combination of these sums
114 %    and n2  will ultimately characterize the mean color of a set of
115 %    pixels represented by this node.
116 %
117 %    E: the distance squared in RGB space between each pixel contained
118 %    within a node and the nodes' center.  This represents the
119 %    quantization error for a node.
120 %
121 %  Reduction repeatedly prunes the tree until the number of nodes with n2
122 %  > 0 is less than or equal to the maximum number of colors allowed in
123 %  the output image.  On any given iteration over the tree, it selects
124 %  those nodes whose E count is minimal for pruning and merges their color
125 %  statistics upward. It uses a pruning threshold, Ep, to govern node
126 %  selection as follows:
127 %
128 %    Ep = 0
129 %    while number of nodes with (n2 > 0) > required maximum number of colors
130 %      prune all nodes such that E <= Ep
131 %      Set Ep to minimum E in remaining nodes
132 %
133 %  This has the effect of minimizing any quantization error when merging
134 %  two nodes together.
135 %
136 %  When a node to be pruned has offspring, the pruning procedure invokes
137 %  itself recursively in order to prune the tree from the leaves upward.
138 %  n2,  Sr, Sg,  and  Sb in a node being pruned are always added to the
139 %  corresponding data in that node's parent.  This retains the pruned
140 %  node's color characteristics for later averaging.
141 %
142 %  For each node, n2 pixels exist for which that node represents the
143 %  smallest volume in RGB space containing those pixel's colors.  When n2
144 %  > 0 the node will uniquely define a color in the output image. At the
145 %  beginning of reduction,  n2 = 0  for all nodes except a the leaves of
146 %  the tree which represent colors present in the input image.
147 %
148 %  The other pixel count, n1, indicates the total number of colors within
149 %  the cubic volume which the node represents.  This includes n1 - n2
150 %  pixels whose colors should be defined by nodes at a lower level in the
151 %  tree.
152 %
153 %  Assignment generates the output image from the pruned tree.  The output
154 %  image consists of two parts: (1)  A color map, which is an array of
155 %  color descriptions (RGB triples) for each color present in the output
156 %  image;  (2)  A pixel array, which represents each pixel as an index
157 %  into the color map array.
158 %
159 %  First, the assignment phase makes one pass over the pruned color
160 %  description tree to establish the image's color map.  For each node
161 %  with n2  > 0, it divides Sr, Sg, and Sb by n2 .  This produces the mean
162 %  color of all pixels that classify no lower than this node.  Each of
163 %  these colors becomes an entry in the color map.
164 %
165 %  Finally,  the assignment phase reclassifies each pixel in the pruned
166 %  tree to identify the deepest node containing the pixel's color.  The
167 %  pixel's value in the pixel array becomes the index of this node's mean
168 %  color in the color map.
169 %
170 %  This method is based on a similar algorithm written by Paul Raveling.
171 %
172 */
173 \f
174 /*
175   Include declarations.
176 */
177 #include "magick/studio.h"
178 #include "magick/cache-view.h"
179 #include "magick/color.h"
180 #include "magick/color-private.h"
181 #include "magick/colormap.h"
182 #include "magick/colorspace.h"
183 #include "magick/enhance.h"
184 #include "magick/exception.h"
185 #include "magick/exception-private.h"
186 #include "magick/histogram.h"
187 #include "magick/image.h"
188 #include "magick/image-private.h"
189 #include "magick/list.h"
190 #include "magick/memory_.h"
191 #include "magick/monitor.h"
192 #include "magick/monitor-private.h"
193 #include "magick/option.h"
194 #include "magick/pixel-private.h"
195 #include "magick/quantize.h"
196 #include "magick/quantum.h"
197 #include "magick/string_.h"
198 #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) ParseCommandOption(
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 ((GetRedPixelComponent(p) != q->red) || (GetGreenPixelComponent(p) != q->green) || (GetBluePixelComponent(p) != q->blue))
480     return(MagickFalse);
481   if ((image->matte != MagickFalse) && (GetOpacityPixelComponent(p) != 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*GetRedPixelComponent(p)-beta*q->red;
1095       distance=pixel*pixel;
1096       if (distance <= cube_info->distance)
1097         {
1098           pixel=alpha*GetGreenPixelComponent(p)-beta*q->green;
1099           distance+=pixel*pixel;
1100           if (distance <= cube_info->distance)
1101             {
1102               pixel=alpha*GetBluePixelComponent(p)-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   for (y=0; y < (ssize_t) image->rows; y++)
1469   {
1470     const int
1471       id = GetOpenMPThreadId();
1472
1473     CubeInfo
1474       cube;
1475
1476     RealPixelPacket
1477       *current,
1478       *previous;
1479
1480     register IndexPacket
1481       *restrict indexes;
1482
1483     register PixelPacket
1484       *restrict q;
1485
1486     register ssize_t
1487       x;
1488
1489     size_t
1490       index;
1491
1492     ssize_t
1493       v;
1494
1495     if (status == MagickFalse)
1496       continue;
1497     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1498     if (q == (PixelPacket *) NULL)
1499       {
1500         status=MagickFalse;
1501         continue;
1502       }
1503     indexes=GetCacheViewAuthenticIndexQueue(image_view);
1504     cube=(*cube_info);
1505     current=pixels[id]+(y & 0x01)*image->columns;
1506     previous=pixels[id]+((y+1) & 0x01)*image->columns;
1507     v=(ssize_t) ((y & 0x01) ? -1 : 1);
1508     for (x=0; x < (ssize_t) image->columns; x++)
1509     {
1510       RealPixelPacket
1511         color,
1512         pixel;
1513
1514       register ssize_t
1515         i;
1516
1517       ssize_t
1518         u;
1519
1520       u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
1521       AssociateAlphaPixel(&cube,q+u,&pixel);
1522       if (x > 0)
1523         {
1524           pixel.red+=7*current[u-v].red/16;
1525           pixel.green+=7*current[u-v].green/16;
1526           pixel.blue+=7*current[u-v].blue/16;
1527           if (cube.associate_alpha != MagickFalse)
1528             pixel.opacity+=7*current[u-v].opacity/16;
1529         }
1530       if (y > 0)
1531         {
1532           if (x < (ssize_t) (image->columns-1))
1533             {
1534               pixel.red+=previous[u+v].red/16;
1535               pixel.green+=previous[u+v].green/16;
1536               pixel.blue+=previous[u+v].blue/16;
1537               if (cube.associate_alpha != MagickFalse)
1538                 pixel.opacity+=previous[u+v].opacity/16;
1539             }
1540           pixel.red+=5*previous[u].red/16;
1541           pixel.green+=5*previous[u].green/16;
1542           pixel.blue+=5*previous[u].blue/16;
1543           if (cube.associate_alpha != MagickFalse)
1544             pixel.opacity+=5*previous[u].opacity/16;
1545           if (x > 0)
1546             {
1547               pixel.red+=3*previous[u-v].red/16;
1548               pixel.green+=3*previous[u-v].green/16;
1549               pixel.blue+=3*previous[u-v].blue/16;
1550               if (cube.associate_alpha != MagickFalse)
1551                 pixel.opacity+=3*previous[u-v].opacity/16;
1552             }
1553         }
1554       pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1555       pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1556       pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1557       if (cube.associate_alpha != MagickFalse)
1558         pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1559       i=CacheOffset(&cube,&pixel);
1560       if (cube.cache[i] < 0)
1561         {
1562           register NodeInfo
1563             *node_info;
1564
1565           register size_t
1566             id;
1567
1568           /*
1569             Identify the deepest node containing the pixel's color.
1570           */
1571           node_info=cube.root;
1572           for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1573           {
1574             id=ColorToNodeId(&cube,&pixel,index);
1575             if (node_info->child[id] == (NodeInfo *) NULL)
1576               break;
1577             node_info=node_info->child[id];
1578           }
1579           /*
1580             Find closest color among siblings and their children.
1581           */
1582           cube.target=pixel;
1583           cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1584             1.0)+1.0);
1585           ClosestColor(image,&cube,node_info->parent);
1586           cube.cache[i]=(ssize_t) cube.color_number;
1587         }
1588       /*
1589         Assign pixel to closest colormap entry.
1590       */
1591       index=(size_t) cube.cache[i];
1592       if (image->storage_class == PseudoClass)
1593         indexes[u]=(IndexPacket) index;
1594       if (cube.quantize_info->measure_error == MagickFalse)
1595         {
1596           (q+u)->red=image->colormap[index].red;
1597           (q+u)->green=image->colormap[index].green;
1598           (q+u)->blue=image->colormap[index].blue;
1599           if (cube.associate_alpha != MagickFalse)
1600             (q+u)->opacity=image->colormap[index].opacity;
1601         }
1602       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1603         status=MagickFalse;
1604       /*
1605         Store the error.
1606       */
1607       AssociateAlphaPixel(&cube,image->colormap+index,&color);
1608       current[u].red=pixel.red-color.red;
1609       current[u].green=pixel.green-color.green;
1610       current[u].blue=pixel.blue-color.blue;
1611       if (cube.associate_alpha != MagickFalse)
1612         current[u].opacity=pixel.opacity-color.opacity;
1613       if (image->progress_monitor != (MagickProgressMonitor) NULL)
1614         {
1615           MagickBooleanType
1616             proceed;
1617
1618 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1619           #pragma omp critical (MagickCore_FloydSteinbergDither)
1620 #endif
1621           proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1622             image->rows);
1623           if (proceed == MagickFalse)
1624             status=MagickFalse;
1625         }
1626     }
1627   }
1628   image_view=DestroyCacheView(image_view);
1629   pixels=DestroyPixelThreadSet(pixels);
1630   return(MagickTrue);
1631 }
1632
1633 static MagickBooleanType
1634   RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1635
1636 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
1637   const size_t level,const unsigned int direction)
1638 {
1639   if (level == 1)
1640     switch (direction)
1641     {
1642       case WestGravity:
1643       {
1644         (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1645         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1646         (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1647         break;
1648       }
1649       case EastGravity:
1650       {
1651         (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1652         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1653         (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1654         break;
1655       }
1656       case NorthGravity:
1657       {
1658         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1659         (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1660         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1661         break;
1662       }
1663       case SouthGravity:
1664       {
1665         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1666         (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1667         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1668         break;
1669       }
1670       default:
1671         break;
1672     }
1673   else
1674     switch (direction)
1675     {
1676       case WestGravity:
1677       {
1678         Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1679         (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1680         Riemersma(image,image_view,cube_info,level-1,WestGravity);
1681         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1682         Riemersma(image,image_view,cube_info,level-1,WestGravity);
1683         (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1684         Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1685         break;
1686       }
1687       case EastGravity:
1688       {
1689         Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1690         (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1691         Riemersma(image,image_view,cube_info,level-1,EastGravity);
1692         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1693         Riemersma(image,image_view,cube_info,level-1,EastGravity);
1694         (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1695         Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1696         break;
1697       }
1698       case NorthGravity:
1699       {
1700         Riemersma(image,image_view,cube_info,level-1,WestGravity);
1701         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1702         Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1703         (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1704         Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1705         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1706         Riemersma(image,image_view,cube_info,level-1,EastGravity);
1707         break;
1708       }
1709       case SouthGravity:
1710       {
1711         Riemersma(image,image_view,cube_info,level-1,EastGravity);
1712         (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1713         Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1714         (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1715         Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1716         (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1717         Riemersma(image,image_view,cube_info,level-1,WestGravity);
1718         break;
1719       }
1720       default:
1721         break;
1722     }
1723 }
1724
1725 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1726   CubeInfo *cube_info,const unsigned int direction)
1727 {
1728 #define DitherImageTag  "Dither/Image"
1729
1730   MagickBooleanType
1731     proceed;
1732
1733   RealPixelPacket
1734     color,
1735     pixel;
1736
1737   register CubeInfo
1738     *p;
1739
1740   size_t
1741     index;
1742
1743   p=cube_info;
1744   if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1745       (p->y >= 0) && (p->y < (ssize_t) image->rows))
1746     {
1747       ExceptionInfo
1748         *exception;
1749
1750       register IndexPacket
1751         *restrict indexes;
1752
1753       register PixelPacket
1754         *restrict q;
1755
1756       register ssize_t
1757         i;
1758
1759       /*
1760         Distribute error.
1761       */
1762       exception=(&image->exception);
1763       q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1764       if (q == (PixelPacket *) NULL)
1765         return(MagickFalse);
1766       indexes=GetCacheViewAuthenticIndexQueue(image_view);
1767       AssociateAlphaPixel(cube_info,q,&pixel);
1768       for (i=0; i < ErrorQueueLength; i++)
1769       {
1770         pixel.red+=p->weights[i]*p->error[i].red;
1771         pixel.green+=p->weights[i]*p->error[i].green;
1772         pixel.blue+=p->weights[i]*p->error[i].blue;
1773         if (cube_info->associate_alpha != MagickFalse)
1774           pixel.opacity+=p->weights[i]*p->error[i].opacity;
1775       }
1776       pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1777       pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1778       pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
1779       if (cube_info->associate_alpha != MagickFalse)
1780         pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
1781       i=CacheOffset(cube_info,&pixel);
1782       if (p->cache[i] < 0)
1783         {
1784           register NodeInfo
1785             *node_info;
1786
1787           register size_t
1788             id;
1789
1790           /*
1791             Identify the deepest node containing the pixel's color.
1792           */
1793           node_info=p->root;
1794           for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
1795           {
1796             id=ColorToNodeId(cube_info,&pixel,index);
1797             if (node_info->child[id] == (NodeInfo *) NULL)
1798               break;
1799             node_info=node_info->child[id];
1800           }
1801           node_info=node_info->parent;
1802           /*
1803             Find closest color among siblings and their children.
1804           */
1805           p->target=pixel;
1806           p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1807             QuantumRange+1.0)+1.0);
1808           ClosestColor(image,p,node_info->parent);
1809           p->cache[i]=(ssize_t) p->color_number;
1810         }
1811       /*
1812         Assign pixel to closest colormap entry.
1813       */
1814       index=(size_t) (1*p->cache[i]);
1815       if (image->storage_class == PseudoClass)
1816         *indexes=(IndexPacket) index;
1817       if (cube_info->quantize_info->measure_error == MagickFalse)
1818         {
1819           q->red=image->colormap[index].red;
1820           q->green=image->colormap[index].green;
1821           q->blue=image->colormap[index].blue;
1822           if (cube_info->associate_alpha != MagickFalse)
1823             q->opacity=image->colormap[index].opacity;
1824         }
1825       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1826         return(MagickFalse);
1827       /*
1828         Propagate the error as the last entry of the error queue.
1829       */
1830       (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1831         sizeof(p->error[0]));
1832       AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1833       p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1834       p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1835       p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1836       if (cube_info->associate_alpha != MagickFalse)
1837         p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1838       proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1839       if (proceed == MagickFalse)
1840         return(MagickFalse);
1841       p->offset++;
1842     }
1843   switch (direction)
1844   {
1845     case WestGravity: p->x--; break;
1846     case EastGravity: p->x++; break;
1847     case NorthGravity: p->y--; break;
1848     case SouthGravity: p->y++; break;
1849   }
1850   return(MagickTrue);
1851 }
1852
1853 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
1854 {
1855   if (x > y)
1856     return(x);
1857   return(y);
1858 }
1859
1860 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
1861 {
1862   if (x < y)
1863     return(x);
1864   return(y);
1865 }
1866
1867 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1868 {
1869   CacheView
1870     *image_view;
1871
1872   MagickBooleanType
1873     status;
1874
1875   register ssize_t
1876     i;
1877
1878   size_t
1879     depth;
1880
1881   if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
1882     return(FloydSteinbergDither(image,cube_info));
1883   /*
1884     Distribute quantization error along a Hilbert curve.
1885   */
1886   (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1887     sizeof(*cube_info->error));
1888   cube_info->x=0;
1889   cube_info->y=0;
1890   i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
1891   for (depth=1; i != 0; depth++)
1892     i>>=1;
1893   if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
1894     depth++;
1895   cube_info->offset=0;
1896   cube_info->span=(MagickSizeType) image->columns*image->rows;
1897   image_view=AcquireCacheView(image);
1898   if (depth > 1)
1899     Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1900   status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1901   image_view=DestroyCacheView(image_view);
1902   return(status);
1903 }
1904 \f
1905 /*
1906 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1907 %                                                                             %
1908 %                                                                             %
1909 %                                                                             %
1910 +   G e t C u b e I n f o                                                     %
1911 %                                                                             %
1912 %                                                                             %
1913 %                                                                             %
1914 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1915 %
1916 %  GetCubeInfo() initialize the Cube data structure.
1917 %
1918 %  The format of the GetCubeInfo method is:
1919 %
1920 %      CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
1921 %        const size_t depth,const size_t maximum_colors)
1922 %
1923 %  A description of each parameter follows.
1924 %
1925 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1926 %
1927 %    o depth: Normally, this integer value is zero or one.  A zero or
1928 %      one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1929 %      A tree of this depth generally allows the best representation of the
1930 %      reference image with the least amount of memory and the fastest
1931 %      computational speed.  In some cases, such as an image with low color
1932 %      dispersion (a few number of colors), a value other than
1933 %      Log4(number_colors) is required.  To expand the color tree completely,
1934 %      use a value of 8.
1935 %
1936 %    o maximum_colors: maximum colors.
1937 %
1938 */
1939 static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
1940   const size_t depth,const size_t maximum_colors)
1941 {
1942   CubeInfo
1943     *cube_info;
1944
1945   MagickRealType
1946     sum,
1947     weight;
1948
1949   register ssize_t
1950     i;
1951
1952   size_t
1953     length;
1954
1955   /*
1956     Initialize tree to describe color cube_info.
1957   */
1958   cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
1959   if (cube_info == (CubeInfo *) NULL)
1960     return((CubeInfo *) NULL);
1961   (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1962   cube_info->depth=depth;
1963   if (cube_info->depth > MaxTreeDepth)
1964     cube_info->depth=MaxTreeDepth;
1965   if (cube_info->depth < 2)
1966     cube_info->depth=2;
1967   cube_info->maximum_colors=maximum_colors;
1968   /*
1969     Initialize root node.
1970   */
1971   cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1972   if (cube_info->root == (NodeInfo *) NULL)
1973     return((CubeInfo *) NULL);
1974   cube_info->root->parent=cube_info->root;
1975   cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1976   if (cube_info->quantize_info->dither == MagickFalse)
1977     return(cube_info);
1978   /*
1979     Initialize dither resources.
1980   */
1981   length=(size_t) (1UL << (4*(8-CacheShift)));
1982   cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
1983     sizeof(*cube_info->cache));
1984   if (cube_info->cache == (ssize_t *) NULL)
1985     return((CubeInfo *) NULL);
1986   /*
1987     Initialize color cache.
1988   */
1989   for (i=0; i < (ssize_t) length; i++)
1990     cube_info->cache[i]=(-1);
1991   /*
1992     Distribute weights along a curve of exponential decay.
1993   */
1994   weight=1.0;
1995   for (i=0; i < ErrorQueueLength; i++)
1996   {
1997     cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1998     weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1999   }
2000   /*
2001     Normalize the weighting factors.
2002   */
2003   weight=0.0;
2004   for (i=0; i < ErrorQueueLength; i++)
2005     weight+=cube_info->weights[i];
2006   sum=0.0;
2007   for (i=0; i < ErrorQueueLength; i++)
2008   {
2009     cube_info->weights[i]/=weight;
2010     sum+=cube_info->weights[i];
2011   }
2012   cube_info->weights[0]+=1.0-sum;
2013   return(cube_info);
2014 }
2015 \f
2016 /*
2017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2018 %                                                                             %
2019 %                                                                             %
2020 %                                                                             %
2021 +   G e t N o d e I n f o                                                     %
2022 %                                                                             %
2023 %                                                                             %
2024 %                                                                             %
2025 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2026 %
2027 %  GetNodeInfo() allocates memory for a new node in the color cube tree and
2028 %  presets all fields to zero.
2029 %
2030 %  The format of the GetNodeInfo method is:
2031 %
2032 %      NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2033 %        const size_t level,NodeInfo *parent)
2034 %
2035 %  A description of each parameter follows.
2036 %
2037 %    o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2038 %
2039 %    o id: Specifies the child number of the node.
2040 %
2041 %    o level: Specifies the level in the storage_class the node resides.
2042 %
2043 */
2044 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2045   const size_t level,NodeInfo *parent)
2046 {
2047   NodeInfo
2048     *node_info;
2049
2050   if (cube_info->free_nodes == 0)
2051     {
2052       Nodes
2053         *nodes;
2054
2055       /*
2056         Allocate a new queue of nodes.
2057       */
2058       nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
2059       if (nodes == (Nodes *) NULL)
2060         return((NodeInfo *) NULL);
2061       nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2062         sizeof(*nodes->nodes));
2063       if (nodes->nodes == (NodeInfo *) NULL)
2064         return((NodeInfo *) NULL);
2065       nodes->next=cube_info->node_queue;
2066       cube_info->node_queue=nodes;
2067       cube_info->next_node=nodes->nodes;
2068       cube_info->free_nodes=NodesInAList;
2069     }
2070   cube_info->nodes++;
2071   cube_info->free_nodes--;
2072   node_info=cube_info->next_node++;
2073   (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2074   node_info->parent=parent;
2075   node_info->id=id;
2076   node_info->level=level;
2077   return(node_info);
2078 }
2079 \f
2080 /*
2081 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2082 %                                                                             %
2083 %                                                                             %
2084 %                                                                             %
2085 %  G e t I m a g e Q u a n t i z e E r r o r                                  %
2086 %                                                                             %
2087 %                                                                             %
2088 %                                                                             %
2089 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2090 %
2091 %  GetImageQuantizeError() measures the difference between the original
2092 %  and quantized images.  This difference is the total quantization error.
2093 %  The error is computed by summing over all pixels in an image the distance
2094 %  squared in RGB space between each reference pixel value and its quantized
2095 %  value.  These values are computed:
2096 %
2097 %    o mean_error_per_pixel:  This value is the mean error for any single
2098 %      pixel in the image.
2099 %
2100 %    o normalized_mean_square_error:  This value is the normalized mean
2101 %      quantization error for any single pixel in the image.  This distance
2102 %      measure is normalized to a range between 0 and 1.  It is independent
2103 %      of the range of red, green, and blue values in the image.
2104 %
2105 %    o normalized_maximum_square_error:  Thsi value is the normalized
2106 %      maximum quantization error for any single pixel in the image.  This
2107 %      distance measure is normalized to a range between 0 and 1.  It is
2108 %      independent of the range of red, green, and blue values in your image.
2109 %
2110 %  The format of the GetImageQuantizeError method is:
2111 %
2112 %      MagickBooleanType GetImageQuantizeError(Image *image)
2113 %
2114 %  A description of each parameter follows.
2115 %
2116 %    o image: the image.
2117 %
2118 */
2119 MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2120 {
2121   CacheView
2122     *image_view;
2123
2124   ExceptionInfo
2125     *exception;
2126
2127   IndexPacket
2128     *indexes;
2129
2130   MagickRealType
2131     alpha,
2132     area,
2133     beta,
2134     distance,
2135     maximum_error,
2136     mean_error,
2137     mean_error_per_pixel;
2138
2139   size_t
2140     index;
2141
2142   ssize_t
2143     y;
2144
2145   assert(image != (Image *) NULL);
2146   assert(image->signature == MagickSignature);
2147   if (image->debug != MagickFalse)
2148     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2149   image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2150   (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2151   if (image->storage_class == DirectClass)
2152     return(MagickTrue);
2153   alpha=1.0;
2154   beta=1.0;
2155   area=3.0*image->columns*image->rows;
2156   maximum_error=0.0;
2157   mean_error_per_pixel=0.0;
2158   mean_error=0.0;
2159   exception=(&image->exception);
2160   image_view=AcquireCacheView(image);
2161   for (y=0; y < (ssize_t) image->rows; y++)
2162   {
2163     register const PixelPacket
2164       *restrict p;
2165
2166     register ssize_t
2167       x;
2168
2169     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2170     if (p == (const PixelPacket *) NULL)
2171       break;
2172     indexes=GetCacheViewAuthenticIndexQueue(image_view);
2173     for (x=0; x < (ssize_t) image->columns; x++)
2174     {
2175       index=1UL*indexes[x];
2176       if (image->matte != MagickFalse)
2177         {
2178           alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
2179           beta=(MagickRealType) (QuantumScale*(QuantumRange-
2180             image->colormap[index].opacity));
2181         }
2182       distance=fabs(alpha*GetRedPixelComponent(p)-beta*image->colormap[index].red);
2183       mean_error_per_pixel+=distance;
2184       mean_error+=distance*distance;
2185       if (distance > maximum_error)
2186         maximum_error=distance;
2187       distance=fabs(alpha*GetGreenPixelComponent(p)-beta*image->colormap[index].green);
2188       mean_error_per_pixel+=distance;
2189       mean_error+=distance*distance;
2190       if (distance > maximum_error)
2191         maximum_error=distance;
2192       distance=fabs(alpha*GetBluePixelComponent(p)-beta*image->colormap[index].blue);
2193       mean_error_per_pixel+=distance;
2194       mean_error+=distance*distance;
2195       if (distance > maximum_error)
2196         maximum_error=distance;
2197       p++;
2198     }
2199   }
2200   image_view=DestroyCacheView(image_view);
2201   image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2202   image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2203     mean_error/area;
2204   image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2205   return(MagickTrue);
2206 }
2207 \f
2208 /*
2209 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2210 %                                                                             %
2211 %                                                                             %
2212 %                                                                             %
2213 %   G e t Q u a n t i z e I n f o                                             %
2214 %                                                                             %
2215 %                                                                             %
2216 %                                                                             %
2217 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2218 %
2219 %  GetQuantizeInfo() initializes the QuantizeInfo structure.
2220 %
2221 %  The format of the GetQuantizeInfo method is:
2222 %
2223 %      GetQuantizeInfo(QuantizeInfo *quantize_info)
2224 %
2225 %  A description of each parameter follows:
2226 %
2227 %    o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2228 %
2229 */
2230 MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2231 {
2232   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2233   assert(quantize_info != (QuantizeInfo *) NULL);
2234   (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2235   quantize_info->number_colors=256;
2236   quantize_info->dither=MagickTrue;
2237   quantize_info->dither_method=RiemersmaDitherMethod;
2238   quantize_info->colorspace=UndefinedColorspace;
2239   quantize_info->measure_error=MagickFalse;
2240   quantize_info->signature=MagickSignature;
2241 }
2242 \f
2243 /*
2244 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2245 %                                                                             %
2246 %                                                                             %
2247 %                                                                             %
2248 %     P o s t e r i z e I m a g e C h a n n e l                               %
2249 %                                                                             %
2250 %                                                                             %
2251 %                                                                             %
2252 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2253 %
2254 %  PosterizeImage() reduces the image to a limited number of colors for a
2255 %  "poster" effect.
2256 %
2257 %  The format of the PosterizeImage method is:
2258 %
2259 %      MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2260 %        const MagickBooleanType dither)
2261 %      MagickBooleanType PosterizeImageChannel(Image *image,
2262 %        const ChannelType channel,const size_t levels,
2263 %        const MagickBooleanType dither)
2264 %
2265 %  A description of each parameter follows:
2266 %
2267 %    o image: Specifies a pointer to an Image structure.
2268 %
2269 %    o levels: Number of color levels allowed in each channel.  Very low values
2270 %      (2, 3, or 4) have the most visible effect.
2271 %
2272 %    o dither: Set this integer value to something other than zero to dither
2273 %      the mapped image.
2274 %
2275 */
2276
2277 static inline ssize_t MagickRound(MagickRealType x)
2278 {
2279   /*
2280     Round the fraction to nearest integer.
2281   */
2282   if (x >= 0.0)
2283     return((ssize_t) (x+0.5));
2284   return((ssize_t) (x-0.5));
2285 }
2286
2287 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2288   const MagickBooleanType dither)
2289 {
2290   MagickBooleanType
2291     status;
2292
2293   status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2294   return(status);
2295 }
2296
2297 MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2298   const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2299 {
2300 #define PosterizeImageTag  "Posterize/Image"
2301 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
2302   QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
2303
2304   CacheView
2305     *image_view;
2306
2307   ExceptionInfo
2308     *exception;
2309
2310   MagickBooleanType
2311     status;
2312
2313   MagickOffsetType
2314     progress;
2315
2316   QuantizeInfo
2317     *quantize_info;
2318
2319   register ssize_t
2320     i;
2321
2322   ssize_t
2323     y;
2324
2325   assert(image != (Image *) NULL);
2326   assert(image->signature == MagickSignature);
2327   if (image->debug != MagickFalse)
2328     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2329   if (image->storage_class == PseudoClass)
2330 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2331     #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2332 #endif
2333     for (i=0; i < (ssize_t) image->colors; i++)
2334     {
2335       /*
2336         Posterize colormap.
2337       */
2338       if ((channel & RedChannel) != 0)
2339         image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2340       if ((channel & GreenChannel) != 0)
2341         image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2342       if ((channel & BlueChannel) != 0)
2343         image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2344       if ((channel & OpacityChannel) != 0)
2345         image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
2346     }
2347   /*
2348     Posterize image.
2349   */
2350   status=MagickTrue;
2351   progress=0;
2352   exception=(&image->exception);
2353   image_view=AcquireCacheView(image);
2354 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2355   #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2356 #endif
2357   for (y=0; y < (ssize_t) image->rows; y++)
2358   {
2359     register IndexPacket
2360       *restrict indexes;
2361
2362     register PixelPacket
2363       *restrict q;
2364
2365     register ssize_t
2366       x;
2367
2368     if (status == MagickFalse)
2369       continue;
2370     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2371     if (q == (PixelPacket *) NULL)
2372       {
2373         status=MagickFalse;
2374         continue;
2375       }
2376     indexes=GetCacheViewAuthenticIndexQueue(image_view);
2377     for (x=0; x < (ssize_t) image->columns; x++)
2378     {
2379       if ((channel & RedChannel) != 0)
2380         q->red=PosterizePixel(q->red);
2381       if ((channel & GreenChannel) != 0)
2382         q->green=PosterizePixel(q->green);
2383       if ((channel & BlueChannel) != 0)
2384         q->blue=PosterizePixel(q->blue);
2385       if (((channel & OpacityChannel) != 0) &&
2386           (image->matte == MagickTrue))
2387         q->opacity=PosterizePixel(q->opacity);
2388       if (((channel & IndexChannel) != 0) &&
2389           (image->colorspace == CMYKColorspace))
2390         indexes[x]=PosterizePixel(indexes[x]);
2391       q++;
2392     }
2393     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2394       status=MagickFalse;
2395     if (image->progress_monitor != (MagickProgressMonitor) NULL)
2396       {
2397         MagickBooleanType
2398           proceed;
2399
2400 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2401         #pragma omp critical (MagickCore_PosterizeImageChannel)
2402 #endif
2403         proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2404           image->rows);
2405         if (proceed == MagickFalse)
2406           status=MagickFalse;
2407       }
2408   }
2409   image_view=DestroyCacheView(image_view);
2410   quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2411   quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2412     levels,MaxColormapSize+1);
2413   quantize_info->dither=dither;
2414   quantize_info->tree_depth=MaxTreeDepth;
2415   status=QuantizeImage(quantize_info,image);
2416   quantize_info=DestroyQuantizeInfo(quantize_info);
2417   return(status);
2418 }
2419 \f
2420 /*
2421 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2422 %                                                                             %
2423 %                                                                             %
2424 %                                                                             %
2425 +   P r u n e C h i l d                                                       %
2426 %                                                                             %
2427 %                                                                             %
2428 %                                                                             %
2429 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2430 %
2431 %  PruneChild() deletes the given node and merges its statistics into its
2432 %  parent.
2433 %
2434 %  The format of the PruneSubtree method is:
2435 %
2436 %      PruneChild(const Image *image,CubeInfo *cube_info,
2437 %        const NodeInfo *node_info)
2438 %
2439 %  A description of each parameter follows.
2440 %
2441 %    o image: the image.
2442 %
2443 %    o cube_info: A pointer to the Cube structure.
2444 %
2445 %    o node_info: pointer to node in color cube tree that is to be pruned.
2446 %
2447 */
2448 static void PruneChild(const Image *image,CubeInfo *cube_info,
2449   const NodeInfo *node_info)
2450 {
2451   NodeInfo
2452     *parent;
2453
2454   register ssize_t
2455     i;
2456
2457   size_t
2458     number_children;
2459
2460   /*
2461     Traverse any children.
2462   */
2463   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2464   for (i=0; i < (ssize_t) number_children; i++)
2465     if (node_info->child[i] != (NodeInfo *) NULL)
2466       PruneChild(image,cube_info,node_info->child[i]);
2467   /*
2468     Merge color statistics into parent.
2469   */
2470   parent=node_info->parent;
2471   parent->number_unique+=node_info->number_unique;
2472   parent->total_color.red+=node_info->total_color.red;
2473   parent->total_color.green+=node_info->total_color.green;
2474   parent->total_color.blue+=node_info->total_color.blue;
2475   parent->total_color.opacity+=node_info->total_color.opacity;
2476   parent->child[node_info->id]=(NodeInfo *) NULL;
2477   cube_info->nodes--;
2478 }
2479 \f
2480 /*
2481 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2482 %                                                                             %
2483 %                                                                             %
2484 %                                                                             %
2485 +  P r u n e L e v e l                                                        %
2486 %                                                                             %
2487 %                                                                             %
2488 %                                                                             %
2489 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2490 %
2491 %  PruneLevel() deletes all nodes at the bottom level of the color tree merging
2492 %  their color statistics into their parent node.
2493 %
2494 %  The format of the PruneLevel method is:
2495 %
2496 %      PruneLevel(const Image *image,CubeInfo *cube_info,
2497 %        const NodeInfo *node_info)
2498 %
2499 %  A description of each parameter follows.
2500 %
2501 %    o image: the image.
2502 %
2503 %    o cube_info: A pointer to the Cube structure.
2504 %
2505 %    o node_info: pointer to node in color cube tree that is to be pruned.
2506 %
2507 */
2508 static void PruneLevel(const Image *image,CubeInfo *cube_info,
2509   const NodeInfo *node_info)
2510 {
2511   register ssize_t
2512     i;
2513
2514   size_t
2515     number_children;
2516
2517   /*
2518     Traverse any children.
2519   */
2520   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2521   for (i=0; i < (ssize_t) number_children; i++)
2522     if (node_info->child[i] != (NodeInfo *) NULL)
2523       PruneLevel(image,cube_info,node_info->child[i]);
2524   if (node_info->level == cube_info->depth)
2525     PruneChild(image,cube_info,node_info);
2526 }
2527 \f
2528 /*
2529 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2530 %                                                                             %
2531 %                                                                             %
2532 %                                                                             %
2533 +  P r u n e T o C u b e D e p t h                                            %
2534 %                                                                             %
2535 %                                                                             %
2536 %                                                                             %
2537 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2538 %
2539 %  PruneToCubeDepth() deletes any nodes at a depth greater than
2540 %  cube_info->depth while merging their color statistics into their parent
2541 %  node.
2542 %
2543 %  The format of the PruneToCubeDepth method is:
2544 %
2545 %      PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2546 %        const NodeInfo *node_info)
2547 %
2548 %  A description of each parameter follows.
2549 %
2550 %    o cube_info: A pointer to the Cube structure.
2551 %
2552 %    o node_info: pointer to node in color cube tree that is to be pruned.
2553 %
2554 */
2555 static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2556   const NodeInfo *node_info)
2557 {
2558   register ssize_t
2559     i;
2560
2561   size_t
2562     number_children;
2563
2564   /*
2565     Traverse any children.
2566   */
2567   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2568   for (i=0; i < (ssize_t) number_children; i++)
2569     if (node_info->child[i] != (NodeInfo *) NULL)
2570       PruneToCubeDepth(image,cube_info,node_info->child[i]);
2571   if (node_info->level > cube_info->depth)
2572     PruneChild(image,cube_info,node_info);
2573 }
2574 \f
2575 /*
2576 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2577 %                                                                             %
2578 %                                                                             %
2579 %                                                                             %
2580 %  Q u a n t i z e I m a g e                                                  %
2581 %                                                                             %
2582 %                                                                             %
2583 %                                                                             %
2584 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2585 %
2586 %  QuantizeImage() analyzes the colors within a reference image and chooses a
2587 %  fixed number of colors to represent the image.  The goal of the algorithm
2588 %  is to minimize the color difference between the input and output image while
2589 %  minimizing the processing time.
2590 %
2591 %  The format of the QuantizeImage method is:
2592 %
2593 %      MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2594 %        Image *image)
2595 %
2596 %  A description of each parameter follows:
2597 %
2598 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2599 %
2600 %    o image: the image.
2601 %
2602 */
2603 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2604   Image *image)
2605 {
2606   CubeInfo
2607     *cube_info;
2608
2609   MagickBooleanType
2610     status;
2611
2612   size_t
2613     depth,
2614     maximum_colors;
2615
2616   assert(quantize_info != (const QuantizeInfo *) NULL);
2617   assert(quantize_info->signature == MagickSignature);
2618   assert(image != (Image *) NULL);
2619   assert(image->signature == MagickSignature);
2620   if (image->debug != MagickFalse)
2621     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2622   maximum_colors=quantize_info->number_colors;
2623   if (maximum_colors == 0)
2624     maximum_colors=MaxColormapSize;
2625   if (maximum_colors > MaxColormapSize)
2626     maximum_colors=MaxColormapSize;
2627   if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2628       (image->matte == MagickFalse))
2629     (void) SetGrayscaleImage(image);
2630   if ((image->storage_class == PseudoClass) &&
2631       (image->colors <= maximum_colors))
2632     return(MagickTrue);
2633   depth=quantize_info->tree_depth;
2634   if (depth == 0)
2635     {
2636       size_t
2637         colors;
2638
2639       /*
2640         Depth of color tree is: Log4(colormap size)+2.
2641       */
2642       colors=maximum_colors;
2643       for (depth=1; colors != 0; depth++)
2644         colors>>=2;
2645       if ((quantize_info->dither != MagickFalse) && (depth > 2))
2646         depth--;
2647       if ((image->matte != MagickFalse) && (depth > 5))
2648         depth--;
2649     }
2650   /*
2651     Initialize color cube.
2652   */
2653   cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2654   if (cube_info == (CubeInfo *) NULL)
2655     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2656       image->filename);
2657   status=ClassifyImageColors(cube_info,image,&image->exception);
2658   if (status != MagickFalse)
2659     {
2660       /*
2661         Reduce the number of colors in the image.
2662       */
2663       ReduceImageColors(image,cube_info);
2664       status=AssignImageColors(image,cube_info);
2665     }
2666   DestroyCubeInfo(cube_info);
2667   return(status);
2668 }
2669 \f
2670 /*
2671 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2672 %                                                                             %
2673 %                                                                             %
2674 %                                                                             %
2675 %   Q u a n t i z e I m a g e s                                               %
2676 %                                                                             %
2677 %                                                                             %
2678 %                                                                             %
2679 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2680 %
2681 %  QuantizeImages() analyzes the colors within a set of reference images and
2682 %  chooses a fixed number of colors to represent the set.  The goal of the
2683 %  algorithm is to minimize the color difference between the input and output
2684 %  images while minimizing the processing time.
2685 %
2686 %  The format of the QuantizeImages method is:
2687 %
2688 %      MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2689 %        Image *images)
2690 %
2691 %  A description of each parameter follows:
2692 %
2693 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2694 %
2695 %    o images: Specifies a pointer to a list of Image structures.
2696 %
2697 */
2698 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2699   Image *images)
2700 {
2701   CubeInfo
2702     *cube_info;
2703
2704   Image
2705     *image;
2706
2707   MagickBooleanType
2708     proceed,
2709     status;
2710
2711   MagickProgressMonitor
2712     progress_monitor;
2713
2714   register ssize_t
2715     i;
2716
2717   size_t
2718     depth,
2719     maximum_colors,
2720     number_images;
2721
2722   assert(quantize_info != (const QuantizeInfo *) NULL);
2723   assert(quantize_info->signature == MagickSignature);
2724   assert(images != (Image *) NULL);
2725   assert(images->signature == MagickSignature);
2726   if (images->debug != MagickFalse)
2727     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2728   if (GetNextImageInList(images) == (Image *) NULL)
2729     {
2730       /*
2731         Handle a single image with QuantizeImage.
2732       */
2733       status=QuantizeImage(quantize_info,images);
2734       return(status);
2735     }
2736   status=MagickFalse;
2737   maximum_colors=quantize_info->number_colors;
2738   if (maximum_colors == 0)
2739     maximum_colors=MaxColormapSize;
2740   if (maximum_colors > MaxColormapSize)
2741     maximum_colors=MaxColormapSize;
2742   depth=quantize_info->tree_depth;
2743   if (depth == 0)
2744     {
2745       size_t
2746         colors;
2747
2748       /*
2749         Depth of color tree is: Log4(colormap size)+2.
2750       */
2751       colors=maximum_colors;
2752       for (depth=1; colors != 0; depth++)
2753         colors>>=2;
2754       if (quantize_info->dither != MagickFalse)
2755         depth--;
2756     }
2757   /*
2758     Initialize color cube.
2759   */
2760   cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2761   if (cube_info == (CubeInfo *) NULL)
2762     {
2763       (void) ThrowMagickException(&images->exception,GetMagickModule(),
2764         ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2765       return(MagickFalse);
2766     }
2767   number_images=GetImageListLength(images);
2768   image=images;
2769   for (i=0; image != (Image *) NULL; i++)
2770   {
2771     progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2772       image->client_data);
2773     status=ClassifyImageColors(cube_info,image,&image->exception);
2774     if (status == MagickFalse)
2775       break;
2776     (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
2777     proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2778       number_images);
2779     if (proceed == MagickFalse)
2780       break;
2781     image=GetNextImageInList(image);
2782   }
2783   if (status != MagickFalse)
2784     {
2785       /*
2786         Reduce the number of colors in an image sequence.
2787       */
2788       ReduceImageColors(images,cube_info);
2789       image=images;
2790       for (i=0; image != (Image *) NULL; i++)
2791       {
2792         progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2793           NULL,image->client_data);
2794         status=AssignImageColors(image,cube_info);
2795         if (status == MagickFalse)
2796           break;
2797         (void) SetImageProgressMonitor(image,progress_monitor,
2798           image->client_data);
2799         proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2800           number_images);
2801         if (proceed == MagickFalse)
2802           break;
2803         image=GetNextImageInList(image);
2804       }
2805     }
2806   DestroyCubeInfo(cube_info);
2807   return(status);
2808 }
2809 \f
2810 /*
2811 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2812 %                                                                             %
2813 %                                                                             %
2814 %                                                                             %
2815 +   R e d u c e                                                               %
2816 %                                                                             %
2817 %                                                                             %
2818 %                                                                             %
2819 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2820 %
2821 %  Reduce() traverses the color cube tree and prunes any node whose
2822 %  quantization error falls below a particular threshold.
2823 %
2824 %  The format of the Reduce method is:
2825 %
2826 %      Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2827 %
2828 %  A description of each parameter follows.
2829 %
2830 %    o image: the image.
2831 %
2832 %    o cube_info: A pointer to the Cube structure.
2833 %
2834 %    o node_info: pointer to node in color cube tree that is to be pruned.
2835 %
2836 */
2837 static void Reduce(const Image *image,CubeInfo *cube_info,
2838   const NodeInfo *node_info)
2839 {
2840   register ssize_t
2841     i;
2842
2843   size_t
2844     number_children;
2845
2846   /*
2847     Traverse any children.
2848   */
2849   number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
2850   for (i=0; i < (ssize_t) number_children; i++)
2851     if (node_info->child[i] != (NodeInfo *) NULL)
2852       Reduce(image,cube_info,node_info->child[i]);
2853   if (node_info->quantize_error <= cube_info->pruning_threshold)
2854     PruneChild(image,cube_info,node_info);
2855   else
2856     {
2857       /*
2858         Find minimum pruning threshold.
2859       */
2860       if (node_info->number_unique > 0)
2861         cube_info->colors++;
2862       if (node_info->quantize_error < cube_info->next_threshold)
2863         cube_info->next_threshold=node_info->quantize_error;
2864     }
2865 }
2866 \f
2867 /*
2868 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2869 %                                                                             %
2870 %                                                                             %
2871 %                                                                             %
2872 +   R e d u c e I m a g e C o l o r s                                         %
2873 %                                                                             %
2874 %                                                                             %
2875 %                                                                             %
2876 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2877 %
2878 %  ReduceImageColors() repeatedly prunes the tree until the number of nodes
2879 %  with n2 > 0 is less than or equal to the maximum number of colors allowed
2880 %  in the output image.  On any given iteration over the tree, it selects
2881 %  those nodes whose E value is minimal for pruning and merges their
2882 %  color statistics upward. It uses a pruning threshold, Ep, to govern
2883 %  node selection as follows:
2884 %
2885 %    Ep = 0
2886 %    while number of nodes with (n2 > 0) > required maximum number of colors
2887 %      prune all nodes such that E <= Ep
2888 %      Set Ep to minimum E in remaining nodes
2889 %
2890 %  This has the effect of minimizing any quantization error when merging
2891 %  two nodes together.
2892 %
2893 %  When a node to be pruned has offspring, the pruning procedure invokes
2894 %  itself recursively in order to prune the tree from the leaves upward.
2895 %  n2,  Sr, Sg,  and  Sb in a node being pruned are always added to the
2896 %  corresponding data in that node's parent.  This retains the pruned
2897 %  node's color characteristics for later averaging.
2898 %
2899 %  For each node, n2 pixels exist for which that node represents the
2900 %  smallest volume in RGB space containing those pixel's colors.  When n2
2901 %  > 0 the node will uniquely define a color in the output image. At the
2902 %  beginning of reduction,  n2 = 0  for all nodes except a the leaves of
2903 %  the tree which represent colors present in the input image.
2904 %
2905 %  The other pixel count, n1, indicates the total number of colors
2906 %  within the cubic volume which the node represents.  This includes n1 -
2907 %  n2  pixels whose colors should be defined by nodes at a lower level in
2908 %  the tree.
2909 %
2910 %  The format of the ReduceImageColors method is:
2911 %
2912 %      ReduceImageColors(const Image *image,CubeInfo *cube_info)
2913 %
2914 %  A description of each parameter follows.
2915 %
2916 %    o image: the image.
2917 %
2918 %    o cube_info: A pointer to the Cube structure.
2919 %
2920 */
2921 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2922 {
2923 #define ReduceImageTag  "Reduce/Image"
2924
2925   MagickBooleanType
2926     proceed;
2927
2928   MagickOffsetType
2929     offset;
2930
2931   size_t
2932     span;
2933
2934   cube_info->next_threshold=0.0;
2935   for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2936   {
2937     cube_info->pruning_threshold=cube_info->next_threshold;
2938     cube_info->next_threshold=cube_info->root->quantize_error-1;
2939     cube_info->colors=0;
2940     Reduce(image,cube_info,cube_info->root);
2941     offset=(MagickOffsetType) span-cube_info->colors;
2942     proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2943       cube_info->maximum_colors+1);
2944     if (proceed == MagickFalse)
2945       break;
2946   }
2947 }
2948 \f
2949 /*
2950 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2951 %                                                                             %
2952 %                                                                             %
2953 %                                                                             %
2954 %   R e m a p I m a g e                                                       %
2955 %                                                                             %
2956 %                                                                             %
2957 %                                                                             %
2958 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2959 %
2960 %  RemapImage() replaces the colors of an image with the closest color from
2961 %  a reference image.
2962 %
2963 %  The format of the RemapImage method is:
2964 %
2965 %      MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2966 %        Image *image,const Image *remap_image)
2967 %
2968 %  A description of each parameter follows:
2969 %
2970 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2971 %
2972 %    o image: the image.
2973 %
2974 %    o remap_image: the reference image.
2975 %
2976 */
2977 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2978   Image *image,const Image *remap_image)
2979 {
2980   CubeInfo
2981     *cube_info;
2982
2983   MagickBooleanType
2984     status;
2985
2986   /*
2987     Initialize color cube.
2988   */
2989   assert(image != (Image *) NULL);
2990   assert(image->signature == MagickSignature);
2991   if (image->debug != MagickFalse)
2992     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2993   assert(remap_image != (Image *) NULL);
2994   assert(remap_image->signature == MagickSignature);
2995   cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2996     quantize_info->number_colors);
2997   if (cube_info == (CubeInfo *) NULL)
2998     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2999       image->filename);
3000   status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3001   if (status != MagickFalse)
3002     {
3003       /*
3004         Classify image colors from the reference image.
3005       */
3006       cube_info->quantize_info->number_colors=cube_info->colors;
3007       status=AssignImageColors(image,cube_info);
3008     }
3009   DestroyCubeInfo(cube_info);
3010   return(status);
3011 }
3012 \f
3013 /*
3014 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3015 %                                                                             %
3016 %                                                                             %
3017 %                                                                             %
3018 %   R e m a p I m a g e s                                                     %
3019 %                                                                             %
3020 %                                                                             %
3021 %                                                                             %
3022 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3023 %
3024 %  RemapImages() replaces the colors of a sequence of images with the
3025 %  closest color from a reference image.
3026 %
3027 %  The format of the RemapImage method is:
3028 %
3029 %      MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3030 %        Image *images,Image *remap_image)
3031 %
3032 %  A description of each parameter follows:
3033 %
3034 %    o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3035 %
3036 %    o images: the image sequence.
3037 %
3038 %    o remap_image: the reference image.
3039 %
3040 */
3041 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3042   Image *images,const Image *remap_image)
3043 {
3044   CubeInfo
3045     *cube_info;
3046
3047   Image
3048     *image;
3049
3050   MagickBooleanType
3051     status;
3052
3053   assert(images != (Image *) NULL);
3054   assert(images->signature == MagickSignature);
3055   if (images->debug != MagickFalse)
3056     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3057   image=images;
3058   if (remap_image == (Image *) NULL)
3059     {
3060       /*
3061         Create a global colormap for an image sequence.
3062       */
3063       status=QuantizeImages(quantize_info,images);
3064       return(status);
3065     }
3066   /*
3067     Classify image colors from the reference image.
3068   */
3069   cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3070     quantize_info->number_colors);
3071   if (cube_info == (CubeInfo *) NULL)
3072     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3073       image->filename);
3074   status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3075   if (status != MagickFalse)
3076     {
3077       /*
3078         Classify image colors from the reference image.
3079       */
3080       cube_info->quantize_info->number_colors=cube_info->colors;
3081       image=images;
3082       for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3083       {
3084         status=AssignImageColors(image,cube_info);
3085         if (status == MagickFalse)
3086           break;
3087       }
3088     }
3089   DestroyCubeInfo(cube_info);
3090   return(status);
3091 }
3092 \f
3093 /*
3094 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3095 %                                                                             %
3096 %                                                                             %
3097 %                                                                             %
3098 %   S e t G r a y s c a l e I m a g e                                         %
3099 %                                                                             %
3100 %                                                                             %
3101 %                                                                             %
3102 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3103 %
3104 %  SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3105 %
3106 %  The format of the SetGrayscaleImage method is:
3107 %
3108 %      MagickBooleanType SetGrayscaleImage(Image *image)
3109 %
3110 %  A description of each parameter follows:
3111 %
3112 %    o image: The image.
3113 %
3114 */
3115
3116 #if defined(__cplusplus) || defined(c_plusplus)
3117 extern "C" {
3118 #endif
3119
3120 static int IntensityCompare(const void *x,const void *y)
3121 {
3122   PixelPacket
3123     *color_1,
3124     *color_2;
3125
3126   ssize_t
3127     intensity;
3128
3129   color_1=(PixelPacket *) x;
3130   color_2=(PixelPacket *) y;
3131   intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
3132     PixelIntensityToQuantum(color_2);
3133   return((int) intensity);
3134 }
3135
3136 #if defined(__cplusplus) || defined(c_plusplus)
3137 }
3138 #endif
3139
3140 static MagickBooleanType SetGrayscaleImage(Image *image)
3141 {
3142   CacheView
3143     *image_view;
3144
3145   ExceptionInfo
3146     *exception;
3147
3148   MagickBooleanType
3149     status;
3150
3151   PixelPacket
3152     *colormap;
3153
3154   register ssize_t
3155     i;
3156
3157   ssize_t
3158     *colormap_index,
3159     j,
3160     y;
3161
3162   assert(image != (Image *) NULL);
3163   assert(image->signature == MagickSignature);
3164   if (image->type != GrayscaleType)
3165     (void) TransformImageColorspace(image,GRAYColorspace);
3166   colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
3167     sizeof(*colormap_index));
3168   if (colormap_index == (ssize_t *) NULL)
3169     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3170       image->filename);
3171   if (image->storage_class != PseudoClass)
3172     {
3173       ExceptionInfo
3174         *exception;
3175
3176       for (i=0; i <= (ssize_t) MaxMap; i++)
3177         colormap_index[i]=(-1);
3178       if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3179         ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3180           image->filename);
3181       image->colors=0;
3182       status=MagickTrue;
3183       exception=(&image->exception);
3184       image_view=AcquireCacheView(image);
3185 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3186       #pragma omp parallel for schedule(dynamic,4) shared(status)
3187 #endif
3188       for (y=0; y < (ssize_t) image->rows; y++)
3189       {
3190         register IndexPacket
3191           *restrict indexes;
3192
3193         register const PixelPacket
3194           *restrict q;
3195
3196         register ssize_t
3197           x;
3198
3199         if (status == MagickFalse)
3200           continue;
3201         q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3202           exception);
3203         if (q == (PixelPacket *) NULL)
3204           {
3205             status=MagickFalse;
3206             continue;
3207           }
3208         indexes=GetCacheViewAuthenticIndexQueue(image_view);
3209         for (x=0; x < (ssize_t) image->columns; x++)
3210         {
3211           register size_t
3212             intensity;
3213
3214           intensity=ScaleQuantumToMap(q->red);
3215           if (colormap_index[intensity] < 0)
3216             {
3217 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3218     #pragma omp critical (MagickCore_SetGrayscaleImage)
3219 #endif
3220               if (colormap_index[intensity] < 0)
3221                 {
3222                   colormap_index[intensity]=(ssize_t) image->colors;
3223                   image->colormap[image->colors]=(*q);
3224                   image->colors++;
3225                }
3226             }
3227           indexes[x]=(IndexPacket) colormap_index[intensity];
3228           q++;
3229         }
3230         if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3231           status=MagickFalse;
3232       }
3233       image_view=DestroyCacheView(image_view);
3234     }
3235   for (i=0; i < (ssize_t) image->colors; i++)
3236     image->colormap[i].opacity=(unsigned short) i;
3237   qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3238     IntensityCompare);
3239   colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3240     sizeof(*colormap));
3241   if (colormap == (PixelPacket *) NULL)
3242     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3243       image->filename);
3244   j=0;
3245   colormap[j]=image->colormap[0];
3246   for (i=0; i < (ssize_t) image->colors; i++)
3247   {
3248     if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3249       {
3250         j++;
3251         colormap[j]=image->colormap[i];
3252       }
3253     colormap_index[(ssize_t) image->colormap[i].opacity]=j;
3254   }
3255   image->colors=(size_t) (j+1);
3256   image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3257   image->colormap=colormap;
3258   status=MagickTrue;
3259   exception=(&image->exception);
3260   image_view=AcquireCacheView(image);
3261 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3262   #pragma omp parallel for schedule(dynamic,4) shared(status)
3263 #endif
3264   for (y=0; y < (ssize_t) image->rows; y++)
3265   {
3266     register IndexPacket
3267       *restrict indexes;
3268
3269     register const PixelPacket
3270       *restrict q;
3271
3272     register ssize_t
3273       x;
3274
3275     if (status == MagickFalse)
3276       continue;
3277     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3278     if (q == (PixelPacket *) NULL)
3279       {
3280         status=MagickFalse;
3281         continue;
3282       }
3283     indexes=GetCacheViewAuthenticIndexQueue(image_view);
3284     for (x=0; x < (ssize_t) image->columns; x++)
3285       indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3286     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3287       status=MagickFalse;
3288   }
3289   image_view=DestroyCacheView(image_view);
3290   colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
3291   image->type=GrayscaleType;
3292   if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3293     image->type=BilevelType;
3294   return(status);
3295 }