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