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