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