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