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