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