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