blob: b62cd56d5aa61f3ad1adbd9054eba0c4d475c5a1 [file] [log] [blame]
cristy3ed852e2009-09-05 21:47:34 +00001/*
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% John Cristy %
17% July 1992 %
18% %
19% %
cristy7e41fe82010-12-04 23:12:08 +000020% Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization %
cristy3ed852e2009-09-05 21:47:34 +000021% 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% http://www.imagemagick.org/script/license.php %
27% %
28% Unless required by applicable law or agreed to in writing, software %
29% distributed under the License is distributed on an "AS IS" BASIS, %
30% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31% See the License for the specific language governing permissions and %
32% limitations under the License. %
33% %
34%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35%
36% Realism in computer graphics typically requires using 24 bits/pixel to
37% generate an image. Yet many graphic display devices do not contain the
38% amount of memory necessary to match the spatial and color resolution of
39% the human eye. The Quantize methods takes a 24 bit image and reduces
40% the number of colors so it can be displayed on raster device with less
41% bits per pixel. In most instances, the quantized image closely
42% resembles the original reference image.
43%
44% A reduction of colors in an image is also desirable for image
45% transmission and real-time animation.
46%
47% QuantizeImage() takes a standard RGB or monochrome images and quantizes
48% them down to some fixed number of colors.
49%
50% For purposes of color allocation, an image is a set of n pixels, where
51% each pixel is a point in RGB space. RGB space is a 3-dimensional
52% vector space, and each pixel, Pi, is defined by an ordered triple of
53% red, green, and blue coordinates, (Ri, Gi, Bi).
54%
55% Each primary color component (red, green, or blue) represents an
56% intensity which varies linearly from 0 to a maximum value, Cmax, which
57% corresponds to full saturation of that color. Color allocation is
58% defined over a domain consisting of the cube in RGB space with opposite
59% vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
60% 255.
61%
62% The algorithm maps this domain onto a tree in which each node
63% represents a cube within that domain. In the following discussion
64% these cubes are defined by the coordinate of two opposite vertices:
65% The vertex nearest the origin in RGB space and the vertex farthest from
66% the origin.
67%
68% The tree's root node represents the entire domain, (0,0,0) through
69% (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70% subdividing one node's cube into eight smaller cubes of equal size.
71% This corresponds to bisecting the parent cube with planes passing
72% through the midpoints of each edge.
73%
74% The basic algorithm operates in three phases: Classification,
75% Reduction, and Assignment. Classification builds a color description
76% tree for the image. Reduction collapses the tree until the number it
77% represents, at most, the number of colors desired in the output image.
78% Assignment defines the output image's color map and sets each pixel's
79% color by restorage_class in the reduced tree. Our goal is to minimize
80% the numerical discrepancies between the original colors and quantized
81% colors (quantization error).
82%
83% Classification begins by initializing a color description tree of
84% sufficient depth to represent each possible input color in a leaf.
85% However, it is impractical to generate a fully-formed color description
86% tree in the storage_class phase for realistic values of Cmax. If
87% colors components in the input image are quantized to k-bit precision,
88% so that Cmax= 2k-1, the tree would need k levels below the root node to
89% allow representing each possible input color in a leaf. This becomes
90% prohibitive because the tree's total number of nodes is 1 +
91% sum(i=1, k, 8k).
92%
93% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95% Initializes data structures for nodes only as they are needed; (2)
96% Chooses a maximum depth for the tree as a function of the desired
97% number of colors in the output image (currently log2(colormap size)).
98%
99% For each pixel in the input image, storage_class scans downward from
100% the root of the color description tree. At each level of the tree it
101% identifies the single node which represents a cube in RGB space
102% containing the pixel's color. It updates the following data for each
103% such node:
104%
105% n1: Number of pixels whose color is contained in the RGB cube which
106% this node represents;
107%
108% n2: Number of pixels whose color is not represented in a node at
109% lower depth in the tree; initially, n2 = 0 for all nodes except
110% leaves of the tree.
111%
112% Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113% pixels not classified at a lower depth. The combination of these sums
114% and n2 will ultimately characterize the mean color of a set of
115% pixels represented by this node.
116%
117% E: the distance squared in RGB space between each pixel contained
118% within a node and the nodes' center. This represents the
119% quantization error for a node.
120%
121% Reduction repeatedly prunes the tree until the number of nodes with n2
122% > 0 is less than or equal to the maximum number of colors allowed in
123% the output image. On any given iteration over the tree, it selects
124% those nodes whose E count is minimal for pruning and merges their color
125% statistics upward. It uses a pruning threshold, Ep, to govern node
126% selection as follows:
127%
128% Ep = 0
129% while number of nodes with (n2 > 0) > required maximum number of colors
130% prune all nodes such that E <= Ep
131% Set Ep to minimum E in remaining nodes
132%
133% This has the effect of minimizing any quantization error when merging
134% two nodes together.
135%
136% When a node to be pruned has offspring, the pruning procedure invokes
137% itself recursively in order to prune the tree from the leaves upward.
138% n2, Sr, Sg, and Sb in a node being pruned are always added to the
139% corresponding data in that node's parent. This retains the pruned
140% node's color characteristics for later averaging.
141%
142% For each node, n2 pixels exist for which that node represents the
143% smallest volume in RGB space containing those pixel's colors. When n2
144% > 0 the node will uniquely define a color in the output image. At the
145% beginning of reduction, n2 = 0 for all nodes except a the leaves of
146% the tree which represent colors present in the input image.
147%
148% The other pixel count, n1, indicates the total number of colors within
149% the cubic volume which the node represents. This includes n1 - n2
150% pixels whose colors should be defined by nodes at a lower level in the
151% tree.
152%
153% Assignment generates the output image from the pruned tree. The output
154% image consists of two parts: (1) A color map, which is an array of
155% color descriptions (RGB triples) for each color present in the output
156% image; (2) A pixel array, which represents each pixel as an index
157% into the color map array.
158%
159% First, the assignment phase makes one pass over the pruned color
160% description tree to establish the image's color map. For each node
161% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162% color of all pixels that classify no lower than this node. Each of
163% these colors becomes an entry in the color map.
164%
165% Finally, the assignment phase reclassifies each pixel in the pruned
166% tree to identify the deepest node containing the pixel's color. The
167% pixel's value in the pixel array becomes the index of this node's mean
168% color in the color map.
169%
170% This method is based on a similar algorithm written by Paul Raveling.
171%
172*/
173
174/*
175 Include declarations.
176*/
cristy4c08aed2011-07-01 19:47:50 +0000177#include "MagickCore/studio.h"
178#include "MagickCore/attribute.h"
179#include "MagickCore/cache-view.h"
180#include "MagickCore/color.h"
181#include "MagickCore/color-private.h"
182#include "MagickCore/colormap.h"
183#include "MagickCore/colorspace.h"
cristy510d06a2011-07-06 23:43:54 +0000184#include "MagickCore/colorspace-private.h"
cristy4c08aed2011-07-01 19:47:50 +0000185#include "MagickCore/enhance.h"
186#include "MagickCore/exception.h"
187#include "MagickCore/exception-private.h"
188#include "MagickCore/histogram.h"
189#include "MagickCore/image.h"
190#include "MagickCore/image-private.h"
191#include "MagickCore/list.h"
192#include "MagickCore/memory_.h"
193#include "MagickCore/monitor.h"
194#include "MagickCore/monitor-private.h"
195#include "MagickCore/option.h"
196#include "MagickCore/pixel-accessor.h"
197#include "MagickCore/quantize.h"
198#include "MagickCore/quantum.h"
199#include "MagickCore/quantum-private.h"
200#include "MagickCore/string_.h"
201#include "MagickCore/thread-private.h"
cristy3ed852e2009-09-05 21:47:34 +0000202
203/*
204 Define declarations.
205*/
cristye1287512010-06-19 17:38:25 +0000206#if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
cristy3ed852e2009-09-05 21:47:34 +0000207#define CacheShift 2
cristye1287512010-06-19 17:38:25 +0000208#else
209#define CacheShift 3
210#endif
cristy3ed852e2009-09-05 21:47:34 +0000211#define ErrorQueueLength 16
212#define MaxNodes 266817
213#define MaxTreeDepth 8
214#define NodesInAList 1920
215
216/*
217 Typdef declarations.
218*/
219typedef struct _RealPixelPacket
220{
221 MagickRealType
222 red,
223 green,
224 blue,
cristy4c08aed2011-07-01 19:47:50 +0000225 alpha;
cristy3ed852e2009-09-05 21:47:34 +0000226} RealPixelPacket;
227
228typedef struct _NodeInfo
229{
230 struct _NodeInfo
231 *parent,
232 *child[16];
233
234 MagickSizeType
235 number_unique;
236
237 RealPixelPacket
238 total_color;
239
240 MagickRealType
241 quantize_error;
242
cristybb503372010-05-27 20:51:26 +0000243 size_t
cristy3ed852e2009-09-05 21:47:34 +0000244 color_number,
245 id,
246 level;
247} NodeInfo;
248
249typedef struct _Nodes
250{
251 NodeInfo
252 *nodes;
253
254 struct _Nodes
255 *next;
256} Nodes;
257
258typedef struct _CubeInfo
259{
260 NodeInfo
261 *root;
262
cristybb503372010-05-27 20:51:26 +0000263 size_t
cristy3ed852e2009-09-05 21:47:34 +0000264 colors,
265 maximum_colors;
266
cristybb503372010-05-27 20:51:26 +0000267 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000268 transparent_index;
269
270 MagickSizeType
271 transparent_pixels;
272
273 RealPixelPacket
274 target;
275
276 MagickRealType
277 distance,
278 pruning_threshold,
279 next_threshold;
280
cristybb503372010-05-27 20:51:26 +0000281 size_t
cristy3ed852e2009-09-05 21:47:34 +0000282 nodes,
283 free_nodes,
284 color_number;
285
286 NodeInfo
287 *next_node;
288
289 Nodes
290 *node_queue;
291
cristybb503372010-05-27 20:51:26 +0000292 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000293 *cache;
294
295 RealPixelPacket
296 error[ErrorQueueLength];
297
298 MagickRealType
299 weights[ErrorQueueLength];
300
301 QuantizeInfo
302 *quantize_info;
303
304 MagickBooleanType
305 associate_alpha;
306
cristybb503372010-05-27 20:51:26 +0000307 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000308 x,
309 y;
310
cristybb503372010-05-27 20:51:26 +0000311 size_t
cristy3ed852e2009-09-05 21:47:34 +0000312 depth;
313
314 MagickOffsetType
315 offset;
316
317 MagickSizeType
318 span;
319} CubeInfo;
320
321/*
322 Method prototypes.
323*/
324static CubeInfo
cristybb503372010-05-27 20:51:26 +0000325 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
cristy3ed852e2009-09-05 21:47:34 +0000326
327static NodeInfo
cristybb503372010-05-27 20:51:26 +0000328 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
cristy3ed852e2009-09-05 21:47:34 +0000329
330static MagickBooleanType
331 AssignImageColors(Image *,CubeInfo *),
332 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
333 DitherImage(Image *,CubeInfo *),
334 SetGrayscaleImage(Image *);
335
cristybb503372010-05-27 20:51:26 +0000336static size_t
cristy3ed852e2009-09-05 21:47:34 +0000337 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
338
339static void
340 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
341 DestroyCubeInfo(CubeInfo *),
342 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
343 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
344 ReduceImageColors(const Image *,CubeInfo *);
345
346/*
347%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
348% %
349% %
350% %
351% A c q u i r e Q u a n t i z e I n f o %
352% %
353% %
354% %
355%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
356%
357% AcquireQuantizeInfo() allocates the QuantizeInfo structure.
358%
359% The format of the AcquireQuantizeInfo method is:
360%
361% QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
362%
363% A description of each parameter follows:
364%
365% o image_info: the image info.
366%
367*/
368MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
369{
370 QuantizeInfo
371 *quantize_info;
372
cristy73bd4a52010-10-05 11:24:23 +0000373 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
cristy3ed852e2009-09-05 21:47:34 +0000374 if (quantize_info == (QuantizeInfo *) NULL)
375 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
376 GetQuantizeInfo(quantize_info);
377 if (image_info != (ImageInfo *) NULL)
378 {
379 const char
380 *option;
381
382 quantize_info->dither=image_info->dither;
383 option=GetImageOption(image_info,"dither");
384 if (option != (const char *) NULL)
cristy042ee782011-04-22 18:48:30 +0000385 quantize_info->dither_method=(DitherMethod) ParseCommandOption(
cristy3ed852e2009-09-05 21:47:34 +0000386 MagickDitherOptions,MagickFalse,option);
387 quantize_info->measure_error=image_info->verbose;
388 }
389 return(quantize_info);
390}
391
392/*
393%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
394% %
395% %
396% %
397+ A s s i g n I m a g e C o l o r s %
398% %
399% %
400% %
401%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
402%
403% AssignImageColors() generates the output image from the pruned tree. The
404% output image consists of two parts: (1) A color map, which is an array
405% of color descriptions (RGB triples) for each color present in the
406% output image; (2) A pixel array, which represents each pixel as an
407% index into the color map array.
408%
409% First, the assignment phase makes one pass over the pruned color
410% description tree to establish the image's color map. For each node
411% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
412% color of all pixels that classify no lower than this node. Each of
413% these colors becomes an entry in the color map.
414%
415% Finally, the assignment phase reclassifies each pixel in the pruned
416% tree to identify the deepest node containing the pixel's color. The
417% pixel's value in the pixel array becomes the index of this node's mean
418% color in the color map.
419%
420% The format of the AssignImageColors() method is:
421%
422% MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
423%
424% A description of each parameter follows.
425%
426% o image: the image.
427%
428% o cube_info: A pointer to the Cube structure.
429%
430*/
431
cristy4c08aed2011-07-01 19:47:50 +0000432static inline void AssociateAlphaPixel(const Image *image,
433 const CubeInfo *cube_info,const Quantum *pixel,
434 RealPixelPacket *alpha_pixel)
cristy3ed852e2009-09-05 21:47:34 +0000435{
436 MagickRealType
437 alpha;
438
439 if ((cube_info->associate_alpha == MagickFalse) ||
cristy4c08aed2011-07-01 19:47:50 +0000440 (GetPixelAlpha(image,pixel)== OpaqueAlpha))
cristy3ed852e2009-09-05 21:47:34 +0000441 {
cristy4c08aed2011-07-01 19:47:50 +0000442 alpha_pixel->red=(MagickRealType) GetPixelRed(image,pixel);
443 alpha_pixel->green=(MagickRealType) GetPixelGreen(image,pixel);
444 alpha_pixel->blue=(MagickRealType) GetPixelBlue(image,pixel);
445 alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
cristy3ed852e2009-09-05 21:47:34 +0000446 return;
447 }
cristy4c08aed2011-07-01 19:47:50 +0000448 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,pixel));
449 alpha_pixel->red=alpha*GetPixelRed(image,pixel);
450 alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
451 alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
452 alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
453}
454
455static inline void AssociateAlphaPixelPacket(const Image *image,
456 const CubeInfo *cube_info,const PixelPacket *pixel,
457 RealPixelPacket *alpha_pixel)
458{
459 MagickRealType
460 alpha;
461
462 if ((cube_info->associate_alpha == MagickFalse) ||
463 (pixel->alpha == OpaqueAlpha))
464 {
465 alpha_pixel->red=(MagickRealType) pixel->red;
466 alpha_pixel->green=(MagickRealType) pixel->green;
467 alpha_pixel->blue=(MagickRealType) pixel->blue;
468 alpha_pixel->alpha=(MagickRealType) pixel->alpha;
469 return;
470 }
471 alpha=(MagickRealType) (QuantumScale*pixel->alpha);
472 alpha_pixel->red=alpha*pixel->red;
473 alpha_pixel->green=alpha*pixel->green;
474 alpha_pixel->blue=alpha*pixel->blue;
475 alpha_pixel->alpha=(MagickRealType) pixel->alpha;
cristy3ed852e2009-09-05 21:47:34 +0000476}
477
cristy75ffdb72010-01-07 17:40:12 +0000478static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
cristy3ed852e2009-09-05 21:47:34 +0000479{
480 if (value <= 0.0)
481 return((Quantum) 0);
482 if (value >= QuantumRange)
483 return((Quantum) QuantumRange);
484 return((Quantum) (value+0.5));
485}
486
cristybb503372010-05-27 20:51:26 +0000487static inline size_t ColorToNodeId(const CubeInfo *cube_info,
488 const RealPixelPacket *pixel,size_t index)
cristy3ed852e2009-09-05 21:47:34 +0000489{
cristybb503372010-05-27 20:51:26 +0000490 size_t
cristy3ed852e2009-09-05 21:47:34 +0000491 id;
492
cristy4c08aed2011-07-01 19:47:50 +0000493 id=(size_t) (((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x01) |
494 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x01) << 1 |
495 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x01) << 2);
cristy3ed852e2009-09-05 21:47:34 +0000496 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +0000497 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->alpha)) >> index) & 0x1) << 3;
cristy3ed852e2009-09-05 21:47:34 +0000498 return(id);
499}
500
cristy3ed852e2009-09-05 21:47:34 +0000501static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
502{
503#define AssignImageTag "Assign/Image"
504
cristyecc31b12011-02-13 00:32:29 +0000505 ssize_t
cristyecc31b12011-02-13 00:32:29 +0000506 y;
507
cristy3ed852e2009-09-05 21:47:34 +0000508 /*
509 Allocate image colormap.
510 */
511 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
512 (cube_info->quantize_info->colorspace != CMYKColorspace))
513 (void) TransformImageColorspace((Image *) image,
514 cube_info->quantize_info->colorspace);
515 else
516 if ((image->colorspace != GRAYColorspace) &&
cristy510d06a2011-07-06 23:43:54 +0000517 (IsRGBColorspace(image->colorspace) == MagickFalse) &&
cristy3ed852e2009-09-05 21:47:34 +0000518 (image->colorspace != CMYColorspace))
519 (void) TransformImageColorspace((Image *) image,RGBColorspace);
520 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
521 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
522 image->filename);
523 image->colors=0;
524 cube_info->transparent_pixels=0;
525 cube_info->transparent_index=(-1);
526 (void) DefineImageColormap(image,cube_info,cube_info->root);
527 /*
528 Create a reduced color image.
529 */
530 if ((cube_info->quantize_info->dither != MagickFalse) &&
cristyd5acfd12010-06-15 00:11:38 +0000531 (cube_info->quantize_info->dither_method != NoDitherMethod))
cristy3ed852e2009-09-05 21:47:34 +0000532 (void) DitherImage(image,cube_info);
533 else
534 {
cristy3ed852e2009-09-05 21:47:34 +0000535 CacheView
536 *image_view;
537
cristye9717ac2011-02-20 16:17:17 +0000538 ExceptionInfo
539 *exception;
540
541 MagickBooleanType
542 status;
543
544 status=MagickTrue;
cristy3ed852e2009-09-05 21:47:34 +0000545 exception=(&image->exception);
546 image_view=AcquireCacheView(image);
cristye9717ac2011-02-20 16:17:17 +0000547#if defined(MAGICKCORE_OPENMP_SUPPORT)
548 #pragma omp parallel for schedule(dynamic,4) shared(status)
549#endif
cristybb503372010-05-27 20:51:26 +0000550 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000551 {
cristye9717ac2011-02-20 16:17:17 +0000552 CubeInfo
553 cube;
554
cristy4c08aed2011-07-01 19:47:50 +0000555 register Quantum
cristyc47d1f82009-11-26 01:44:43 +0000556 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000557
cristye9717ac2011-02-20 16:17:17 +0000558 register ssize_t
559 x;
560
561 ssize_t
562 count;
563
564 if (status == MagickFalse)
565 continue;
cristy3ed852e2009-09-05 21:47:34 +0000566 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
567 exception);
cristy4c08aed2011-07-01 19:47:50 +0000568 if (q == (const Quantum *) NULL)
cristye9717ac2011-02-20 16:17:17 +0000569 {
570 status=MagickFalse;
571 continue;
572 }
cristye9717ac2011-02-20 16:17:17 +0000573 cube=(*cube_info);
cristybb503372010-05-27 20:51:26 +0000574 for (x=0; x < (ssize_t) image->columns; x+=count)
cristy3ed852e2009-09-05 21:47:34 +0000575 {
cristye9717ac2011-02-20 16:17:17 +0000576 RealPixelPacket
577 pixel;
578
579 register const NodeInfo
580 *node_info;
581
582 register ssize_t
583 i;
584
585 size_t
586 id,
587 index;
588
cristy3ed852e2009-09-05 21:47:34 +0000589 /*
590 Identify the deepest node containing the pixel's color.
591 */
cristybb503372010-05-27 20:51:26 +0000592 for (count=1; (x+count) < (ssize_t) image->columns; count++)
cristy4c08aed2011-07-01 19:47:50 +0000593 {
594 PixelPacket
595 packet;
596
cristydcfc1ad2011-07-07 16:25:41 +0000597 GetPixelPacket(image,q+count*GetPixelComponents(image),&packet);
cristy4c08aed2011-07-01 19:47:50 +0000598 if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +0000599 break;
cristy4c08aed2011-07-01 19:47:50 +0000600 }
601 AssociateAlphaPixel(image,&cube,q,&pixel);
cristye9717ac2011-02-20 16:17:17 +0000602 node_info=cube.root;
cristybb503372010-05-27 20:51:26 +0000603 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +0000604 {
cristye9717ac2011-02-20 16:17:17 +0000605 id=ColorToNodeId(&cube,&pixel,index);
cristy3ed852e2009-09-05 21:47:34 +0000606 if (node_info->child[id] == (NodeInfo *) NULL)
607 break;
608 node_info=node_info->child[id];
609 }
610 /*
611 Find closest color among siblings and their children.
612 */
cristye9717ac2011-02-20 16:17:17 +0000613 cube.target=pixel;
614 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
cristy3ed852e2009-09-05 21:47:34 +0000615 (QuantumRange+1.0)+1.0);
cristye9717ac2011-02-20 16:17:17 +0000616 ClosestColor(image,&cube,node_info->parent);
617 index=cube.color_number;
cristybb503372010-05-27 20:51:26 +0000618 for (i=0; i < (ssize_t) count; i++)
cristy3ed852e2009-09-05 21:47:34 +0000619 {
620 if (image->storage_class == PseudoClass)
cristy4c08aed2011-07-01 19:47:50 +0000621 SetPixelIndex(image,(Quantum) index,q);
cristye9717ac2011-02-20 16:17:17 +0000622 if (cube.quantize_info->measure_error == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +0000623 {
cristy4c08aed2011-07-01 19:47:50 +0000624 SetPixelRed(image,image->colormap[index].red,q);
625 SetPixelGreen(image,image->colormap[index].green,q);
626 SetPixelBlue(image,image->colormap[index].blue,q);
cristye9717ac2011-02-20 16:17:17 +0000627 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +0000628 SetPixelAlpha(image,image->colormap[index].alpha,q);
cristy3ed852e2009-09-05 21:47:34 +0000629 }
cristydcfc1ad2011-07-07 16:25:41 +0000630 q+=GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +0000631 }
632 }
633 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
cristye9717ac2011-02-20 16:17:17 +0000634 status=MagickFalse;
635 if (image->progress_monitor != (MagickProgressMonitor) NULL)
636 {
637 MagickBooleanType
638 proceed;
639
640#if defined(MAGICKCORE_OPENMP_SUPPORT)
641 #pragma omp critical (MagickCore_AssignImageColors)
642#endif
643 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
644 image->rows);
645 if (proceed == MagickFalse)
646 status=MagickFalse;
647 }
cristy3ed852e2009-09-05 21:47:34 +0000648 }
649 image_view=DestroyCacheView(image_view);
650 }
651 if (cube_info->quantize_info->measure_error != MagickFalse)
652 (void) GetImageQuantizeError(image);
653 if ((cube_info->quantize_info->number_colors == 2) &&
654 (cube_info->quantize_info->colorspace == GRAYColorspace))
655 {
656 Quantum
657 intensity;
658
659 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000660 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000661
cristye9717ac2011-02-20 16:17:17 +0000662 register ssize_t
663 i;
664
cristy3ed852e2009-09-05 21:47:34 +0000665 /*
666 Monochrome image.
667 */
668 q=image->colormap;
cristybb503372010-05-27 20:51:26 +0000669 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +0000670 {
cristy4c08aed2011-07-01 19:47:50 +0000671 intensity=(Quantum) ((MagickRealType) GetPixelPacketIntensity(q) <
672 ((MagickRealType) QuantumRange/2.0) ? 0 : QuantumRange);
673 q->red=intensity;
674 q->green=intensity;
675 q->blue=intensity;
cristy3ed852e2009-09-05 21:47:34 +0000676 q++;
677 }
678 }
679 (void) SyncImage(image);
680 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
681 (cube_info->quantize_info->colorspace != CMYKColorspace))
682 (void) TransformImageColorspace((Image *) image,RGBColorspace);
683 return(MagickTrue);
684}
685
686/*
687%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
688% %
689% %
690% %
691+ C l a s s i f y I m a g e C o l o r s %
692% %
693% %
694% %
695%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
696%
697% ClassifyImageColors() begins by initializing a color description tree
698% of sufficient depth to represent each possible input color in a leaf.
699% However, it is impractical to generate a fully-formed color
700% description tree in the storage_class phase for realistic values of
701% Cmax. If colors components in the input image are quantized to k-bit
702% precision, so that Cmax= 2k-1, the tree would need k levels below the
703% root node to allow representing each possible input color in a leaf.
704% This becomes prohibitive because the tree's total number of nodes is
705% 1 + sum(i=1,k,8k).
706%
707% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
708% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
709% Initializes data structures for nodes only as they are needed; (2)
710% Chooses a maximum depth for the tree as a function of the desired
711% number of colors in the output image (currently log2(colormap size)).
712%
713% For each pixel in the input image, storage_class scans downward from
714% the root of the color description tree. At each level of the tree it
715% identifies the single node which represents a cube in RGB space
716% containing It updates the following data for each such node:
717%
718% n1 : Number of pixels whose color is contained in the RGB cube
719% which this node represents;
720%
721% n2 : Number of pixels whose color is not represented in a node at
722% lower depth in the tree; initially, n2 = 0 for all nodes except
723% leaves of the tree.
724%
725% Sr, Sg, Sb : Sums of the red, green, and blue component values for
726% all pixels not classified at a lower depth. The combination of
727% these sums and n2 will ultimately characterize the mean color of a
728% set of pixels represented by this node.
729%
730% E: the distance squared in RGB space between each pixel contained
731% within a node and the nodes' center. This represents the quantization
732% error for a node.
733%
734% The format of the ClassifyImageColors() method is:
735%
736% MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
737% const Image *image,ExceptionInfo *exception)
738%
739% A description of each parameter follows.
740%
741% o cube_info: A pointer to the Cube structure.
742%
743% o image: the image.
744%
745*/
746
747static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
748{
749 MagickBooleanType
750 associate_alpha;
751
752 associate_alpha=image->matte;
753 if (cube_info->quantize_info->colorspace == TransparentColorspace)
754 associate_alpha=MagickFalse;
755 if ((cube_info->quantize_info->number_colors == 2) &&
756 (cube_info->quantize_info->colorspace == GRAYColorspace))
757 associate_alpha=MagickFalse;
758 cube_info->associate_alpha=associate_alpha;
759}
760
761static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
762 const Image *image,ExceptionInfo *exception)
763{
764#define ClassifyImageTag "Classify/Image"
765
cristyc4c8d132010-01-07 01:58:38 +0000766 CacheView
767 *image_view;
768
cristy3ed852e2009-09-05 21:47:34 +0000769 MagickBooleanType
770 proceed;
771
772 MagickRealType
773 bisect;
774
775 NodeInfo
776 *node_info;
777
778 RealPixelPacket
779 error,
780 mid,
781 midpoint,
782 pixel;
783
784 size_t
cristyecc31b12011-02-13 00:32:29 +0000785 count,
cristy3ed852e2009-09-05 21:47:34 +0000786 id,
787 index,
788 level;
789
cristyecc31b12011-02-13 00:32:29 +0000790 ssize_t
791 y;
792
cristy3ed852e2009-09-05 21:47:34 +0000793 /*
794 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
795 */
796 SetAssociatedAlpha(image,cube_info);
797 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
798 (cube_info->quantize_info->colorspace != CMYKColorspace))
799 (void) TransformImageColorspace((Image *) image,
800 cube_info->quantize_info->colorspace);
801 else
802 if ((image->colorspace != GRAYColorspace) &&
803 (image->colorspace != CMYColorspace) &&
cristy510d06a2011-07-06 23:43:54 +0000804 (IsRGBColorspace(image->colorspace) == MagickFalse))
cristy3ed852e2009-09-05 21:47:34 +0000805 (void) TransformImageColorspace((Image *) image,RGBColorspace);
806 midpoint.red=(MagickRealType) QuantumRange/2.0;
807 midpoint.green=(MagickRealType) QuantumRange/2.0;
808 midpoint.blue=(MagickRealType) QuantumRange/2.0;
cristy4c08aed2011-07-01 19:47:50 +0000809 midpoint.alpha=(MagickRealType) QuantumRange/2.0;
810 error.alpha=0.0;
cristy3ed852e2009-09-05 21:47:34 +0000811 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +0000812 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000813 {
cristy4c08aed2011-07-01 19:47:50 +0000814 register const Quantum
cristyc47d1f82009-11-26 01:44:43 +0000815 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000816
cristybb503372010-05-27 20:51:26 +0000817 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000818 x;
819
820 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
cristy4c08aed2011-07-01 19:47:50 +0000821 if (p == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +0000822 break;
823 if (cube_info->nodes > MaxNodes)
824 {
825 /*
826 Prune one level if the color tree is too large.
827 */
828 PruneLevel(image,cube_info,cube_info->root);
829 cube_info->depth--;
830 }
cristybb503372010-05-27 20:51:26 +0000831 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
cristy3ed852e2009-09-05 21:47:34 +0000832 {
833 /*
834 Start at the root and descend the color cube tree.
835 */
cristybb66d9c2010-10-09 01:40:31 +0000836 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
cristy4c08aed2011-07-01 19:47:50 +0000837 {
838 PixelPacket
839 packet;
840
cristydcfc1ad2011-07-07 16:25:41 +0000841 GetPixelPacket(image,p+count*GetPixelComponents(image),&packet);
cristy4c08aed2011-07-01 19:47:50 +0000842 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +0000843 break;
cristy4c08aed2011-07-01 19:47:50 +0000844 }
845 AssociateAlphaPixel(image,cube_info,p,&pixel);
cristy3ed852e2009-09-05 21:47:34 +0000846 index=MaxTreeDepth-1;
847 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
848 mid=midpoint;
849 node_info=cube_info->root;
850 for (level=1; level <= MaxTreeDepth; level++)
851 {
852 bisect*=0.5;
853 id=ColorToNodeId(cube_info,&pixel,index);
854 mid.red+=(id & 1) != 0 ? bisect : -bisect;
855 mid.green+=(id & 2) != 0 ? bisect : -bisect;
856 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
cristy4c08aed2011-07-01 19:47:50 +0000857 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
cristy3ed852e2009-09-05 21:47:34 +0000858 if (node_info->child[id] == (NodeInfo *) NULL)
859 {
860 /*
861 Set colors of new node to contain pixel.
862 */
863 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
864 if (node_info->child[id] == (NodeInfo *) NULL)
865 (void) ThrowMagickException(exception,GetMagickModule(),
866 ResourceLimitError,"MemoryAllocationFailed","`%s'",
867 image->filename);
868 if (level == MaxTreeDepth)
869 cube_info->colors++;
870 }
871 /*
872 Approximate the quantization error represented by this node.
873 */
874 node_info=node_info->child[id];
875 error.red=QuantumScale*(pixel.red-mid.red);
876 error.green=QuantumScale*(pixel.green-mid.green);
877 error.blue=QuantumScale*(pixel.blue-mid.blue);
878 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +0000879 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
cristy3ed852e2009-09-05 21:47:34 +0000880 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
881 count*error.green*error.green+count*error.blue*error.blue+
cristy4c08aed2011-07-01 19:47:50 +0000882 count*error.alpha*error.alpha));
cristy3ed852e2009-09-05 21:47:34 +0000883 cube_info->root->quantize_error+=node_info->quantize_error;
884 index--;
885 }
886 /*
887 Sum RGB for this leaf for later derivation of the mean cube color.
888 */
889 node_info->number_unique+=count;
890 node_info->total_color.red+=count*QuantumScale*pixel.red;
891 node_info->total_color.green+=count*QuantumScale*pixel.green;
892 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
893 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +0000894 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
cristydcfc1ad2011-07-07 16:25:41 +0000895 p+=count*GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +0000896 }
897 if (cube_info->colors > cube_info->maximum_colors)
898 {
899 PruneToCubeDepth(image,cube_info,cube_info->root);
900 break;
901 }
cristycee97112010-05-28 00:44:52 +0000902 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
903 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000904 if (proceed == MagickFalse)
905 break;
906 }
cristybb503372010-05-27 20:51:26 +0000907 for (y++; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000908 {
cristy4c08aed2011-07-01 19:47:50 +0000909 register const Quantum
cristyc47d1f82009-11-26 01:44:43 +0000910 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000911
cristybb503372010-05-27 20:51:26 +0000912 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000913 x;
914
915 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
cristy4c08aed2011-07-01 19:47:50 +0000916 if (p == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +0000917 break;
918 if (cube_info->nodes > MaxNodes)
919 {
920 /*
921 Prune one level if the color tree is too large.
922 */
923 PruneLevel(image,cube_info,cube_info->root);
924 cube_info->depth--;
925 }
cristybb503372010-05-27 20:51:26 +0000926 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
cristy3ed852e2009-09-05 21:47:34 +0000927 {
928 /*
929 Start at the root and descend the color cube tree.
930 */
cristybb66d9c2010-10-09 01:40:31 +0000931 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
cristy4c08aed2011-07-01 19:47:50 +0000932 {
933 PixelPacket
934 packet;
935
cristydcfc1ad2011-07-07 16:25:41 +0000936 GetPixelPacket(image,p+count*GetPixelComponents(image),&packet);
cristy4c08aed2011-07-01 19:47:50 +0000937 if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +0000938 break;
cristy4c08aed2011-07-01 19:47:50 +0000939 }
940 AssociateAlphaPixel(image,cube_info,p,&pixel);
cristy3ed852e2009-09-05 21:47:34 +0000941 index=MaxTreeDepth-1;
942 bisect=((MagickRealType) 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 bisect*=0.5;
948 id=ColorToNodeId(cube_info,&pixel,index);
949 mid.red+=(id & 1) != 0 ? bisect : -bisect;
950 mid.green+=(id & 2) != 0 ? bisect : -bisect;
951 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
cristy4c08aed2011-07-01 19:47:50 +0000952 mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
cristy3ed852e2009-09-05 21:47:34 +0000953 if (node_info->child[id] == (NodeInfo *) NULL)
954 {
955 /*
956 Set colors of new node to contain pixel.
957 */
958 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
959 if (node_info->child[id] == (NodeInfo *) NULL)
960 (void) ThrowMagickException(exception,GetMagickModule(),
961 ResourceLimitError,"MemoryAllocationFailed","%s",
962 image->filename);
963 if (level == cube_info->depth)
964 cube_info->colors++;
965 }
966 /*
967 Approximate the quantization error represented by this node.
968 */
969 node_info=node_info->child[id];
970 error.red=QuantumScale*(pixel.red-mid.red);
971 error.green=QuantumScale*(pixel.green-mid.green);
972 error.blue=QuantumScale*(pixel.blue-mid.blue);
973 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +0000974 error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
cristy3ed852e2009-09-05 21:47:34 +0000975 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
cristy83b6e792011-01-26 15:46:06 +0000976 count*error.green*error.green+count*error.blue*error.blue+
cristy4c08aed2011-07-01 19:47:50 +0000977 count*error.alpha*error.alpha));
cristy3ed852e2009-09-05 21:47:34 +0000978 cube_info->root->quantize_error+=node_info->quantize_error;
979 index--;
980 }
981 /*
982 Sum RGB for this leaf for later derivation of the mean cube color.
983 */
984 node_info->number_unique+=count;
985 node_info->total_color.red+=count*QuantumScale*pixel.red;
986 node_info->total_color.green+=count*QuantumScale*pixel.green;
987 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
988 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +0000989 node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
cristydcfc1ad2011-07-07 16:25:41 +0000990 p+=count*GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +0000991 }
cristycee97112010-05-28 00:44:52 +0000992 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
993 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000994 if (proceed == MagickFalse)
995 break;
996 }
997 image_view=DestroyCacheView(image_view);
998 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
999 (cube_info->quantize_info->colorspace != CMYKColorspace))
1000 (void) TransformImageColorspace((Image *) image,RGBColorspace);
1001 return(MagickTrue);
1002}
1003
1004/*
1005%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1006% %
1007% %
1008% %
1009% C l o n e Q u a n t i z e I n f o %
1010% %
1011% %
1012% %
1013%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1014%
1015% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
1016% or if quantize info is NULL, a new one.
1017%
1018% The format of the CloneQuantizeInfo method is:
1019%
1020% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1021%
1022% A description of each parameter follows:
1023%
1024% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
1025% quantize info, or if image info is NULL a new one.
1026%
1027% o quantize_info: a structure of type info.
1028%
1029*/
1030MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1031{
1032 QuantizeInfo
1033 *clone_info;
1034
cristy73bd4a52010-10-05 11:24:23 +00001035 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
cristy3ed852e2009-09-05 21:47:34 +00001036 if (clone_info == (QuantizeInfo *) NULL)
1037 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1038 GetQuantizeInfo(clone_info);
1039 if (quantize_info == (QuantizeInfo *) NULL)
1040 return(clone_info);
1041 clone_info->number_colors=quantize_info->number_colors;
1042 clone_info->tree_depth=quantize_info->tree_depth;
1043 clone_info->dither=quantize_info->dither;
1044 clone_info->dither_method=quantize_info->dither_method;
1045 clone_info->colorspace=quantize_info->colorspace;
1046 clone_info->measure_error=quantize_info->measure_error;
1047 return(clone_info);
1048}
1049
1050/*
1051%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1052% %
1053% %
1054% %
1055+ C l o s e s t C o l o r %
1056% %
1057% %
1058% %
1059%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1060%
1061% ClosestColor() traverses the color cube tree at a particular node and
1062% determines which colormap entry best represents the input color.
1063%
1064% The format of the ClosestColor method is:
1065%
1066% void ClosestColor(const Image *image,CubeInfo *cube_info,
1067% const NodeInfo *node_info)
1068%
1069% A description of each parameter follows.
1070%
1071% o image: the image.
1072%
1073% o cube_info: A pointer to the Cube structure.
1074%
1075% o node_info: the address of a structure of type NodeInfo which points to a
1076% node in the color cube tree that is to be pruned.
1077%
1078*/
1079static void ClosestColor(const Image *image,CubeInfo *cube_info,
1080 const NodeInfo *node_info)
1081{
cristybb503372010-05-27 20:51:26 +00001082 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001083 i;
1084
cristybb503372010-05-27 20:51:26 +00001085 size_t
cristy3ed852e2009-09-05 21:47:34 +00001086 number_children;
1087
1088 /*
1089 Traverse any children.
1090 */
1091 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00001092 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00001093 if (node_info->child[i] != (NodeInfo *) NULL)
1094 ClosestColor(image,cube_info,node_info->child[i]);
1095 if (node_info->number_unique != 0)
1096 {
1097 MagickRealType
1098 pixel;
1099
1100 register MagickRealType
1101 alpha,
1102 beta,
1103 distance;
1104
1105 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001106 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00001107
1108 register RealPixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001109 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001110
1111 /*
1112 Determine if this color is "closest".
1113 */
1114 p=image->colormap+node_info->color_number;
1115 q=(&cube_info->target);
1116 alpha=1.0;
1117 beta=1.0;
cristy847620f2011-02-09 02:24:21 +00001118 if (cube_info->associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001119 {
cristy4c08aed2011-07-01 19:47:50 +00001120 alpha=(MagickRealType) (QuantumScale*p->alpha);
1121 beta=(MagickRealType) (QuantumScale*q->alpha);
cristy3ed852e2009-09-05 21:47:34 +00001122 }
cristy4c08aed2011-07-01 19:47:50 +00001123 pixel=alpha*p->red-beta*q->red;
cristy3ed852e2009-09-05 21:47:34 +00001124 distance=pixel*pixel;
cristy36fbc3b2011-02-09 02:30:04 +00001125 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001126 {
cristy4c08aed2011-07-01 19:47:50 +00001127 pixel=alpha*p->green-beta*q->green;
cristy3ed852e2009-09-05 21:47:34 +00001128 distance+=pixel*pixel;
cristy36fbc3b2011-02-09 02:30:04 +00001129 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001130 {
cristy4c08aed2011-07-01 19:47:50 +00001131 pixel=alpha*p->blue-beta*q->blue;
cristy3ed852e2009-09-05 21:47:34 +00001132 distance+=pixel*pixel;
cristy36fbc3b2011-02-09 02:30:04 +00001133 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001134 {
1135 pixel=alpha-beta;
1136 distance+=pixel*pixel;
cristyc4080402011-02-09 02:55:58 +00001137 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001138 {
1139 cube_info->distance=distance;
1140 cube_info->color_number=node_info->color_number;
1141 }
1142 }
1143 }
1144 }
1145 }
1146}
1147
1148/*
1149%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1150% %
1151% %
1152% %
1153% C o m p r e s s I m a g e C o l o r m a p %
1154% %
1155% %
1156% %
1157%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1158%
1159% CompressImageColormap() compresses an image colormap by removing any
1160% duplicate or unused color entries.
1161%
1162% The format of the CompressImageColormap method is:
1163%
1164% MagickBooleanType CompressImageColormap(Image *image)
1165%
1166% A description of each parameter follows:
1167%
1168% o image: the image.
1169%
1170*/
1171MagickExport MagickBooleanType CompressImageColormap(Image *image)
1172{
1173 QuantizeInfo
1174 quantize_info;
1175
1176 assert(image != (Image *) NULL);
1177 assert(image->signature == MagickSignature);
1178 if (image->debug != MagickFalse)
1179 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1180 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1181 return(MagickFalse);
1182 GetQuantizeInfo(&quantize_info);
1183 quantize_info.number_colors=image->colors;
1184 quantize_info.tree_depth=MaxTreeDepth;
1185 return(QuantizeImage(&quantize_info,image));
1186}
1187
1188/*
1189%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1190% %
1191% %
1192% %
1193+ D e f i n e I m a g e C o l o r m a p %
1194% %
1195% %
1196% %
1197%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1198%
1199% DefineImageColormap() traverses the color cube tree and notes each colormap
1200% entry. A colormap entry is any node in the color cube tree where the
1201% of unique colors is not zero. DefineImageColormap() returns the number of
1202% colors in the image colormap.
1203%
1204% The format of the DefineImageColormap method is:
1205%
cristybb503372010-05-27 20:51:26 +00001206% size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
cristy3ed852e2009-09-05 21:47:34 +00001207% NodeInfo *node_info)
1208%
1209% A description of each parameter follows.
1210%
1211% o image: the image.
1212%
1213% o cube_info: A pointer to the Cube structure.
1214%
1215% o node_info: the address of a structure of type NodeInfo which points to a
1216% node in the color cube tree that is to be pruned.
1217%
1218*/
cristybb503372010-05-27 20:51:26 +00001219static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
cristy3ed852e2009-09-05 21:47:34 +00001220 NodeInfo *node_info)
1221{
cristybb503372010-05-27 20:51:26 +00001222 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001223 i;
1224
cristybb503372010-05-27 20:51:26 +00001225 size_t
cristy3ed852e2009-09-05 21:47:34 +00001226 number_children;
1227
1228 /*
1229 Traverse any children.
1230 */
1231 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00001232 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00001233 if (node_info->child[i] != (NodeInfo *) NULL)
cristycee97112010-05-28 00:44:52 +00001234 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
cristy3ed852e2009-09-05 21:47:34 +00001235 if (node_info->number_unique != 0)
1236 {
1237 register MagickRealType
1238 alpha;
1239
1240 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001241 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001242
1243 /*
1244 Colormap entry is defined by the mean color in this cube.
1245 */
1246 q=image->colormap+image->colors;
1247 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1248 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1249 if (cube_info->associate_alpha == MagickFalse)
1250 {
cristy4c08aed2011-07-01 19:47:50 +00001251 q->red=ClampToQuantum((MagickRealType)
1252 (alpha*QuantumRange*node_info->total_color.red));
1253 q->green=ClampToQuantum((MagickRealType)
1254 (alpha*QuantumRange*node_info->total_color.green));
1255 q->blue=ClampToQuantum((MagickRealType)
1256 (alpha*QuantumRange*node_info->total_color.blue));
1257 q->alpha=OpaqueAlpha;
cristy3ed852e2009-09-05 21:47:34 +00001258 }
1259 else
1260 {
1261 MagickRealType
1262 opacity;
1263
1264 opacity=(MagickRealType) (alpha*QuantumRange*
cristy4c08aed2011-07-01 19:47:50 +00001265 node_info->total_color.alpha);
1266 q->alpha=ClampToQuantum(opacity);
1267 if (q->alpha == OpaqueAlpha)
cristy3ed852e2009-09-05 21:47:34 +00001268 {
cristy4c08aed2011-07-01 19:47:50 +00001269 q->red=ClampToQuantum((MagickRealType)
1270 (alpha*QuantumRange*node_info->total_color.red));
1271 q->green=ClampToQuantum((MagickRealType)
1272 (alpha*QuantumRange*node_info->total_color.green));
1273 q->blue=ClampToQuantum((MagickRealType)
1274 (alpha*QuantumRange*node_info->total_color.blue));
cristy3ed852e2009-09-05 21:47:34 +00001275 }
1276 else
1277 {
1278 MagickRealType
1279 gamma;
1280
cristy4c08aed2011-07-01 19:47:50 +00001281 gamma=(MagickRealType) (QuantumScale*q->alpha);
cristy3ed852e2009-09-05 21:47:34 +00001282 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
cristy4c08aed2011-07-01 19:47:50 +00001283 q->red=ClampToQuantum((MagickRealType)
1284 (alpha*gamma*QuantumRange*node_info->total_color.red));
1285 q->green=ClampToQuantum((MagickRealType)
1286 (alpha*gamma*QuantumRange*node_info->total_color.green));
1287 q->blue=ClampToQuantum((MagickRealType)
1288 (alpha*gamma*QuantumRange*node_info->total_color.blue));
cristy3ed852e2009-09-05 21:47:34 +00001289 if (node_info->number_unique > cube_info->transparent_pixels)
1290 {
1291 cube_info->transparent_pixels=node_info->number_unique;
cristybb503372010-05-27 20:51:26 +00001292 cube_info->transparent_index=(ssize_t) image->colors;
cristy3ed852e2009-09-05 21:47:34 +00001293 }
1294 }
1295 }
1296 node_info->color_number=image->colors++;
1297 }
1298 return(image->colors);
1299}
1300
1301/*
1302%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1303% %
1304% %
1305% %
1306+ D e s t r o y C u b e I n f o %
1307% %
1308% %
1309% %
1310%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1311%
1312% DestroyCubeInfo() deallocates memory associated with an image.
1313%
1314% The format of the DestroyCubeInfo method is:
1315%
1316% DestroyCubeInfo(CubeInfo *cube_info)
1317%
1318% A description of each parameter follows:
1319%
1320% o cube_info: the address of a structure of type CubeInfo.
1321%
1322*/
1323static void DestroyCubeInfo(CubeInfo *cube_info)
1324{
1325 register Nodes
1326 *nodes;
1327
1328 /*
1329 Release color cube tree storage.
1330 */
1331 do
1332 {
1333 nodes=cube_info->node_queue->next;
1334 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1335 cube_info->node_queue->nodes);
1336 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1337 cube_info->node_queue);
1338 cube_info->node_queue=nodes;
1339 } while (cube_info->node_queue != (Nodes *) NULL);
cristybb503372010-05-27 20:51:26 +00001340 if (cube_info->cache != (ssize_t *) NULL)
1341 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
cristy3ed852e2009-09-05 21:47:34 +00001342 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1343 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1344}
1345
1346/*
1347%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1348% %
1349% %
1350% %
1351% D e s t r o y Q u a n t i z e I n f o %
1352% %
1353% %
1354% %
1355%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1356%
1357% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1358% structure.
1359%
1360% The format of the DestroyQuantizeInfo method is:
1361%
1362% QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1363%
1364% A description of each parameter follows:
1365%
1366% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1367%
1368*/
1369MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1370{
1371 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1372 assert(quantize_info != (QuantizeInfo *) NULL);
1373 assert(quantize_info->signature == MagickSignature);
1374 quantize_info->signature=(~MagickSignature);
1375 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1376 return(quantize_info);
1377}
1378
1379/*
1380%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1381% %
1382% %
1383% %
1384+ D i t h e r I m a g e %
1385% %
1386% %
1387% %
1388%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1389%
1390% DitherImage() distributes the difference between an original image and
1391% the corresponding color reduced algorithm to neighboring pixels using
1392% serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1393% MagickTrue if the image is dithered otherwise MagickFalse.
1394%
1395% The format of the DitherImage method is:
1396%
1397% MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1398%
1399% A description of each parameter follows.
1400%
1401% o image: the image.
1402%
1403% o cube_info: A pointer to the Cube structure.
1404%
1405*/
1406
cristye9717ac2011-02-20 16:17:17 +00001407static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1408{
1409 register ssize_t
1410 i;
1411
1412 assert(pixels != (RealPixelPacket **) NULL);
1413 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1414 if (pixels[i] != (RealPixelPacket *) NULL)
1415 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1416 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1417 return(pixels);
1418}
1419
1420static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1421{
1422 RealPixelPacket
1423 **pixels;
1424
1425 register ssize_t
1426 i;
1427
1428 size_t
1429 number_threads;
1430
1431 number_threads=GetOpenMPMaximumThreads();
1432 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1433 sizeof(*pixels));
1434 if (pixels == (RealPixelPacket **) NULL)
1435 return((RealPixelPacket **) NULL);
1436 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1437 for (i=0; i < (ssize_t) number_threads; i++)
1438 {
1439 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1440 2*sizeof(**pixels));
1441 if (pixels[i] == (RealPixelPacket *) NULL)
1442 return(DestroyPixelThreadSet(pixels));
1443 }
1444 return(pixels);
1445}
1446
cristyca972de2010-06-20 23:37:02 +00001447static inline ssize_t CacheOffset(CubeInfo *cube_info,
1448 const RealPixelPacket *pixel)
1449{
1450#define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1451#define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1452#define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1453#define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1454
1455 ssize_t
1456 offset;
1457
1458 offset=(ssize_t)
cristy15893a42010-11-20 18:57:15 +00001459 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
cristyca972de2010-06-20 23:37:02 +00001460 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
cristy15893a42010-11-20 18:57:15 +00001461 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
cristyca972de2010-06-20 23:37:02 +00001462 if (cube_info->associate_alpha != MagickFalse)
cristy15893a42010-11-20 18:57:15 +00001463 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
cristy4c08aed2011-07-01 19:47:50 +00001464 pixel->alpha)));
cristyca972de2010-06-20 23:37:02 +00001465 return(offset);
1466}
1467
cristy3ed852e2009-09-05 21:47:34 +00001468static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1469{
1470#define DitherImageTag "Dither/Image"
1471
cristyc4c8d132010-01-07 01:58:38 +00001472 CacheView
1473 *image_view;
1474
cristy3ed852e2009-09-05 21:47:34 +00001475 ExceptionInfo
1476 *exception;
1477
cristy3ed852e2009-09-05 21:47:34 +00001478 MagickBooleanType
cristye9717ac2011-02-20 16:17:17 +00001479 status;
cristy3ed852e2009-09-05 21:47:34 +00001480
1481 RealPixelPacket
cristye9717ac2011-02-20 16:17:17 +00001482 **pixels;
cristy3ed852e2009-09-05 21:47:34 +00001483
cristy847620f2011-02-09 02:24:21 +00001484 ssize_t
cristy847620f2011-02-09 02:24:21 +00001485 y;
1486
cristy3ed852e2009-09-05 21:47:34 +00001487 /*
1488 Distribute quantization error using Floyd-Steinberg.
1489 */
cristye9717ac2011-02-20 16:17:17 +00001490 pixels=AcquirePixelThreadSet(image->columns);
1491 if (pixels == (RealPixelPacket **) NULL)
cristy3ed852e2009-09-05 21:47:34 +00001492 return(MagickFalse);
cristy3ed852e2009-09-05 21:47:34 +00001493 exception=(&image->exception);
cristye9717ac2011-02-20 16:17:17 +00001494 status=MagickTrue;
cristy3ed852e2009-09-05 21:47:34 +00001495 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +00001496 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00001497 {
cristye9717ac2011-02-20 16:17:17 +00001498 const int
1499 id = GetOpenMPThreadId();
1500
1501 CubeInfo
1502 cube;
1503
1504 RealPixelPacket
1505 *current,
1506 *previous;
1507
cristy4c08aed2011-07-01 19:47:50 +00001508 register Quantum
cristyecc31b12011-02-13 00:32:29 +00001509 *restrict q;
1510
cristybb503372010-05-27 20:51:26 +00001511 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001512 x;
1513
cristye9717ac2011-02-20 16:17:17 +00001514 size_t
1515 index;
1516
1517 ssize_t
1518 v;
1519
1520 if (status == MagickFalse)
1521 continue;
cristy3ed852e2009-09-05 21:47:34 +00001522 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
cristy4c08aed2011-07-01 19:47:50 +00001523 if (q == (const Quantum *) NULL)
cristye9717ac2011-02-20 16:17:17 +00001524 {
1525 status=MagickFalse;
cristy00cbdd62011-02-20 17:29:26 +00001526 continue;
cristye9717ac2011-02-20 16:17:17 +00001527 }
cristydcfc1ad2011-07-07 16:25:41 +00001528 q+=(y & 0x01)*image->columns*GetPixelComponents(image);
cristye9717ac2011-02-20 16:17:17 +00001529 cube=(*cube_info);
1530 current=pixels[id]+(y & 0x01)*image->columns;
1531 previous=pixels[id]+((y+1) & 0x01)*image->columns;
cristy4c08aed2011-07-01 19:47:50 +00001532 v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
cristybb503372010-05-27 20:51:26 +00001533 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00001534 {
cristye9717ac2011-02-20 16:17:17 +00001535 RealPixelPacket
1536 color,
1537 pixel;
1538
1539 register ssize_t
1540 i;
1541
1542 ssize_t
1543 u;
1544
cristydcfc1ad2011-07-07 16:25:41 +00001545 q-=(y & 0x01)*GetPixelComponents(image);
cristy4c08aed2011-07-01 19:47:50 +00001546 u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
1547 AssociateAlphaPixel(image,&cube,q,&pixel);
cristy3ed852e2009-09-05 21:47:34 +00001548 if (x > 0)
1549 {
1550 pixel.red+=7*current[u-v].red/16;
1551 pixel.green+=7*current[u-v].green/16;
1552 pixel.blue+=7*current[u-v].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001553 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001554 pixel.alpha+=7*current[u-v].alpha/16;
cristy3ed852e2009-09-05 21:47:34 +00001555 }
1556 if (y > 0)
1557 {
cristybb503372010-05-27 20:51:26 +00001558 if (x < (ssize_t) (image->columns-1))
cristy3ed852e2009-09-05 21:47:34 +00001559 {
1560 pixel.red+=previous[u+v].red/16;
1561 pixel.green+=previous[u+v].green/16;
1562 pixel.blue+=previous[u+v].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001563 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001564 pixel.alpha+=previous[u+v].alpha/16;
cristy3ed852e2009-09-05 21:47:34 +00001565 }
1566 pixel.red+=5*previous[u].red/16;
1567 pixel.green+=5*previous[u].green/16;
1568 pixel.blue+=5*previous[u].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001569 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001570 pixel.alpha+=5*previous[u].alpha/16;
cristy3ed852e2009-09-05 21:47:34 +00001571 if (x > 0)
1572 {
1573 pixel.red+=3*previous[u-v].red/16;
1574 pixel.green+=3*previous[u-v].green/16;
1575 pixel.blue+=3*previous[u-v].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001576 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001577 pixel.alpha+=3*previous[u-v].alpha/16;
cristy3ed852e2009-09-05 21:47:34 +00001578 }
1579 }
cristy75ffdb72010-01-07 17:40:12 +00001580 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1581 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1582 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristye9717ac2011-02-20 16:17:17 +00001583 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001584 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
cristye9717ac2011-02-20 16:17:17 +00001585 i=CacheOffset(&cube,&pixel);
1586 if (cube.cache[i] < 0)
cristy3ed852e2009-09-05 21:47:34 +00001587 {
1588 register NodeInfo
1589 *node_info;
1590
cristybb503372010-05-27 20:51:26 +00001591 register size_t
cristy3ed852e2009-09-05 21:47:34 +00001592 id;
1593
1594 /*
1595 Identify the deepest node containing the pixel's color.
1596 */
cristye9717ac2011-02-20 16:17:17 +00001597 node_info=cube.root;
cristybb503372010-05-27 20:51:26 +00001598 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +00001599 {
cristye9717ac2011-02-20 16:17:17 +00001600 id=ColorToNodeId(&cube,&pixel,index);
cristy3ed852e2009-09-05 21:47:34 +00001601 if (node_info->child[id] == (NodeInfo *) NULL)
1602 break;
1603 node_info=node_info->child[id];
1604 }
1605 /*
1606 Find closest color among siblings and their children.
1607 */
cristye9717ac2011-02-20 16:17:17 +00001608 cube.target=pixel;
1609 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
cristy3ed852e2009-09-05 21:47:34 +00001610 1.0)+1.0);
cristye9717ac2011-02-20 16:17:17 +00001611 ClosestColor(image,&cube,node_info->parent);
1612 cube.cache[i]=(ssize_t) cube.color_number;
cristy3ed852e2009-09-05 21:47:34 +00001613 }
1614 /*
1615 Assign pixel to closest colormap entry.
1616 */
cristye9717ac2011-02-20 16:17:17 +00001617 index=(size_t) cube.cache[i];
cristy3ed852e2009-09-05 21:47:34 +00001618 if (image->storage_class == PseudoClass)
cristy4c08aed2011-07-01 19:47:50 +00001619 SetPixelIndex(image,(Quantum) index,q);
cristye9717ac2011-02-20 16:17:17 +00001620 if (cube.quantize_info->measure_error == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001621 {
cristy4c08aed2011-07-01 19:47:50 +00001622 SetPixelRed(image,image->colormap[index].red,q);
1623 SetPixelGreen(image,image->colormap[index].green,q);
1624 SetPixelBlue(image,image->colormap[index].blue,q);
cristye9717ac2011-02-20 16:17:17 +00001625 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001626 SetPixelAlpha(image,image->colormap[index].alpha,q);
cristy3ed852e2009-09-05 21:47:34 +00001627 }
1628 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
cristye9717ac2011-02-20 16:17:17 +00001629 status=MagickFalse;
cristy3ed852e2009-09-05 21:47:34 +00001630 /*
1631 Store the error.
1632 */
cristy4c08aed2011-07-01 19:47:50 +00001633 AssociateAlphaPixelPacket(image,&cube,image->colormap+index,&color);
cristy3ed852e2009-09-05 21:47:34 +00001634 current[u].red=pixel.red-color.red;
1635 current[u].green=pixel.green-color.green;
1636 current[u].blue=pixel.blue-color.blue;
cristye9717ac2011-02-20 16:17:17 +00001637 if (cube.associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001638 current[u].alpha=pixel.alpha-color.alpha;
cristye9717ac2011-02-20 16:17:17 +00001639 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1640 {
1641 MagickBooleanType
1642 proceed;
1643
1644#if defined(MAGICKCORE_OPENMP_SUPPORT)
1645 #pragma omp critical (MagickCore_FloydSteinbergDither)
1646#endif
1647 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1648 image->rows);
1649 if (proceed == MagickFalse)
1650 status=MagickFalse;
1651 }
cristydcfc1ad2011-07-07 16:25:41 +00001652 q+=((y+1) & 0x01)*GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +00001653 }
1654 }
cristy3ed852e2009-09-05 21:47:34 +00001655 image_view=DestroyCacheView(image_view);
cristye9717ac2011-02-20 16:17:17 +00001656 pixels=DestroyPixelThreadSet(pixels);
cristy3ed852e2009-09-05 21:47:34 +00001657 return(MagickTrue);
1658}
1659
1660static MagickBooleanType
1661 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1662
1663static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
cristybb503372010-05-27 20:51:26 +00001664 const size_t level,const unsigned int direction)
cristy3ed852e2009-09-05 21:47:34 +00001665{
1666 if (level == 1)
1667 switch (direction)
1668 {
1669 case WestGravity:
1670 {
1671 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1672 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1673 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1674 break;
1675 }
1676 case EastGravity:
1677 {
1678 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1679 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1680 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1681 break;
1682 }
1683 case NorthGravity:
1684 {
1685 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1686 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1687 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1688 break;
1689 }
1690 case SouthGravity:
1691 {
1692 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1693 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1694 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1695 break;
1696 }
1697 default:
1698 break;
1699 }
1700 else
1701 switch (direction)
1702 {
1703 case WestGravity:
1704 {
1705 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1707 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1708 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1709 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1710 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1711 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1712 break;
1713 }
1714 case EastGravity:
1715 {
1716 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1717 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1718 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1719 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1720 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1721 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1722 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1723 break;
1724 }
1725 case NorthGravity:
1726 {
1727 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1728 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1729 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1730 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1731 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1732 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1733 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1734 break;
1735 }
1736 case SouthGravity:
1737 {
1738 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1739 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1740 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1741 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1742 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1743 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1744 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1745 break;
1746 }
1747 default:
1748 break;
1749 }
1750}
1751
1752static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1753 CubeInfo *cube_info,const unsigned int direction)
1754{
1755#define DitherImageTag "Dither/Image"
1756
1757 MagickBooleanType
1758 proceed;
1759
1760 RealPixelPacket
1761 color,
1762 pixel;
1763
1764 register CubeInfo
1765 *p;
1766
cristybb503372010-05-27 20:51:26 +00001767 size_t
cristy3ed852e2009-09-05 21:47:34 +00001768 index;
1769
1770 p=cube_info;
cristybb503372010-05-27 20:51:26 +00001771 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1772 (p->y >= 0) && (p->y < (ssize_t) image->rows))
cristy3ed852e2009-09-05 21:47:34 +00001773 {
1774 ExceptionInfo
1775 *exception;
1776
cristy4c08aed2011-07-01 19:47:50 +00001777 register Quantum
cristyc47d1f82009-11-26 01:44:43 +00001778 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001779
cristyecc31b12011-02-13 00:32:29 +00001780 register ssize_t
1781 i;
1782
cristy3ed852e2009-09-05 21:47:34 +00001783 /*
1784 Distribute error.
1785 */
1786 exception=(&image->exception);
1787 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
cristy4c08aed2011-07-01 19:47:50 +00001788 if (q == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00001789 return(MagickFalse);
cristy4c08aed2011-07-01 19:47:50 +00001790 AssociateAlphaPixel(image,cube_info,q,&pixel);
cristy3ed852e2009-09-05 21:47:34 +00001791 for (i=0; i < ErrorQueueLength; i++)
1792 {
1793 pixel.red+=p->weights[i]*p->error[i].red;
1794 pixel.green+=p->weights[i]*p->error[i].green;
1795 pixel.blue+=p->weights[i]*p->error[i].blue;
1796 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001797 pixel.alpha+=p->weights[i]*p->error[i].alpha;
cristy3ed852e2009-09-05 21:47:34 +00001798 }
cristy75ffdb72010-01-07 17:40:12 +00001799 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1800 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1801 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristy3ed852e2009-09-05 21:47:34 +00001802 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001803 pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
cristyca972de2010-06-20 23:37:02 +00001804 i=CacheOffset(cube_info,&pixel);
cristy3ed852e2009-09-05 21:47:34 +00001805 if (p->cache[i] < 0)
1806 {
1807 register NodeInfo
1808 *node_info;
1809
cristybb503372010-05-27 20:51:26 +00001810 register size_t
cristy3ed852e2009-09-05 21:47:34 +00001811 id;
1812
1813 /*
1814 Identify the deepest node containing the pixel's color.
1815 */
1816 node_info=p->root;
cristybb503372010-05-27 20:51:26 +00001817 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +00001818 {
1819 id=ColorToNodeId(cube_info,&pixel,index);
1820 if (node_info->child[id] == (NodeInfo *) NULL)
1821 break;
1822 node_info=node_info->child[id];
1823 }
cristyecc31b12011-02-13 00:32:29 +00001824 node_info=node_info->parent;
cristy3ed852e2009-09-05 21:47:34 +00001825 /*
1826 Find closest color among siblings and their children.
1827 */
1828 p->target=pixel;
1829 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1830 QuantumRange+1.0)+1.0);
1831 ClosestColor(image,p,node_info->parent);
cristybb503372010-05-27 20:51:26 +00001832 p->cache[i]=(ssize_t) p->color_number;
cristy3ed852e2009-09-05 21:47:34 +00001833 }
1834 /*
1835 Assign pixel to closest colormap entry.
1836 */
cristy4c08aed2011-07-01 19:47:50 +00001837 index=(size_t) p->cache[i];
cristy3ed852e2009-09-05 21:47:34 +00001838 if (image->storage_class == PseudoClass)
cristy4c08aed2011-07-01 19:47:50 +00001839 SetPixelIndex(image,(Quantum) index,q);
cristy3ed852e2009-09-05 21:47:34 +00001840 if (cube_info->quantize_info->measure_error == MagickFalse)
1841 {
cristy4c08aed2011-07-01 19:47:50 +00001842 SetPixelRed(image,image->colormap[index].red,q);
1843 SetPixelGreen(image,image->colormap[index].green,q);
1844 SetPixelBlue(image,image->colormap[index].blue,q);
cristy3ed852e2009-09-05 21:47:34 +00001845 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001846 SetPixelAlpha(image,image->colormap[index].alpha,q);
cristy3ed852e2009-09-05 21:47:34 +00001847 }
1848 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1849 return(MagickFalse);
1850 /*
1851 Propagate the error as the last entry of the error queue.
1852 */
1853 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1854 sizeof(p->error[0]));
cristy4c08aed2011-07-01 19:47:50 +00001855 AssociateAlphaPixelPacket(image,cube_info,image->colormap+index,&color);
cristy3ed852e2009-09-05 21:47:34 +00001856 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1857 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1858 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1859 if (cube_info->associate_alpha != MagickFalse)
cristy4c08aed2011-07-01 19:47:50 +00001860 p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
cristy3ed852e2009-09-05 21:47:34 +00001861 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1862 if (proceed == MagickFalse)
1863 return(MagickFalse);
1864 p->offset++;
1865 }
1866 switch (direction)
1867 {
1868 case WestGravity: p->x--; break;
1869 case EastGravity: p->x++; break;
1870 case NorthGravity: p->y--; break;
1871 case SouthGravity: p->y++; break;
1872 }
1873 return(MagickTrue);
1874}
1875
cristybb503372010-05-27 20:51:26 +00001876static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
cristy3ed852e2009-09-05 21:47:34 +00001877{
1878 if (x > y)
1879 return(x);
1880 return(y);
1881}
1882
cristybb503372010-05-27 20:51:26 +00001883static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
cristy3ed852e2009-09-05 21:47:34 +00001884{
1885 if (x < y)
1886 return(x);
1887 return(y);
1888}
1889
1890static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1891{
cristyc4c8d132010-01-07 01:58:38 +00001892 CacheView
1893 *image_view;
1894
cristy3ed852e2009-09-05 21:47:34 +00001895 MagickBooleanType
1896 status;
1897
cristybb503372010-05-27 20:51:26 +00001898 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001899 i;
1900
cristybb503372010-05-27 20:51:26 +00001901 size_t
cristy3ed852e2009-09-05 21:47:34 +00001902 depth;
1903
cristyfb7e9cd2011-02-20 16:26:15 +00001904 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
cristy3ed852e2009-09-05 21:47:34 +00001905 return(FloydSteinbergDither(image,cube_info));
1906 /*
cristycee97112010-05-28 00:44:52 +00001907 Distribute quantization error along a Hilbert curve.
cristy3ed852e2009-09-05 21:47:34 +00001908 */
1909 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1910 sizeof(*cube_info->error));
1911 cube_info->x=0;
1912 cube_info->y=0;
cristybb503372010-05-27 20:51:26 +00001913 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
cristy3ed852e2009-09-05 21:47:34 +00001914 for (depth=1; i != 0; depth++)
1915 i>>=1;
cristybb503372010-05-27 20:51:26 +00001916 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
cristy3ed852e2009-09-05 21:47:34 +00001917 depth++;
1918 cube_info->offset=0;
1919 cube_info->span=(MagickSizeType) image->columns*image->rows;
1920 image_view=AcquireCacheView(image);
1921 if (depth > 1)
1922 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1923 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1924 image_view=DestroyCacheView(image_view);
1925 return(status);
1926}
1927
1928/*
1929%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1930% %
1931% %
1932% %
1933+ G e t C u b e I n f o %
1934% %
1935% %
1936% %
1937%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1938%
1939% GetCubeInfo() initialize the Cube data structure.
1940%
1941% The format of the GetCubeInfo method is:
1942%
1943% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
cristybb503372010-05-27 20:51:26 +00001944% const size_t depth,const size_t maximum_colors)
cristy3ed852e2009-09-05 21:47:34 +00001945%
1946% A description of each parameter follows.
1947%
1948% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1949%
1950% o depth: Normally, this integer value is zero or one. A zero or
1951% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1952% A tree of this depth generally allows the best representation of the
1953% reference image with the least amount of memory and the fastest
1954% computational speed. In some cases, such as an image with low color
1955% dispersion (a few number of colors), a value other than
1956% Log4(number_colors) is required. To expand the color tree completely,
1957% use a value of 8.
1958%
1959% o maximum_colors: maximum colors.
1960%
1961*/
1962static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
cristybb503372010-05-27 20:51:26 +00001963 const size_t depth,const size_t maximum_colors)
cristy3ed852e2009-09-05 21:47:34 +00001964{
1965 CubeInfo
1966 *cube_info;
1967
1968 MagickRealType
1969 sum,
1970 weight;
1971
cristybb503372010-05-27 20:51:26 +00001972 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001973 i;
1974
cristyecc31b12011-02-13 00:32:29 +00001975 size_t
1976 length;
1977
cristy3ed852e2009-09-05 21:47:34 +00001978 /*
1979 Initialize tree to describe color cube_info.
1980 */
cristy73bd4a52010-10-05 11:24:23 +00001981 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
cristy3ed852e2009-09-05 21:47:34 +00001982 if (cube_info == (CubeInfo *) NULL)
1983 return((CubeInfo *) NULL);
1984 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1985 cube_info->depth=depth;
1986 if (cube_info->depth > MaxTreeDepth)
1987 cube_info->depth=MaxTreeDepth;
1988 if (cube_info->depth < 2)
1989 cube_info->depth=2;
1990 cube_info->maximum_colors=maximum_colors;
1991 /*
1992 Initialize root node.
1993 */
1994 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1995 if (cube_info->root == (NodeInfo *) NULL)
1996 return((CubeInfo *) NULL);
1997 cube_info->root->parent=cube_info->root;
1998 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1999 if (cube_info->quantize_info->dither == MagickFalse)
2000 return(cube_info);
2001 /*
2002 Initialize dither resources.
2003 */
2004 length=(size_t) (1UL << (4*(8-CacheShift)));
cristybb503372010-05-27 20:51:26 +00002005 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
cristy3ed852e2009-09-05 21:47:34 +00002006 sizeof(*cube_info->cache));
cristybb503372010-05-27 20:51:26 +00002007 if (cube_info->cache == (ssize_t *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00002008 return((CubeInfo *) NULL);
2009 /*
2010 Initialize color cache.
2011 */
cristybb503372010-05-27 20:51:26 +00002012 for (i=0; i < (ssize_t) length; i++)
cristy3ed852e2009-09-05 21:47:34 +00002013 cube_info->cache[i]=(-1);
2014 /*
cristycee97112010-05-28 00:44:52 +00002015 Distribute weights along a curve of exponential decay.
cristy3ed852e2009-09-05 21:47:34 +00002016 */
2017 weight=1.0;
2018 for (i=0; i < ErrorQueueLength; i++)
2019 {
2020 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2021 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2022 }
2023 /*
2024 Normalize the weighting factors.
2025 */
2026 weight=0.0;
2027 for (i=0; i < ErrorQueueLength; i++)
2028 weight+=cube_info->weights[i];
2029 sum=0.0;
2030 for (i=0; i < ErrorQueueLength; i++)
2031 {
2032 cube_info->weights[i]/=weight;
2033 sum+=cube_info->weights[i];
2034 }
2035 cube_info->weights[0]+=1.0-sum;
2036 return(cube_info);
2037}
2038
2039/*
2040%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2041% %
2042% %
2043% %
2044+ G e t N o d e I n f o %
2045% %
2046% %
2047% %
2048%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2049%
2050% GetNodeInfo() allocates memory for a new node in the color cube tree and
2051% presets all fields to zero.
2052%
2053% The format of the GetNodeInfo method is:
2054%
cristybb503372010-05-27 20:51:26 +00002055% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2056% const size_t level,NodeInfo *parent)
cristy3ed852e2009-09-05 21:47:34 +00002057%
2058% A description of each parameter follows.
2059%
2060% o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2061%
2062% o id: Specifies the child number of the node.
2063%
2064% o level: Specifies the level in the storage_class the node resides.
2065%
2066*/
cristybb503372010-05-27 20:51:26 +00002067static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2068 const size_t level,NodeInfo *parent)
cristy3ed852e2009-09-05 21:47:34 +00002069{
2070 NodeInfo
2071 *node_info;
2072
2073 if (cube_info->free_nodes == 0)
2074 {
2075 Nodes
2076 *nodes;
2077
2078 /*
2079 Allocate a new queue of nodes.
2080 */
cristy73bd4a52010-10-05 11:24:23 +00002081 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
cristy3ed852e2009-09-05 21:47:34 +00002082 if (nodes == (Nodes *) NULL)
2083 return((NodeInfo *) NULL);
2084 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2085 sizeof(*nodes->nodes));
2086 if (nodes->nodes == (NodeInfo *) NULL)
2087 return((NodeInfo *) NULL);
2088 nodes->next=cube_info->node_queue;
2089 cube_info->node_queue=nodes;
2090 cube_info->next_node=nodes->nodes;
2091 cube_info->free_nodes=NodesInAList;
2092 }
2093 cube_info->nodes++;
2094 cube_info->free_nodes--;
2095 node_info=cube_info->next_node++;
2096 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2097 node_info->parent=parent;
2098 node_info->id=id;
2099 node_info->level=level;
2100 return(node_info);
2101}
2102
2103/*
2104%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2105% %
2106% %
2107% %
2108% G e t I m a g e Q u a n t i z e E r r o r %
2109% %
2110% %
2111% %
2112%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2113%
2114% GetImageQuantizeError() measures the difference between the original
2115% and quantized images. This difference is the total quantization error.
2116% The error is computed by summing over all pixels in an image the distance
2117% squared in RGB space between each reference pixel value and its quantized
2118% value. These values are computed:
2119%
2120% o mean_error_per_pixel: This value is the mean error for any single
2121% pixel in the image.
2122%
2123% o normalized_mean_square_error: This value is the normalized mean
2124% quantization error for any single pixel in the image. This distance
2125% measure is normalized to a range between 0 and 1. It is independent
2126% of the range of red, green, and blue values in the image.
2127%
2128% o normalized_maximum_square_error: Thsi value is the normalized
2129% maximum quantization error for any single pixel in the image. This
2130% distance measure is normalized to a range between 0 and 1. It is
2131% independent of the range of red, green, and blue values in your image.
2132%
2133% The format of the GetImageQuantizeError method is:
2134%
2135% MagickBooleanType GetImageQuantizeError(Image *image)
2136%
2137% A description of each parameter follows.
2138%
2139% o image: the image.
2140%
2141*/
2142MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2143{
cristyc4c8d132010-01-07 01:58:38 +00002144 CacheView
2145 *image_view;
2146
cristy3ed852e2009-09-05 21:47:34 +00002147 ExceptionInfo
2148 *exception;
2149
cristy3ed852e2009-09-05 21:47:34 +00002150 MagickRealType
2151 alpha,
2152 area,
2153 beta,
2154 distance,
2155 maximum_error,
2156 mean_error,
2157 mean_error_per_pixel;
2158
cristybb503372010-05-27 20:51:26 +00002159 size_t
cristy3ed852e2009-09-05 21:47:34 +00002160 index;
2161
cristyecc31b12011-02-13 00:32:29 +00002162 ssize_t
2163 y;
2164
cristy3ed852e2009-09-05 21:47:34 +00002165 assert(image != (Image *) NULL);
2166 assert(image->signature == MagickSignature);
2167 if (image->debug != MagickFalse)
2168 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2169 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2170 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2171 if (image->storage_class == DirectClass)
2172 return(MagickTrue);
2173 alpha=1.0;
2174 beta=1.0;
2175 area=3.0*image->columns*image->rows;
2176 maximum_error=0.0;
2177 mean_error_per_pixel=0.0;
2178 mean_error=0.0;
2179 exception=(&image->exception);
2180 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +00002181 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00002182 {
cristy4c08aed2011-07-01 19:47:50 +00002183 register const Quantum
cristyc47d1f82009-11-26 01:44:43 +00002184 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00002185
cristybb503372010-05-27 20:51:26 +00002186 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002187 x;
2188
2189 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
cristy4c08aed2011-07-01 19:47:50 +00002190 if (p == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00002191 break;
cristybb503372010-05-27 20:51:26 +00002192 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00002193 {
cristy4c08aed2011-07-01 19:47:50 +00002194 index=1UL*GetPixelIndex(image,p);
cristy3ed852e2009-09-05 21:47:34 +00002195 if (image->matte != MagickFalse)
2196 {
cristy4c08aed2011-07-01 19:47:50 +00002197 alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,p));
2198 beta=(MagickRealType) (QuantumScale*image->colormap[index].alpha);
cristy3ed852e2009-09-05 21:47:34 +00002199 }
cristy4c08aed2011-07-01 19:47:50 +00002200 distance=fabs(alpha*GetPixelRed(image,p)-beta*
cristy01e4e7d2011-05-01 23:00:41 +00002201 image->colormap[index].red);
cristy3ed852e2009-09-05 21:47:34 +00002202 mean_error_per_pixel+=distance;
2203 mean_error+=distance*distance;
2204 if (distance > maximum_error)
2205 maximum_error=distance;
cristy4c08aed2011-07-01 19:47:50 +00002206 distance=fabs(alpha*GetPixelGreen(image,p)-beta*
cristy01e4e7d2011-05-01 23:00:41 +00002207 image->colormap[index].green);
cristy3ed852e2009-09-05 21:47:34 +00002208 mean_error_per_pixel+=distance;
2209 mean_error+=distance*distance;
2210 if (distance > maximum_error)
2211 maximum_error=distance;
cristy4c08aed2011-07-01 19:47:50 +00002212 distance=fabs(alpha*GetPixelBlue(image,p)-beta*
cristy01e4e7d2011-05-01 23:00:41 +00002213 image->colormap[index].blue);
cristy3ed852e2009-09-05 21:47:34 +00002214 mean_error_per_pixel+=distance;
2215 mean_error+=distance*distance;
2216 if (distance > maximum_error)
2217 maximum_error=distance;
cristydcfc1ad2011-07-07 16:25:41 +00002218 p+=GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +00002219 }
2220 }
2221 image_view=DestroyCacheView(image_view);
2222 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2223 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2224 mean_error/area;
2225 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2226 return(MagickTrue);
2227}
2228
2229/*
2230%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2231% %
2232% %
2233% %
2234% G e t Q u a n t i z e I n f o %
2235% %
2236% %
2237% %
2238%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2239%
2240% GetQuantizeInfo() initializes the QuantizeInfo structure.
2241%
2242% The format of the GetQuantizeInfo method is:
2243%
2244% GetQuantizeInfo(QuantizeInfo *quantize_info)
2245%
2246% A description of each parameter follows:
2247%
2248% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2249%
2250*/
2251MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2252{
2253 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2254 assert(quantize_info != (QuantizeInfo *) NULL);
2255 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2256 quantize_info->number_colors=256;
2257 quantize_info->dither=MagickTrue;
2258 quantize_info->dither_method=RiemersmaDitherMethod;
2259 quantize_info->colorspace=UndefinedColorspace;
2260 quantize_info->measure_error=MagickFalse;
2261 quantize_info->signature=MagickSignature;
2262}
2263
2264/*
2265%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2266% %
2267% %
2268% %
cristyd1a2c0f2011-02-09 14:14:50 +00002269% P o s t e r i z e I m a g e C h a n n e l %
cristy3ed852e2009-09-05 21:47:34 +00002270% %
2271% %
2272% %
2273%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2274%
2275% PosterizeImage() reduces the image to a limited number of colors for a
2276% "poster" effect.
2277%
2278% The format of the PosterizeImage method is:
2279%
cristybb503372010-05-27 20:51:26 +00002280% MagickBooleanType PosterizeImage(Image *image,const size_t levels,
cristy3ed852e2009-09-05 21:47:34 +00002281% const MagickBooleanType dither)
cristyd1a2c0f2011-02-09 14:14:50 +00002282% MagickBooleanType PosterizeImageChannel(Image *image,
2283% const ChannelType channel,const size_t levels,
2284% const MagickBooleanType dither)
cristy3ed852e2009-09-05 21:47:34 +00002285%
2286% A description of each parameter follows:
2287%
2288% o image: Specifies a pointer to an Image structure.
2289%
2290% o levels: Number of color levels allowed in each channel. Very low values
2291% (2, 3, or 4) have the most visible effect.
2292%
cristy847620f2011-02-09 02:24:21 +00002293% o dither: Set this integer value to something other than zero to dither
2294% the mapped image.
cristy3ed852e2009-09-05 21:47:34 +00002295%
2296*/
cristyd1a2c0f2011-02-09 14:14:50 +00002297
cristy4d727152011-02-10 19:57:21 +00002298static inline ssize_t MagickRound(MagickRealType x)
2299{
2300 /*
cristyecc31b12011-02-13 00:32:29 +00002301 Round the fraction to nearest integer.
cristy4d727152011-02-10 19:57:21 +00002302 */
2303 if (x >= 0.0)
2304 return((ssize_t) (x+0.5));
2305 return((ssize_t) (x-0.5));
2306}
2307
cristyd1a2c0f2011-02-09 14:14:50 +00002308MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2309 const MagickBooleanType dither)
cristy3ed852e2009-09-05 21:47:34 +00002310{
cristyd1a2c0f2011-02-09 14:14:50 +00002311 MagickBooleanType
2312 status;
2313
2314 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2315 return(status);
2316}
2317
2318MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2319 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2320{
2321#define PosterizeImageTag "Posterize/Image"
cristy4d727152011-02-10 19:57:21 +00002322#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
cristy3e9cad02011-02-20 01:42:00 +00002323 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
cristyd1a2c0f2011-02-09 14:14:50 +00002324
cristyc4c8d132010-01-07 01:58:38 +00002325 CacheView
cristyd1a2c0f2011-02-09 14:14:50 +00002326 *image_view;
cristyc4c8d132010-01-07 01:58:38 +00002327
cristy3ed852e2009-09-05 21:47:34 +00002328 ExceptionInfo
2329 *exception;
2330
cristy3ed852e2009-09-05 21:47:34 +00002331 MagickBooleanType
2332 status;
2333
cristyd1a2c0f2011-02-09 14:14:50 +00002334 MagickOffsetType
2335 progress;
2336
cristy3ed852e2009-09-05 21:47:34 +00002337 QuantizeInfo
2338 *quantize_info;
2339
cristy847620f2011-02-09 02:24:21 +00002340 register ssize_t
2341 i;
2342
cristy847620f2011-02-09 02:24:21 +00002343 ssize_t
cristyd1a2c0f2011-02-09 14:14:50 +00002344 y;
cristy847620f2011-02-09 02:24:21 +00002345
cristy3ed852e2009-09-05 21:47:34 +00002346 assert(image != (Image *) NULL);
2347 assert(image->signature == MagickSignature);
2348 if (image->debug != MagickFalse)
2349 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
cristyd1a2c0f2011-02-09 14:14:50 +00002350 if (image->storage_class == PseudoClass)
2351#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy00cbdd62011-02-20 17:29:26 +00002352 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
cristyd1a2c0f2011-02-09 14:14:50 +00002353#endif
2354 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00002355 {
cristyd1a2c0f2011-02-09 14:14:50 +00002356 /*
2357 Posterize colormap.
2358 */
cristy2b9582a2011-07-04 17:38:56 +00002359 if ((GetPixelRedTraits(image) & ActivePixelTrait) != 0)
cristyd1a2c0f2011-02-09 14:14:50 +00002360 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
cristy2b9582a2011-07-04 17:38:56 +00002361 if ((GetPixelGreenTraits(image) & ActivePixelTrait) != 0)
cristyd1a2c0f2011-02-09 14:14:50 +00002362 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
cristy2b9582a2011-07-04 17:38:56 +00002363 if ((GetPixelBlueTraits(image) & ActivePixelTrait) != 0)
cristyd1a2c0f2011-02-09 14:14:50 +00002364 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
cristy2b9582a2011-07-04 17:38:56 +00002365 if ((GetPixelAlphaTraits(image) & ActivePixelTrait) != 0)
cristy4c08aed2011-07-01 19:47:50 +00002366 image->colormap[i].alpha=PosterizePixel(image->colormap[i].alpha);
cristy3ed852e2009-09-05 21:47:34 +00002367 }
cristyd1a2c0f2011-02-09 14:14:50 +00002368 /*
2369 Posterize image.
2370 */
2371 status=MagickTrue;
2372 progress=0;
cristy3ed852e2009-09-05 21:47:34 +00002373 exception=(&image->exception);
cristyd1a2c0f2011-02-09 14:14:50 +00002374 image_view=AcquireCacheView(image);
2375#if defined(MAGICKCORE_OPENMP_SUPPORT)
2376 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2377#endif
2378 for (y=0; y < (ssize_t) image->rows; y++)
2379 {
cristy4c08aed2011-07-01 19:47:50 +00002380 register Quantum
cristyd1a2c0f2011-02-09 14:14:50 +00002381 *restrict q;
2382
2383 register ssize_t
2384 x;
2385
2386 if (status == MagickFalse)
2387 continue;
2388 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
cristy4c08aed2011-07-01 19:47:50 +00002389 if (q == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00002390 {
cristyd1a2c0f2011-02-09 14:14:50 +00002391 status=MagickFalse;
2392 continue;
cristy3ed852e2009-09-05 21:47:34 +00002393 }
cristyd1a2c0f2011-02-09 14:14:50 +00002394 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00002395 {
cristy2b9582a2011-07-04 17:38:56 +00002396 if ((GetPixelRedTraits(image) & ActivePixelTrait) != 0)
cristy4c08aed2011-07-01 19:47:50 +00002397 SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
cristy2b9582a2011-07-04 17:38:56 +00002398 if ((GetPixelGreenTraits(image) & ActivePixelTrait) != 0)
cristy4c08aed2011-07-01 19:47:50 +00002399 SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
cristy2b9582a2011-07-04 17:38:56 +00002400 if ((GetPixelBlueTraits(image) & ActivePixelTrait) != 0)
cristy4c08aed2011-07-01 19:47:50 +00002401 SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
cristy2b9582a2011-07-04 17:38:56 +00002402 if (((GetPixelBlackTraits(image) & ActivePixelTrait) != 0) &&
cristy4c08aed2011-07-01 19:47:50 +00002403 (image->colorspace == CMYKColorspace))
2404 SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
cristy2b9582a2011-07-04 17:38:56 +00002405 if (((GetPixelAlphaTraits(image) & ActivePixelTrait) != 0) &&
cristyd1a2c0f2011-02-09 14:14:50 +00002406 (image->matte == MagickTrue))
cristy4c08aed2011-07-01 19:47:50 +00002407 SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
cristydcfc1ad2011-07-07 16:25:41 +00002408 q+=GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +00002409 }
cristyd1a2c0f2011-02-09 14:14:50 +00002410 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2411 status=MagickFalse;
2412 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2413 {
2414 MagickBooleanType
2415 proceed;
2416
2417#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy00cbdd62011-02-20 17:29:26 +00002418 #pragma omp critical (MagickCore_PosterizeImageChannel)
cristyd1a2c0f2011-02-09 14:14:50 +00002419#endif
2420 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2421 image->rows);
2422 if (proceed == MagickFalse)
2423 status=MagickFalse;
2424 }
2425 }
2426 image_view=DestroyCacheView(image_view);
cristy3ed852e2009-09-05 21:47:34 +00002427 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
cristyd1a2c0f2011-02-09 14:14:50 +00002428 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2429 levels,MaxColormapSize+1);
cristy3ed852e2009-09-05 21:47:34 +00002430 quantize_info->dither=dither;
cristy3e9cad02011-02-20 01:42:00 +00002431 quantize_info->tree_depth=MaxTreeDepth;
cristyd1a2c0f2011-02-09 14:14:50 +00002432 status=QuantizeImage(quantize_info,image);
cristy3ed852e2009-09-05 21:47:34 +00002433 quantize_info=DestroyQuantizeInfo(quantize_info);
cristy3ed852e2009-09-05 21:47:34 +00002434 return(status);
2435}
2436
2437/*
2438%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2439% %
2440% %
2441% %
2442+ P r u n e C h i l d %
2443% %
2444% %
2445% %
2446%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2447%
2448% PruneChild() deletes the given node and merges its statistics into its
2449% parent.
2450%
2451% The format of the PruneSubtree method is:
2452%
2453% PruneChild(const Image *image,CubeInfo *cube_info,
2454% const NodeInfo *node_info)
2455%
2456% A description of each parameter follows.
2457%
2458% o image: the image.
2459%
2460% o cube_info: A pointer to the Cube structure.
2461%
2462% o node_info: pointer to node in color cube tree that is to be pruned.
2463%
2464*/
2465static void PruneChild(const Image *image,CubeInfo *cube_info,
2466 const NodeInfo *node_info)
2467{
2468 NodeInfo
2469 *parent;
2470
cristybb503372010-05-27 20:51:26 +00002471 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002472 i;
2473
cristybb503372010-05-27 20:51:26 +00002474 size_t
cristy3ed852e2009-09-05 21:47:34 +00002475 number_children;
2476
2477 /*
2478 Traverse any children.
2479 */
2480 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002481 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002482 if (node_info->child[i] != (NodeInfo *) NULL)
2483 PruneChild(image,cube_info,node_info->child[i]);
2484 /*
2485 Merge color statistics into parent.
2486 */
2487 parent=node_info->parent;
2488 parent->number_unique+=node_info->number_unique;
2489 parent->total_color.red+=node_info->total_color.red;
2490 parent->total_color.green+=node_info->total_color.green;
2491 parent->total_color.blue+=node_info->total_color.blue;
cristy4c08aed2011-07-01 19:47:50 +00002492 parent->total_color.alpha+=node_info->total_color.alpha;
cristy3ed852e2009-09-05 21:47:34 +00002493 parent->child[node_info->id]=(NodeInfo *) NULL;
2494 cube_info->nodes--;
2495}
2496
2497/*
2498%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2499% %
2500% %
2501% %
2502+ P r u n e L e v e l %
2503% %
2504% %
2505% %
2506%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2507%
2508% PruneLevel() deletes all nodes at the bottom level of the color tree merging
2509% their color statistics into their parent node.
2510%
2511% The format of the PruneLevel method is:
2512%
2513% PruneLevel(const Image *image,CubeInfo *cube_info,
2514% const NodeInfo *node_info)
2515%
2516% A description of each parameter follows.
2517%
2518% o image: the image.
2519%
2520% o cube_info: A pointer to the Cube structure.
2521%
2522% o node_info: pointer to node in color cube tree that is to be pruned.
2523%
2524*/
2525static void PruneLevel(const Image *image,CubeInfo *cube_info,
2526 const NodeInfo *node_info)
2527{
cristybb503372010-05-27 20:51:26 +00002528 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002529 i;
2530
cristybb503372010-05-27 20:51:26 +00002531 size_t
cristy3ed852e2009-09-05 21:47:34 +00002532 number_children;
2533
2534 /*
2535 Traverse any children.
2536 */
2537 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002538 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002539 if (node_info->child[i] != (NodeInfo *) NULL)
2540 PruneLevel(image,cube_info,node_info->child[i]);
2541 if (node_info->level == cube_info->depth)
2542 PruneChild(image,cube_info,node_info);
2543}
2544
2545/*
2546%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2547% %
2548% %
2549% %
2550+ P r u n e T o C u b e D e p t h %
2551% %
2552% %
2553% %
2554%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2555%
2556% PruneToCubeDepth() deletes any nodes at a depth greater than
2557% cube_info->depth while merging their color statistics into their parent
2558% node.
2559%
2560% The format of the PruneToCubeDepth method is:
2561%
2562% PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2563% const NodeInfo *node_info)
2564%
2565% A description of each parameter follows.
2566%
2567% o cube_info: A pointer to the Cube structure.
2568%
2569% o node_info: pointer to node in color cube tree that is to be pruned.
2570%
2571*/
2572static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2573 const NodeInfo *node_info)
2574{
cristybb503372010-05-27 20:51:26 +00002575 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002576 i;
2577
cristybb503372010-05-27 20:51:26 +00002578 size_t
cristy3ed852e2009-09-05 21:47:34 +00002579 number_children;
2580
2581 /*
2582 Traverse any children.
2583 */
2584 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002585 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002586 if (node_info->child[i] != (NodeInfo *) NULL)
2587 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2588 if (node_info->level > cube_info->depth)
2589 PruneChild(image,cube_info,node_info);
2590}
2591
2592/*
2593%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2594% %
2595% %
2596% %
2597% Q u a n t i z e I m a g e %
2598% %
2599% %
2600% %
2601%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2602%
2603% QuantizeImage() analyzes the colors within a reference image and chooses a
2604% fixed number of colors to represent the image. The goal of the algorithm
2605% is to minimize the color difference between the input and output image while
2606% minimizing the processing time.
2607%
2608% The format of the QuantizeImage method is:
2609%
2610% MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2611% Image *image)
2612%
2613% A description of each parameter follows:
2614%
2615% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2616%
2617% o image: the image.
2618%
2619*/
2620MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2621 Image *image)
2622{
2623 CubeInfo
2624 *cube_info;
2625
2626 MagickBooleanType
2627 status;
2628
cristybb503372010-05-27 20:51:26 +00002629 size_t
cristy3ed852e2009-09-05 21:47:34 +00002630 depth,
2631 maximum_colors;
2632
2633 assert(quantize_info != (const QuantizeInfo *) NULL);
2634 assert(quantize_info->signature == MagickSignature);
2635 assert(image != (Image *) NULL);
2636 assert(image->signature == MagickSignature);
2637 if (image->debug != MagickFalse)
2638 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2639 maximum_colors=quantize_info->number_colors;
2640 if (maximum_colors == 0)
2641 maximum_colors=MaxColormapSize;
2642 if (maximum_colors > MaxColormapSize)
2643 maximum_colors=MaxColormapSize;
cristy4c08aed2011-07-01 19:47:50 +00002644 if ((IsImageGray(image,&image->exception) != MagickFalse) &&
cristy8e752752011-04-16 13:48:22 +00002645 (image->matte == MagickFalse))
2646 (void) SetGrayscaleImage(image);
cristy3ed852e2009-09-05 21:47:34 +00002647 if ((image->storage_class == PseudoClass) &&
2648 (image->colors <= maximum_colors))
2649 return(MagickTrue);
2650 depth=quantize_info->tree_depth;
2651 if (depth == 0)
2652 {
cristybb503372010-05-27 20:51:26 +00002653 size_t
cristy3ed852e2009-09-05 21:47:34 +00002654 colors;
2655
2656 /*
2657 Depth of color tree is: Log4(colormap size)+2.
2658 */
2659 colors=maximum_colors;
2660 for (depth=1; colors != 0; depth++)
2661 colors>>=2;
2662 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2663 depth--;
2664 if ((image->matte != MagickFalse) && (depth > 5))
2665 depth--;
2666 }
2667 /*
2668 Initialize color cube.
2669 */
2670 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2671 if (cube_info == (CubeInfo *) NULL)
2672 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2673 image->filename);
2674 status=ClassifyImageColors(cube_info,image,&image->exception);
2675 if (status != MagickFalse)
2676 {
2677 /*
2678 Reduce the number of colors in the image.
2679 */
2680 ReduceImageColors(image,cube_info);
2681 status=AssignImageColors(image,cube_info);
2682 }
2683 DestroyCubeInfo(cube_info);
2684 return(status);
2685}
2686
2687/*
2688%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2689% %
2690% %
2691% %
2692% Q u a n t i z e I m a g e s %
2693% %
2694% %
2695% %
2696%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2697%
2698% QuantizeImages() analyzes the colors within a set of reference images and
2699% chooses a fixed number of colors to represent the set. The goal of the
2700% algorithm is to minimize the color difference between the input and output
2701% images while minimizing the processing time.
2702%
2703% The format of the QuantizeImages method is:
2704%
2705% MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2706% Image *images)
2707%
2708% A description of each parameter follows:
2709%
2710% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2711%
2712% o images: Specifies a pointer to a list of Image structures.
2713%
2714*/
2715MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2716 Image *images)
2717{
2718 CubeInfo
2719 *cube_info;
2720
2721 Image
2722 *image;
2723
2724 MagickBooleanType
2725 proceed,
2726 status;
2727
2728 MagickProgressMonitor
2729 progress_monitor;
2730
cristybb503372010-05-27 20:51:26 +00002731 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002732 i;
2733
cristybb503372010-05-27 20:51:26 +00002734 size_t
cristy3ed852e2009-09-05 21:47:34 +00002735 depth,
2736 maximum_colors,
2737 number_images;
2738
2739 assert(quantize_info != (const QuantizeInfo *) NULL);
2740 assert(quantize_info->signature == MagickSignature);
2741 assert(images != (Image *) NULL);
2742 assert(images->signature == MagickSignature);
2743 if (images->debug != MagickFalse)
2744 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2745 if (GetNextImageInList(images) == (Image *) NULL)
2746 {
2747 /*
2748 Handle a single image with QuantizeImage.
2749 */
2750 status=QuantizeImage(quantize_info,images);
2751 return(status);
2752 }
2753 status=MagickFalse;
2754 maximum_colors=quantize_info->number_colors;
2755 if (maximum_colors == 0)
2756 maximum_colors=MaxColormapSize;
2757 if (maximum_colors > MaxColormapSize)
2758 maximum_colors=MaxColormapSize;
2759 depth=quantize_info->tree_depth;
2760 if (depth == 0)
2761 {
cristybb503372010-05-27 20:51:26 +00002762 size_t
cristy3ed852e2009-09-05 21:47:34 +00002763 colors;
2764
2765 /*
2766 Depth of color tree is: Log4(colormap size)+2.
2767 */
2768 colors=maximum_colors;
2769 for (depth=1; colors != 0; depth++)
2770 colors>>=2;
2771 if (quantize_info->dither != MagickFalse)
2772 depth--;
2773 }
2774 /*
2775 Initialize color cube.
2776 */
2777 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2778 if (cube_info == (CubeInfo *) NULL)
2779 {
2780 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2781 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2782 return(MagickFalse);
2783 }
2784 number_images=GetImageListLength(images);
2785 image=images;
2786 for (i=0; image != (Image *) NULL; i++)
2787 {
2788 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2789 image->client_data);
2790 status=ClassifyImageColors(cube_info,image,&image->exception);
2791 if (status == MagickFalse)
2792 break;
2793 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
cristycee97112010-05-28 00:44:52 +00002794 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2795 number_images);
cristy3ed852e2009-09-05 21:47:34 +00002796 if (proceed == MagickFalse)
2797 break;
2798 image=GetNextImageInList(image);
2799 }
2800 if (status != MagickFalse)
2801 {
2802 /*
2803 Reduce the number of colors in an image sequence.
2804 */
2805 ReduceImageColors(images,cube_info);
2806 image=images;
2807 for (i=0; image != (Image *) NULL; i++)
2808 {
2809 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2810 NULL,image->client_data);
2811 status=AssignImageColors(image,cube_info);
2812 if (status == MagickFalse)
2813 break;
2814 (void) SetImageProgressMonitor(image,progress_monitor,
2815 image->client_data);
cristycee97112010-05-28 00:44:52 +00002816 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2817 number_images);
cristy3ed852e2009-09-05 21:47:34 +00002818 if (proceed == MagickFalse)
2819 break;
2820 image=GetNextImageInList(image);
2821 }
2822 }
2823 DestroyCubeInfo(cube_info);
2824 return(status);
2825}
2826
2827/*
2828%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2829% %
2830% %
2831% %
2832+ R e d u c e %
2833% %
2834% %
2835% %
2836%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2837%
2838% Reduce() traverses the color cube tree and prunes any node whose
2839% quantization error falls below a particular threshold.
2840%
2841% The format of the Reduce method is:
2842%
2843% Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2844%
2845% A description of each parameter follows.
2846%
2847% o image: the image.
2848%
2849% o cube_info: A pointer to the Cube structure.
2850%
2851% o node_info: pointer to node in color cube tree that is to be pruned.
2852%
2853*/
2854static void Reduce(const Image *image,CubeInfo *cube_info,
2855 const NodeInfo *node_info)
2856{
cristybb503372010-05-27 20:51:26 +00002857 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002858 i;
2859
cristybb503372010-05-27 20:51:26 +00002860 size_t
cristy3ed852e2009-09-05 21:47:34 +00002861 number_children;
2862
2863 /*
2864 Traverse any children.
2865 */
2866 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002867 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002868 if (node_info->child[i] != (NodeInfo *) NULL)
2869 Reduce(image,cube_info,node_info->child[i]);
2870 if (node_info->quantize_error <= cube_info->pruning_threshold)
2871 PruneChild(image,cube_info,node_info);
2872 else
2873 {
2874 /*
2875 Find minimum pruning threshold.
2876 */
2877 if (node_info->number_unique > 0)
2878 cube_info->colors++;
2879 if (node_info->quantize_error < cube_info->next_threshold)
2880 cube_info->next_threshold=node_info->quantize_error;
2881 }
2882}
2883
2884/*
2885%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2886% %
2887% %
2888% %
2889+ R e d u c e I m a g e C o l o r s %
2890% %
2891% %
2892% %
2893%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2894%
2895% ReduceImageColors() repeatedly prunes the tree until the number of nodes
2896% with n2 > 0 is less than or equal to the maximum number of colors allowed
2897% in the output image. On any given iteration over the tree, it selects
2898% those nodes whose E value is minimal for pruning and merges their
2899% color statistics upward. It uses a pruning threshold, Ep, to govern
2900% node selection as follows:
2901%
2902% Ep = 0
2903% while number of nodes with (n2 > 0) > required maximum number of colors
2904% prune all nodes such that E <= Ep
2905% Set Ep to minimum E in remaining nodes
2906%
2907% This has the effect of minimizing any quantization error when merging
2908% two nodes together.
2909%
2910% When a node to be pruned has offspring, the pruning procedure invokes
2911% itself recursively in order to prune the tree from the leaves upward.
2912% n2, Sr, Sg, and Sb in a node being pruned are always added to the
2913% corresponding data in that node's parent. This retains the pruned
2914% node's color characteristics for later averaging.
2915%
2916% For each node, n2 pixels exist for which that node represents the
2917% smallest volume in RGB space containing those pixel's colors. When n2
2918% > 0 the node will uniquely define a color in the output image. At the
2919% beginning of reduction, n2 = 0 for all nodes except a the leaves of
2920% the tree which represent colors present in the input image.
2921%
2922% The other pixel count, n1, indicates the total number of colors
2923% within the cubic volume which the node represents. This includes n1 -
2924% n2 pixels whose colors should be defined by nodes at a lower level in
2925% the tree.
2926%
2927% The format of the ReduceImageColors method is:
2928%
2929% ReduceImageColors(const Image *image,CubeInfo *cube_info)
2930%
2931% A description of each parameter follows.
2932%
2933% o image: the image.
2934%
2935% o cube_info: A pointer to the Cube structure.
2936%
2937*/
2938static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2939{
2940#define ReduceImageTag "Reduce/Image"
2941
2942 MagickBooleanType
2943 proceed;
2944
2945 MagickOffsetType
2946 offset;
2947
cristybb503372010-05-27 20:51:26 +00002948 size_t
cristy3ed852e2009-09-05 21:47:34 +00002949 span;
2950
2951 cube_info->next_threshold=0.0;
2952 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2953 {
2954 cube_info->pruning_threshold=cube_info->next_threshold;
2955 cube_info->next_threshold=cube_info->root->quantize_error-1;
2956 cube_info->colors=0;
2957 Reduce(image,cube_info,cube_info->root);
2958 offset=(MagickOffsetType) span-cube_info->colors;
2959 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2960 cube_info->maximum_colors+1);
2961 if (proceed == MagickFalse)
2962 break;
2963 }
2964}
2965
2966/*
2967%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2968% %
2969% %
2970% %
2971% R e m a p I m a g e %
2972% %
2973% %
2974% %
2975%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2976%
2977% RemapImage() replaces the colors of an image with the closest color from
2978% a reference image.
2979%
2980% The format of the RemapImage method is:
2981%
2982% MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2983% Image *image,const Image *remap_image)
2984%
2985% A description of each parameter follows:
2986%
2987% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2988%
2989% o image: the image.
2990%
2991% o remap_image: the reference image.
2992%
2993*/
2994MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2995 Image *image,const Image *remap_image)
2996{
2997 CubeInfo
2998 *cube_info;
2999
3000 MagickBooleanType
3001 status;
3002
3003 /*
3004 Initialize color cube.
3005 */
3006 assert(image != (Image *) NULL);
3007 assert(image->signature == MagickSignature);
3008 if (image->debug != MagickFalse)
3009 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3010 assert(remap_image != (Image *) NULL);
3011 assert(remap_image->signature == MagickSignature);
3012 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3013 quantize_info->number_colors);
3014 if (cube_info == (CubeInfo *) NULL)
3015 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3016 image->filename);
3017 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3018 if (status != MagickFalse)
3019 {
3020 /*
3021 Classify image colors from the reference image.
3022 */
3023 cube_info->quantize_info->number_colors=cube_info->colors;
3024 status=AssignImageColors(image,cube_info);
3025 }
3026 DestroyCubeInfo(cube_info);
3027 return(status);
3028}
3029
3030/*
3031%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3032% %
3033% %
3034% %
3035% R e m a p I m a g e s %
3036% %
3037% %
3038% %
3039%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3040%
3041% RemapImages() replaces the colors of a sequence of images with the
3042% closest color from a reference image.
3043%
3044% The format of the RemapImage method is:
3045%
3046% MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3047% Image *images,Image *remap_image)
3048%
3049% A description of each parameter follows:
3050%
3051% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3052%
3053% o images: the image sequence.
3054%
3055% o remap_image: the reference image.
3056%
3057*/
3058MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3059 Image *images,const Image *remap_image)
3060{
3061 CubeInfo
3062 *cube_info;
3063
3064 Image
3065 *image;
3066
3067 MagickBooleanType
3068 status;
3069
3070 assert(images != (Image *) NULL);
3071 assert(images->signature == MagickSignature);
3072 if (images->debug != MagickFalse)
3073 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3074 image=images;
3075 if (remap_image == (Image *) NULL)
3076 {
3077 /*
3078 Create a global colormap for an image sequence.
3079 */
3080 status=QuantizeImages(quantize_info,images);
3081 return(status);
3082 }
3083 /*
3084 Classify image colors from the reference image.
3085 */
3086 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3087 quantize_info->number_colors);
3088 if (cube_info == (CubeInfo *) NULL)
3089 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3090 image->filename);
3091 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3092 if (status != MagickFalse)
3093 {
3094 /*
3095 Classify image colors from the reference image.
3096 */
3097 cube_info->quantize_info->number_colors=cube_info->colors;
3098 image=images;
3099 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3100 {
3101 status=AssignImageColors(image,cube_info);
3102 if (status == MagickFalse)
3103 break;
3104 }
3105 }
3106 DestroyCubeInfo(cube_info);
3107 return(status);
3108}
3109
3110/*
3111%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3112% %
3113% %
3114% %
3115% S e t G r a y s c a l e I m a g e %
3116% %
3117% %
3118% %
3119%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3120%
3121% SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3122%
3123% The format of the SetGrayscaleImage method is:
3124%
3125% MagickBooleanType SetGrayscaleImage(Image *image)
3126%
3127% A description of each parameter follows:
3128%
3129% o image: The image.
3130%
3131*/
3132
3133#if defined(__cplusplus) || defined(c_plusplus)
3134extern "C" {
3135#endif
3136
3137static int IntensityCompare(const void *x,const void *y)
3138{
cristy3ed852e2009-09-05 21:47:34 +00003139 PixelPacket
3140 *color_1,
3141 *color_2;
3142
cristyecc31b12011-02-13 00:32:29 +00003143 ssize_t
3144 intensity;
3145
cristy3ed852e2009-09-05 21:47:34 +00003146 color_1=(PixelPacket *) x;
3147 color_2=(PixelPacket *) y;
cristy4c08aed2011-07-01 19:47:50 +00003148 intensity=GetPixelPacketIntensity(color_1)-(ssize_t)
3149 GetPixelPacketIntensity(color_2);
cristycee97112010-05-28 00:44:52 +00003150 return((int) intensity);
cristy3ed852e2009-09-05 21:47:34 +00003151}
3152
3153#if defined(__cplusplus) || defined(c_plusplus)
3154}
3155#endif
3156
3157static MagickBooleanType SetGrayscaleImage(Image *image)
3158{
cristyc4c8d132010-01-07 01:58:38 +00003159 CacheView
3160 *image_view;
3161
cristy3ed852e2009-09-05 21:47:34 +00003162 ExceptionInfo
3163 *exception;
3164
cristyecc31b12011-02-13 00:32:29 +00003165 MagickBooleanType
3166 status;
cristy3ed852e2009-09-05 21:47:34 +00003167
3168 PixelPacket
3169 *colormap;
3170
cristybb503372010-05-27 20:51:26 +00003171 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003172 i;
3173
cristyecc31b12011-02-13 00:32:29 +00003174 ssize_t
3175 *colormap_index,
3176 j,
3177 y;
cristy3ed852e2009-09-05 21:47:34 +00003178
cristy3ed852e2009-09-05 21:47:34 +00003179 assert(image != (Image *) NULL);
3180 assert(image->signature == MagickSignature);
3181 if (image->type != GrayscaleType)
3182 (void) TransformImageColorspace(image,GRAYColorspace);
cristybb503372010-05-27 20:51:26 +00003183 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
cristy3ed852e2009-09-05 21:47:34 +00003184 sizeof(*colormap_index));
cristybb503372010-05-27 20:51:26 +00003185 if (colormap_index == (ssize_t *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00003186 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3187 image->filename);
3188 if (image->storage_class != PseudoClass)
3189 {
3190 ExceptionInfo
3191 *exception;
3192
cristybb503372010-05-27 20:51:26 +00003193 for (i=0; i <= (ssize_t) MaxMap; i++)
cristy3ed852e2009-09-05 21:47:34 +00003194 colormap_index[i]=(-1);
3195 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3196 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3197 image->filename);
3198 image->colors=0;
3199 status=MagickTrue;
3200 exception=(&image->exception);
3201 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003202#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy00cbdd62011-02-20 17:29:26 +00003203 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003204#endif
cristybb503372010-05-27 20:51:26 +00003205 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00003206 {
cristy4c08aed2011-07-01 19:47:50 +00003207 register Quantum
cristyc47d1f82009-11-26 01:44:43 +00003208 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003209
cristyecc31b12011-02-13 00:32:29 +00003210 register ssize_t
3211 x;
3212
cristy3ed852e2009-09-05 21:47:34 +00003213 if (status == MagickFalse)
3214 continue;
3215 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3216 exception);
cristy4c08aed2011-07-01 19:47:50 +00003217 if (q == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00003218 {
3219 status=MagickFalse;
3220 continue;
3221 }
cristybb503372010-05-27 20:51:26 +00003222 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00003223 {
cristybb503372010-05-27 20:51:26 +00003224 register size_t
cristy3ed852e2009-09-05 21:47:34 +00003225 intensity;
3226
cristy4c08aed2011-07-01 19:47:50 +00003227 intensity=ScaleQuantumToMap(GetPixelRed(image,q));
cristy3ed852e2009-09-05 21:47:34 +00003228 if (colormap_index[intensity] < 0)
3229 {
cristyb5d5f722009-11-04 03:03:49 +00003230#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy3ed852e2009-09-05 21:47:34 +00003231 #pragma omp critical (MagickCore_SetGrayscaleImage)
3232#endif
3233 if (colormap_index[intensity] < 0)
3234 {
cristybb503372010-05-27 20:51:26 +00003235 colormap_index[intensity]=(ssize_t) image->colors;
cristy4c08aed2011-07-01 19:47:50 +00003236 image->colormap[image->colors].red=GetPixelRed(image,q);
3237 image->colormap[image->colors].green=GetPixelGreen(image,q);
3238 image->colormap[image->colors].blue=GetPixelBlue(image,q);
cristy3ed852e2009-09-05 21:47:34 +00003239 image->colors++;
3240 }
3241 }
cristy4c08aed2011-07-01 19:47:50 +00003242 SetPixelIndex(image,(Quantum)
3243 colormap_index[intensity],q);
cristydcfc1ad2011-07-07 16:25:41 +00003244 q+=GetPixelComponents(image);
cristy3ed852e2009-09-05 21:47:34 +00003245 }
3246 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3247 status=MagickFalse;
3248 }
3249 image_view=DestroyCacheView(image_view);
3250 }
cristybb503372010-05-27 20:51:26 +00003251 for (i=0; i < (ssize_t) image->colors; i++)
cristy4c08aed2011-07-01 19:47:50 +00003252 image->colormap[i].alpha=(unsigned short) i;
cristy3ed852e2009-09-05 21:47:34 +00003253 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3254 IntensityCompare);
3255 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3256 sizeof(*colormap));
3257 if (colormap == (PixelPacket *) NULL)
3258 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3259 image->filename);
3260 j=0;
3261 colormap[j]=image->colormap[0];
cristybb503372010-05-27 20:51:26 +00003262 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00003263 {
cristy4c08aed2011-07-01 19:47:50 +00003264 if (IsPixelPacketEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00003265 {
3266 j++;
3267 colormap[j]=image->colormap[i];
3268 }
cristy4c08aed2011-07-01 19:47:50 +00003269 colormap_index[(ssize_t) image->colormap[i].alpha]=j;
cristy3ed852e2009-09-05 21:47:34 +00003270 }
cristybb503372010-05-27 20:51:26 +00003271 image->colors=(size_t) (j+1);
cristy3ed852e2009-09-05 21:47:34 +00003272 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3273 image->colormap=colormap;
3274 status=MagickTrue;
3275 exception=(&image->exception);
3276 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003277#if defined(MAGICKCORE_OPENMP_SUPPORT)
3278 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003279#endif
cristybb503372010-05-27 20:51:26 +00003280 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00003281 {
cristy4c08aed2011-07-01 19:47:50 +00003282 register Quantum
cristyc47d1f82009-11-26 01:44:43 +00003283 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003284
cristyecc31b12011-02-13 00:32:29 +00003285 register ssize_t
3286 x;
3287
cristy3ed852e2009-09-05 21:47:34 +00003288 if (status == MagickFalse)
3289 continue;
3290 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
cristy4c08aed2011-07-01 19:47:50 +00003291 if (q == (const Quantum *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00003292 {
3293 status=MagickFalse;
3294 continue;
3295 }
cristybb503372010-05-27 20:51:26 +00003296 for (x=0; x < (ssize_t) image->columns; x++)
cristy4c08aed2011-07-01 19:47:50 +00003297 {
3298 SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
3299 GetPixelIndex(image,q))],q);
cristydcfc1ad2011-07-07 16:25:41 +00003300 q+=GetPixelComponents(image);
cristy4c08aed2011-07-01 19:47:50 +00003301 }
cristy3ed852e2009-09-05 21:47:34 +00003302 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3303 status=MagickFalse;
3304 }
3305 image_view=DestroyCacheView(image_view);
cristybb503372010-05-27 20:51:26 +00003306 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
cristy3ed852e2009-09-05 21:47:34 +00003307 image->type=GrayscaleType;
cristy4c08aed2011-07-01 19:47:50 +00003308 if (IsImageMonochrome(image,&image->exception) != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00003309 image->type=BilevelType;
3310 return(status);
3311}