blob: 3ed33b3576dcee59239851eba46c8bbfe79f9ee7 [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% %
cristy16af1cb2009-12-11 21:38:29 +000020% Copyright 1999-2010 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*/
177#include "magick/studio.h"
178#include "magick/cache-view.h"
179#include "magick/color.h"
180#include "magick/color-private.h"
cristye7e40552010-04-24 21:34:22 +0000181#include "magick/colormap.h"
cristy3ed852e2009-09-05 21:47:34 +0000182#include "magick/colorspace.h"
183#include "magick/enhance.h"
184#include "magick/exception.h"
185#include "magick/exception-private.h"
cristyf2e11662009-10-14 01:24:43 +0000186#include "magick/histogram.h"
cristy3ed852e2009-09-05 21:47:34 +0000187#include "magick/image.h"
188#include "magick/image-private.h"
189#include "magick/list.h"
190#include "magick/memory_.h"
191#include "magick/monitor.h"
192#include "magick/monitor-private.h"
193#include "magick/option.h"
194#include "magick/pixel-private.h"
195#include "magick/quantize.h"
196#include "magick/quantum.h"
197#include "magick/string_.h"
198
199/*
200 Define declarations.
201*/
cristye1287512010-06-19 17:38:25 +0000202#if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
cristy3ed852e2009-09-05 21:47:34 +0000203#define CacheShift 2
cristye1287512010-06-19 17:38:25 +0000204#else
205#define CacheShift 3
206#endif
cristy3ed852e2009-09-05 21:47:34 +0000207#define ErrorQueueLength 16
208#define MaxNodes 266817
209#define MaxTreeDepth 8
210#define NodesInAList 1920
211
212/*
213 Typdef declarations.
214*/
215typedef struct _RealPixelPacket
216{
217 MagickRealType
218 red,
219 green,
220 blue,
221 opacity;
222} RealPixelPacket;
223
224typedef struct _NodeInfo
225{
226 struct _NodeInfo
227 *parent,
228 *child[16];
229
230 MagickSizeType
231 number_unique;
232
233 RealPixelPacket
234 total_color;
235
236 MagickRealType
237 quantize_error;
238
cristybb503372010-05-27 20:51:26 +0000239 size_t
cristy3ed852e2009-09-05 21:47:34 +0000240 color_number,
241 id,
242 level;
243} NodeInfo;
244
245typedef struct _Nodes
246{
247 NodeInfo
248 *nodes;
249
250 struct _Nodes
251 *next;
252} Nodes;
253
254typedef struct _CubeInfo
255{
256 NodeInfo
257 *root;
258
cristybb503372010-05-27 20:51:26 +0000259 size_t
cristy3ed852e2009-09-05 21:47:34 +0000260 colors,
261 maximum_colors;
262
cristybb503372010-05-27 20:51:26 +0000263 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000264 transparent_index;
265
266 MagickSizeType
267 transparent_pixels;
268
269 RealPixelPacket
270 target;
271
272 MagickRealType
273 distance,
274 pruning_threshold,
275 next_threshold;
276
cristybb503372010-05-27 20:51:26 +0000277 size_t
cristy3ed852e2009-09-05 21:47:34 +0000278 nodes,
279 free_nodes,
280 color_number;
281
282 NodeInfo
283 *next_node;
284
285 Nodes
286 *node_queue;
287
cristybb503372010-05-27 20:51:26 +0000288 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000289 *cache;
290
291 RealPixelPacket
292 error[ErrorQueueLength];
293
294 MagickRealType
295 weights[ErrorQueueLength];
296
297 QuantizeInfo
298 *quantize_info;
299
300 MagickBooleanType
301 associate_alpha;
302
cristybb503372010-05-27 20:51:26 +0000303 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000304 x,
305 y;
306
cristybb503372010-05-27 20:51:26 +0000307 size_t
cristy3ed852e2009-09-05 21:47:34 +0000308 depth;
309
310 MagickOffsetType
311 offset;
312
313 MagickSizeType
314 span;
315} CubeInfo;
316
317/*
318 Method prototypes.
319*/
320static CubeInfo
cristybb503372010-05-27 20:51:26 +0000321 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
cristy3ed852e2009-09-05 21:47:34 +0000322
323static NodeInfo
cristybb503372010-05-27 20:51:26 +0000324 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
cristy3ed852e2009-09-05 21:47:34 +0000325
326static MagickBooleanType
327 AssignImageColors(Image *,CubeInfo *),
328 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
329 DitherImage(Image *,CubeInfo *),
330 SetGrayscaleImage(Image *);
331
cristybb503372010-05-27 20:51:26 +0000332static size_t
cristy3ed852e2009-09-05 21:47:34 +0000333 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
334
335static void
336 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
337 DestroyCubeInfo(CubeInfo *),
338 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
339 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
340 ReduceImageColors(const Image *,CubeInfo *);
341
342/*
343%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
344% %
345% %
346% %
347% A c q u i r e Q u a n t i z e I n f o %
348% %
349% %
350% %
351%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
352%
353% AcquireQuantizeInfo() allocates the QuantizeInfo structure.
354%
355% The format of the AcquireQuantizeInfo method is:
356%
357% QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
358%
359% A description of each parameter follows:
360%
361% o image_info: the image info.
362%
363*/
364MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
365{
366 QuantizeInfo
367 *quantize_info;
368
cristy90823212009-12-12 20:48:33 +0000369 quantize_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*quantize_info));
cristy3ed852e2009-09-05 21:47:34 +0000370 if (quantize_info == (QuantizeInfo *) NULL)
371 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
372 GetQuantizeInfo(quantize_info);
373 if (image_info != (ImageInfo *) NULL)
374 {
375 const char
376 *option;
377
378 quantize_info->dither=image_info->dither;
379 option=GetImageOption(image_info,"dither");
380 if (option != (const char *) NULL)
381 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
382 MagickDitherOptions,MagickFalse,option);
383 quantize_info->measure_error=image_info->verbose;
384 }
385 return(quantize_info);
386}
387
388/*
389%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
390% %
391% %
392% %
393+ A s s i g n I m a g e C o l o r s %
394% %
395% %
396% %
397%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
398%
399% AssignImageColors() generates the output image from the pruned tree. The
400% output image consists of two parts: (1) A color map, which is an array
401% of color descriptions (RGB triples) for each color present in the
402% output image; (2) A pixel array, which represents each pixel as an
403% index into the color map array.
404%
405% First, the assignment phase makes one pass over the pruned color
406% description tree to establish the image's color map. For each node
407% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
408% color of all pixels that classify no lower than this node. Each of
409% these colors becomes an entry in the color map.
410%
411% Finally, the assignment phase reclassifies each pixel in the pruned
412% tree to identify the deepest node containing the pixel's color. The
413% pixel's value in the pixel array becomes the index of this node's mean
414% color in the color map.
415%
416% The format of the AssignImageColors() method is:
417%
418% MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
419%
420% A description of each parameter follows.
421%
422% o image: the image.
423%
424% o cube_info: A pointer to the Cube structure.
425%
426*/
427
428static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
429 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
430{
431 MagickRealType
432 alpha;
433
434 if ((cube_info->associate_alpha == MagickFalse) ||
435 (pixel->opacity == OpaqueOpacity))
436 {
437 alpha_pixel->red=(MagickRealType) pixel->red;
438 alpha_pixel->green=(MagickRealType) pixel->green;
439 alpha_pixel->blue=(MagickRealType) pixel->blue;
440 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
441 return;
442 }
443 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
444 alpha_pixel->red=alpha*pixel->red;
445 alpha_pixel->green=alpha*pixel->green;
446 alpha_pixel->blue=alpha*pixel->blue;
447 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
448}
449
cristy75ffdb72010-01-07 17:40:12 +0000450static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
cristy3ed852e2009-09-05 21:47:34 +0000451{
452 if (value <= 0.0)
453 return((Quantum) 0);
454 if (value >= QuantumRange)
455 return((Quantum) QuantumRange);
456 return((Quantum) (value+0.5));
457}
458
cristybb503372010-05-27 20:51:26 +0000459static inline size_t ColorToNodeId(const CubeInfo *cube_info,
460 const RealPixelPacket *pixel,size_t index)
cristy3ed852e2009-09-05 21:47:34 +0000461{
cristybb503372010-05-27 20:51:26 +0000462 size_t
cristy3ed852e2009-09-05 21:47:34 +0000463 id;
464
cristybb503372010-05-27 20:51:26 +0000465 id=(size_t) (
cristy75ffdb72010-01-07 17:40:12 +0000466 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
467 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
468 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
cristy3ed852e2009-09-05 21:47:34 +0000469 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +0000470 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
cristy3ed852e2009-09-05 21:47:34 +0000471 << 3;
472 return(id);
473}
474
475static inline MagickBooleanType IsSameColor(const Image *image,
476 const PixelPacket *p,const PixelPacket *q)
477{
478 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
479 return(MagickFalse);
480 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
481 return(MagickFalse);
482 return(MagickTrue);
483}
484
485static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
486{
487#define AssignImageTag "Assign/Image"
488
cristybb503372010-05-27 20:51:26 +0000489 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000490 y;
491
492 MagickBooleanType
493 proceed;
494
495 RealPixelPacket
496 pixel;
497
cristybb503372010-05-27 20:51:26 +0000498 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000499 i,
500 x;
501
502 register const NodeInfo
503 *node_info;
504
505 ssize_t
506 count;
507
cristybb503372010-05-27 20:51:26 +0000508 size_t
cristy3ed852e2009-09-05 21:47:34 +0000509 id,
510 index;
511
512 /*
513 Allocate image colormap.
514 */
515 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
516 (cube_info->quantize_info->colorspace != CMYKColorspace))
517 (void) TransformImageColorspace((Image *) image,
518 cube_info->quantize_info->colorspace);
519 else
520 if ((image->colorspace != GRAYColorspace) &&
521 (image->colorspace != RGBColorspace) &&
522 (image->colorspace != CMYColorspace))
523 (void) TransformImageColorspace((Image *) image,RGBColorspace);
524 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
525 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
526 image->filename);
527 image->colors=0;
528 cube_info->transparent_pixels=0;
529 cube_info->transparent_index=(-1);
530 (void) DefineImageColormap(image,cube_info,cube_info->root);
531 /*
532 Create a reduced color image.
533 */
534 if ((cube_info->quantize_info->dither != MagickFalse) &&
cristyd5acfd12010-06-15 00:11:38 +0000535 (cube_info->quantize_info->dither_method != NoDitherMethod))
cristy3ed852e2009-09-05 21:47:34 +0000536 (void) DitherImage(image,cube_info);
537 else
538 {
539 ExceptionInfo
540 *exception;
541
542 CacheView
543 *image_view;
544
545 exception=(&image->exception);
546 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +0000547 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000548 {
549 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +0000550 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +0000551
552 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000553 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000554
555 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
556 exception);
557 if (q == (PixelPacket *) NULL)
558 break;
559 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +0000560 for (x=0; x < (ssize_t) image->columns; x+=count)
cristy3ed852e2009-09-05 21:47:34 +0000561 {
562 /*
563 Identify the deepest node containing the pixel's color.
564 */
cristybb503372010-05-27 20:51:26 +0000565 for (count=1; (x+count) < (ssize_t) image->columns; count++)
cristy3ed852e2009-09-05 21:47:34 +0000566 if (IsSameColor(image,q,q+count) == MagickFalse)
567 break;
568 AssociateAlphaPixel(cube_info,q,&pixel);
569 node_info=cube_info->root;
cristybb503372010-05-27 20:51:26 +0000570 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +0000571 {
572 id=ColorToNodeId(cube_info,&pixel,index);
573 if (node_info->child[id] == (NodeInfo *) NULL)
574 break;
575 node_info=node_info->child[id];
576 }
577 /*
578 Find closest color among siblings and their children.
579 */
580 cube_info->target=pixel;
581 cube_info->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
582 (QuantumRange+1.0)+1.0);
583 ClosestColor(image,cube_info,node_info->parent);
584 index=cube_info->color_number;
cristybb503372010-05-27 20:51:26 +0000585 for (i=0; i < (ssize_t) count; i++)
cristy3ed852e2009-09-05 21:47:34 +0000586 {
587 if (image->storage_class == PseudoClass)
588 indexes[x+i]=(IndexPacket) index;
589 if (cube_info->quantize_info->measure_error == MagickFalse)
590 {
591 q->red=image->colormap[index].red;
592 q->green=image->colormap[index].green;
593 q->blue=image->colormap[index].blue;
594 if (cube_info->associate_alpha != MagickFalse)
595 q->opacity=image->colormap[index].opacity;
596 }
597 q++;
598 }
599 }
600 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
601 break;
cristycee97112010-05-28 00:44:52 +0000602 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
603 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000604 if (proceed == MagickFalse)
605 break;
606 }
607 image_view=DestroyCacheView(image_view);
608 }
609 if (cube_info->quantize_info->measure_error != MagickFalse)
610 (void) GetImageQuantizeError(image);
611 if ((cube_info->quantize_info->number_colors == 2) &&
612 (cube_info->quantize_info->colorspace == GRAYColorspace))
613 {
614 Quantum
615 intensity;
616
617 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000618 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000619
620 /*
621 Monochrome image.
622 */
623 q=image->colormap;
cristybb503372010-05-27 20:51:26 +0000624 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +0000625 {
626 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
627 QuantumRange/2.0) ? 0 : QuantumRange);
628 q->red=intensity;
629 q->green=intensity;
630 q->blue=intensity;
631 q++;
632 }
633 }
634 (void) SyncImage(image);
635 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
636 (cube_info->quantize_info->colorspace != CMYKColorspace))
637 (void) TransformImageColorspace((Image *) image,RGBColorspace);
638 return(MagickTrue);
639}
640
641/*
642%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
643% %
644% %
645% %
646+ C l a s s i f y I m a g e C o l o r s %
647% %
648% %
649% %
650%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
651%
652% ClassifyImageColors() begins by initializing a color description tree
653% of sufficient depth to represent each possible input color in a leaf.
654% However, it is impractical to generate a fully-formed color
655% description tree in the storage_class phase for realistic values of
656% Cmax. If colors components in the input image are quantized to k-bit
657% precision, so that Cmax= 2k-1, the tree would need k levels below the
658% root node to allow representing each possible input color in a leaf.
659% This becomes prohibitive because the tree's total number of nodes is
660% 1 + sum(i=1,k,8k).
661%
662% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
663% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
664% Initializes data structures for nodes only as they are needed; (2)
665% Chooses a maximum depth for the tree as a function of the desired
666% number of colors in the output image (currently log2(colormap size)).
667%
668% For each pixel in the input image, storage_class scans downward from
669% the root of the color description tree. At each level of the tree it
670% identifies the single node which represents a cube in RGB space
671% containing It updates the following data for each such node:
672%
673% n1 : Number of pixels whose color is contained in the RGB cube
674% which this node represents;
675%
676% n2 : Number of pixels whose color is not represented in a node at
677% lower depth in the tree; initially, n2 = 0 for all nodes except
678% leaves of the tree.
679%
680% Sr, Sg, Sb : Sums of the red, green, and blue component values for
681% all pixels not classified at a lower depth. The combination of
682% these sums and n2 will ultimately characterize the mean color of a
683% set of pixels represented by this node.
684%
685% E: the distance squared in RGB space between each pixel contained
686% within a node and the nodes' center. This represents the quantization
687% error for a node.
688%
689% The format of the ClassifyImageColors() method is:
690%
691% MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
692% const Image *image,ExceptionInfo *exception)
693%
694% A description of each parameter follows.
695%
696% o cube_info: A pointer to the Cube structure.
697%
698% o image: the image.
699%
700*/
701
702static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
703{
704 MagickBooleanType
705 associate_alpha;
706
707 associate_alpha=image->matte;
708 if (cube_info->quantize_info->colorspace == TransparentColorspace)
709 associate_alpha=MagickFalse;
710 if ((cube_info->quantize_info->number_colors == 2) &&
711 (cube_info->quantize_info->colorspace == GRAYColorspace))
712 associate_alpha=MagickFalse;
713 cube_info->associate_alpha=associate_alpha;
714}
715
716static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
717 const Image *image,ExceptionInfo *exception)
718{
719#define ClassifyImageTag "Classify/Image"
720
cristyc4c8d132010-01-07 01:58:38 +0000721 CacheView
722 *image_view;
723
cristybb503372010-05-27 20:51:26 +0000724 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000725 y;
726
727 MagickBooleanType
728 proceed;
729
730 MagickRealType
731 bisect;
732
733 NodeInfo
734 *node_info;
735
736 RealPixelPacket
737 error,
738 mid,
739 midpoint,
740 pixel;
741
742 size_t
743 count;
744
cristybb503372010-05-27 20:51:26 +0000745 size_t
cristy3ed852e2009-09-05 21:47:34 +0000746 id,
747 index,
748 level;
749
cristy3ed852e2009-09-05 21:47:34 +0000750 /*
751 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
752 */
753 SetAssociatedAlpha(image,cube_info);
754 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
755 (cube_info->quantize_info->colorspace != CMYKColorspace))
756 (void) TransformImageColorspace((Image *) image,
757 cube_info->quantize_info->colorspace);
758 else
759 if ((image->colorspace != GRAYColorspace) &&
760 (image->colorspace != CMYColorspace) &&
761 (image->colorspace != RGBColorspace))
762 (void) TransformImageColorspace((Image *) image,RGBColorspace);
763 midpoint.red=(MagickRealType) QuantumRange/2.0;
764 midpoint.green=(MagickRealType) QuantumRange/2.0;
765 midpoint.blue=(MagickRealType) QuantumRange/2.0;
766 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
767 error.opacity=0.0;
768 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +0000769 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000770 {
771 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000772 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000773
cristybb503372010-05-27 20:51:26 +0000774 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000775 x;
776
777 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
778 if (p == (const PixelPacket *) NULL)
779 break;
780 if (cube_info->nodes > MaxNodes)
781 {
782 /*
783 Prune one level if the color tree is too large.
784 */
785 PruneLevel(image,cube_info,cube_info->root);
786 cube_info->depth--;
787 }
cristybb503372010-05-27 20:51:26 +0000788 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
cristy3ed852e2009-09-05 21:47:34 +0000789 {
790 /*
791 Start at the root and descend the color cube tree.
792 */
cristyecd0ab52010-05-30 14:59:20 +0000793 for (count=1; (x+count) < (ssize_t) image->columns; count++)
cristy3ed852e2009-09-05 21:47:34 +0000794 if (IsSameColor(image,p,p+count) == MagickFalse)
795 break;
796 AssociateAlphaPixel(cube_info,p,&pixel);
797 index=MaxTreeDepth-1;
798 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
799 mid=midpoint;
800 node_info=cube_info->root;
801 for (level=1; level <= MaxTreeDepth; level++)
802 {
803 bisect*=0.5;
804 id=ColorToNodeId(cube_info,&pixel,index);
805 mid.red+=(id & 1) != 0 ? bisect : -bisect;
806 mid.green+=(id & 2) != 0 ? bisect : -bisect;
807 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
808 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
809 if (node_info->child[id] == (NodeInfo *) NULL)
810 {
811 /*
812 Set colors of new node to contain pixel.
813 */
814 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
815 if (node_info->child[id] == (NodeInfo *) NULL)
816 (void) ThrowMagickException(exception,GetMagickModule(),
817 ResourceLimitError,"MemoryAllocationFailed","`%s'",
818 image->filename);
819 if (level == MaxTreeDepth)
820 cube_info->colors++;
821 }
822 /*
823 Approximate the quantization error represented by this node.
824 */
825 node_info=node_info->child[id];
826 error.red=QuantumScale*(pixel.red-mid.red);
827 error.green=QuantumScale*(pixel.green-mid.green);
828 error.blue=QuantumScale*(pixel.blue-mid.blue);
829 if (cube_info->associate_alpha != MagickFalse)
830 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
831 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
832 count*error.green*error.green+count*error.blue*error.blue+
833 count*error.opacity*error.opacity));
834 cube_info->root->quantize_error+=node_info->quantize_error;
835 index--;
836 }
837 /*
838 Sum RGB for this leaf for later derivation of the mean cube color.
839 */
840 node_info->number_unique+=count;
841 node_info->total_color.red+=count*QuantumScale*pixel.red;
842 node_info->total_color.green+=count*QuantumScale*pixel.green;
843 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
844 if (cube_info->associate_alpha != MagickFalse)
845 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
846 p+=count;
847 }
848 if (cube_info->colors > cube_info->maximum_colors)
849 {
850 PruneToCubeDepth(image,cube_info,cube_info->root);
851 break;
852 }
cristycee97112010-05-28 00:44:52 +0000853 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
854 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000855 if (proceed == MagickFalse)
856 break;
857 }
cristybb503372010-05-27 20:51:26 +0000858 for (y++; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000859 {
860 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000861 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000862
cristybb503372010-05-27 20:51:26 +0000863 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000864 x;
865
866 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
867 if (p == (const PixelPacket *) NULL)
868 break;
869 if (cube_info->nodes > MaxNodes)
870 {
871 /*
872 Prune one level if the color tree is too large.
873 */
874 PruneLevel(image,cube_info,cube_info->root);
875 cube_info->depth--;
876 }
cristybb503372010-05-27 20:51:26 +0000877 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
cristy3ed852e2009-09-05 21:47:34 +0000878 {
879 /*
880 Start at the root and descend the color cube tree.
881 */
cristyecd0ab52010-05-30 14:59:20 +0000882 for (count=1; (x+count) < (ssize_t) image->columns; count++)
cristy3ed852e2009-09-05 21:47:34 +0000883 if (IsSameColor(image,p,p+count) == MagickFalse)
884 break;
885 AssociateAlphaPixel(cube_info,p,&pixel);
886 index=MaxTreeDepth-1;
887 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
888 mid=midpoint;
889 node_info=cube_info->root;
890 for (level=1; level <= cube_info->depth; level++)
891 {
892 bisect*=0.5;
893 id=ColorToNodeId(cube_info,&pixel,index);
894 mid.red+=(id & 1) != 0 ? bisect : -bisect;
895 mid.green+=(id & 2) != 0 ? bisect : -bisect;
896 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
897 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
898 if (node_info->child[id] == (NodeInfo *) NULL)
899 {
900 /*
901 Set colors of new node to contain pixel.
902 */
903 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
904 if (node_info->child[id] == (NodeInfo *) NULL)
905 (void) ThrowMagickException(exception,GetMagickModule(),
906 ResourceLimitError,"MemoryAllocationFailed","%s",
907 image->filename);
908 if (level == cube_info->depth)
909 cube_info->colors++;
910 }
911 /*
912 Approximate the quantization error represented by this node.
913 */
914 node_info=node_info->child[id];
915 error.red=QuantumScale*(pixel.red-mid.red);
916 error.green=QuantumScale*(pixel.green-mid.green);
917 error.blue=QuantumScale*(pixel.blue-mid.blue);
918 if (cube_info->associate_alpha != MagickFalse)
919 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
920 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
921 count*error.green*error.green+error.blue*error.blue+
922 count*error.opacity*error.opacity));
923 cube_info->root->quantize_error+=node_info->quantize_error;
924 index--;
925 }
926 /*
927 Sum RGB for this leaf for later derivation of the mean cube color.
928 */
929 node_info->number_unique+=count;
930 node_info->total_color.red+=count*QuantumScale*pixel.red;
931 node_info->total_color.green+=count*QuantumScale*pixel.green;
932 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
933 if (cube_info->associate_alpha != MagickFalse)
934 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
935 p+=count;
936 }
cristycee97112010-05-28 00:44:52 +0000937 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
938 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000939 if (proceed == MagickFalse)
940 break;
941 }
942 image_view=DestroyCacheView(image_view);
943 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
944 (cube_info->quantize_info->colorspace != CMYKColorspace))
945 (void) TransformImageColorspace((Image *) image,RGBColorspace);
946 return(MagickTrue);
947}
948
949/*
950%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
951% %
952% %
953% %
954% C l o n e Q u a n t i z e I n f o %
955% %
956% %
957% %
958%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
959%
960% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
961% or if quantize info is NULL, a new one.
962%
963% The format of the CloneQuantizeInfo method is:
964%
965% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
966%
967% A description of each parameter follows:
968%
969% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
970% quantize info, or if image info is NULL a new one.
971%
972% o quantize_info: a structure of type info.
973%
974*/
975MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
976{
977 QuantizeInfo
978 *clone_info;
979
cristy90823212009-12-12 20:48:33 +0000980 clone_info=(QuantizeInfo *) AcquireAlignedMemory(1,sizeof(*clone_info));
cristy3ed852e2009-09-05 21:47:34 +0000981 if (clone_info == (QuantizeInfo *) NULL)
982 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
983 GetQuantizeInfo(clone_info);
984 if (quantize_info == (QuantizeInfo *) NULL)
985 return(clone_info);
986 clone_info->number_colors=quantize_info->number_colors;
987 clone_info->tree_depth=quantize_info->tree_depth;
988 clone_info->dither=quantize_info->dither;
989 clone_info->dither_method=quantize_info->dither_method;
990 clone_info->colorspace=quantize_info->colorspace;
991 clone_info->measure_error=quantize_info->measure_error;
992 return(clone_info);
993}
994
995/*
996%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
997% %
998% %
999% %
1000+ C l o s e s t C o l o r %
1001% %
1002% %
1003% %
1004%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1005%
1006% ClosestColor() traverses the color cube tree at a particular node and
1007% determines which colormap entry best represents the input color.
1008%
1009% The format of the ClosestColor method is:
1010%
1011% void ClosestColor(const Image *image,CubeInfo *cube_info,
1012% const NodeInfo *node_info)
1013%
1014% A description of each parameter follows.
1015%
1016% o image: the image.
1017%
1018% o cube_info: A pointer to the Cube structure.
1019%
1020% o node_info: the address of a structure of type NodeInfo which points to a
1021% node in the color cube tree that is to be pruned.
1022%
1023*/
1024static void ClosestColor(const Image *image,CubeInfo *cube_info,
1025 const NodeInfo *node_info)
1026{
cristybb503372010-05-27 20:51:26 +00001027 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001028 i;
1029
cristybb503372010-05-27 20:51:26 +00001030 size_t
cristy3ed852e2009-09-05 21:47:34 +00001031 number_children;
1032
1033 /*
1034 Traverse any children.
1035 */
1036 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00001037 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00001038 if (node_info->child[i] != (NodeInfo *) NULL)
1039 ClosestColor(image,cube_info,node_info->child[i]);
1040 if (node_info->number_unique != 0)
1041 {
1042 MagickRealType
1043 pixel;
1044
1045 register MagickRealType
1046 alpha,
1047 beta,
1048 distance;
1049
1050 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001051 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00001052
1053 register RealPixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001054 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001055
1056 /*
1057 Determine if this color is "closest".
1058 */
1059 p=image->colormap+node_info->color_number;
1060 q=(&cube_info->target);
1061 alpha=1.0;
1062 beta=1.0;
1063 if (cube_info->associate_alpha == MagickFalse)
1064 {
cristy46f08202010-01-10 04:04:21 +00001065 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1066 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
cristy3ed852e2009-09-05 21:47:34 +00001067 }
1068 pixel=alpha*p->red-beta*q->red;
1069 distance=pixel*pixel;
1070 if (distance < cube_info->distance)
1071 {
1072 pixel=alpha*p->green-beta*q->green;
1073 distance+=pixel*pixel;
1074 if (distance < cube_info->distance)
1075 {
1076 pixel=alpha*p->blue-beta*q->blue;
1077 distance+=pixel*pixel;
1078 if (distance < cube_info->distance)
1079 {
1080 pixel=alpha-beta;
1081 distance+=pixel*pixel;
1082 if (distance < cube_info->distance)
1083 {
1084 cube_info->distance=distance;
1085 cube_info->color_number=node_info->color_number;
1086 }
1087 }
1088 }
1089 }
1090 }
1091}
1092
1093/*
1094%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1095% %
1096% %
1097% %
1098% C o m p r e s s I m a g e C o l o r m a p %
1099% %
1100% %
1101% %
1102%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1103%
1104% CompressImageColormap() compresses an image colormap by removing any
1105% duplicate or unused color entries.
1106%
1107% The format of the CompressImageColormap method is:
1108%
1109% MagickBooleanType CompressImageColormap(Image *image)
1110%
1111% A description of each parameter follows:
1112%
1113% o image: the image.
1114%
1115*/
1116MagickExport MagickBooleanType CompressImageColormap(Image *image)
1117{
1118 QuantizeInfo
1119 quantize_info;
1120
1121 assert(image != (Image *) NULL);
1122 assert(image->signature == MagickSignature);
1123 if (image->debug != MagickFalse)
1124 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1125 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1126 return(MagickFalse);
1127 GetQuantizeInfo(&quantize_info);
1128 quantize_info.number_colors=image->colors;
1129 quantize_info.tree_depth=MaxTreeDepth;
1130 return(QuantizeImage(&quantize_info,image));
1131}
1132
1133/*
1134%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1135% %
1136% %
1137% %
1138+ D e f i n e I m a g e C o l o r m a p %
1139% %
1140% %
1141% %
1142%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1143%
1144% DefineImageColormap() traverses the color cube tree and notes each colormap
1145% entry. A colormap entry is any node in the color cube tree where the
1146% of unique colors is not zero. DefineImageColormap() returns the number of
1147% colors in the image colormap.
1148%
1149% The format of the DefineImageColormap method is:
1150%
cristybb503372010-05-27 20:51:26 +00001151% size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
cristy3ed852e2009-09-05 21:47:34 +00001152% NodeInfo *node_info)
1153%
1154% A description of each parameter follows.
1155%
1156% o image: the image.
1157%
1158% o cube_info: A pointer to the Cube structure.
1159%
1160% o node_info: the address of a structure of type NodeInfo which points to a
1161% node in the color cube tree that is to be pruned.
1162%
1163*/
cristybb503372010-05-27 20:51:26 +00001164static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
cristy3ed852e2009-09-05 21:47:34 +00001165 NodeInfo *node_info)
1166{
cristybb503372010-05-27 20:51:26 +00001167 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001168 i;
1169
cristybb503372010-05-27 20:51:26 +00001170 size_t
cristy3ed852e2009-09-05 21:47:34 +00001171 number_children;
1172
1173 /*
1174 Traverse any children.
1175 */
1176 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00001177 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00001178 if (node_info->child[i] != (NodeInfo *) NULL)
cristycee97112010-05-28 00:44:52 +00001179 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
cristy3ed852e2009-09-05 21:47:34 +00001180 if (node_info->number_unique != 0)
1181 {
1182 register MagickRealType
1183 alpha;
1184
1185 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001186 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001187
1188 /*
1189 Colormap entry is defined by the mean color in this cube.
1190 */
1191 q=image->colormap+image->colors;
1192 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1193 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1194 if (cube_info->associate_alpha == MagickFalse)
1195 {
cristyce70c172010-01-07 17:15:30 +00001196 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001197 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001198 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001199 node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001200 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001201 node_info->total_color.blue));
cristyce70c172010-01-07 17:15:30 +00001202 SetOpacityPixelComponent(q,OpaqueOpacity);
cristy3ed852e2009-09-05 21:47:34 +00001203 }
1204 else
1205 {
1206 MagickRealType
1207 opacity;
1208
1209 opacity=(MagickRealType) (alpha*QuantumRange*
1210 node_info->total_color.opacity);
cristyce70c172010-01-07 17:15:30 +00001211 q->opacity=ClampToQuantum(opacity);
cristy3ed852e2009-09-05 21:47:34 +00001212 if (q->opacity == OpaqueOpacity)
1213 {
cristyce70c172010-01-07 17:15:30 +00001214 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001215 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001216 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001217 node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001218 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001219 node_info->total_color.blue));
1220 }
1221 else
1222 {
1223 MagickRealType
1224 gamma;
1225
1226 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1227 (MagickRealType) q->opacity));
1228 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
cristyce70c172010-01-07 17:15:30 +00001229 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001230 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001231 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
cristy3ed852e2009-09-05 21:47:34 +00001232 QuantumRange*node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001233 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001234 node_info->total_color.blue));
1235 if (node_info->number_unique > cube_info->transparent_pixels)
1236 {
1237 cube_info->transparent_pixels=node_info->number_unique;
cristybb503372010-05-27 20:51:26 +00001238 cube_info->transparent_index=(ssize_t) image->colors;
cristy3ed852e2009-09-05 21:47:34 +00001239 }
1240 }
1241 }
1242 node_info->color_number=image->colors++;
1243 }
1244 return(image->colors);
1245}
1246
1247/*
1248%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1249% %
1250% %
1251% %
1252+ D e s t r o y C u b e I n f o %
1253% %
1254% %
1255% %
1256%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1257%
1258% DestroyCubeInfo() deallocates memory associated with an image.
1259%
1260% The format of the DestroyCubeInfo method is:
1261%
1262% DestroyCubeInfo(CubeInfo *cube_info)
1263%
1264% A description of each parameter follows:
1265%
1266% o cube_info: the address of a structure of type CubeInfo.
1267%
1268*/
1269static void DestroyCubeInfo(CubeInfo *cube_info)
1270{
1271 register Nodes
1272 *nodes;
1273
1274 /*
1275 Release color cube tree storage.
1276 */
1277 do
1278 {
1279 nodes=cube_info->node_queue->next;
1280 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1281 cube_info->node_queue->nodes);
1282 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1283 cube_info->node_queue);
1284 cube_info->node_queue=nodes;
1285 } while (cube_info->node_queue != (Nodes *) NULL);
cristybb503372010-05-27 20:51:26 +00001286 if (cube_info->cache != (ssize_t *) NULL)
1287 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
cristy3ed852e2009-09-05 21:47:34 +00001288 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1289 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1290}
1291
1292/*
1293%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1294% %
1295% %
1296% %
1297% D e s t r o y Q u a n t i z e I n f o %
1298% %
1299% %
1300% %
1301%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1302%
1303% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1304% structure.
1305%
1306% The format of the DestroyQuantizeInfo method is:
1307%
1308% QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1309%
1310% A description of each parameter follows:
1311%
1312% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1313%
1314*/
1315MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1316{
1317 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1318 assert(quantize_info != (QuantizeInfo *) NULL);
1319 assert(quantize_info->signature == MagickSignature);
1320 quantize_info->signature=(~MagickSignature);
1321 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1322 return(quantize_info);
1323}
1324
1325/*
1326%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1327% %
1328% %
1329% %
1330+ D i t h e r I m a g e %
1331% %
1332% %
1333% %
1334%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1335%
1336% DitherImage() distributes the difference between an original image and
1337% the corresponding color reduced algorithm to neighboring pixels using
1338% serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1339% MagickTrue if the image is dithered otherwise MagickFalse.
1340%
1341% The format of the DitherImage method is:
1342%
1343% MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1344%
1345% A description of each parameter follows.
1346%
1347% o image: the image.
1348%
1349% o cube_info: A pointer to the Cube structure.
1350%
1351*/
1352
1353static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1354{
1355#define DitherImageTag "Dither/Image"
1356
cristyc4c8d132010-01-07 01:58:38 +00001357 CacheView
1358 *image_view;
1359
cristy3ed852e2009-09-05 21:47:34 +00001360 ExceptionInfo
1361 *exception;
1362
cristybb503372010-05-27 20:51:26 +00001363 ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001364 u,
1365 v,
1366 y;
1367
1368 MagickBooleanType
1369 proceed;
1370
1371 RealPixelPacket
1372 color,
1373 *current,
1374 pixel,
1375 *previous,
1376 *scanlines;
1377
1378 register CubeInfo
1379 *p;
1380
cristybb503372010-05-27 20:51:26 +00001381 size_t
cristy3ed852e2009-09-05 21:47:34 +00001382 index;
1383
cristy3ed852e2009-09-05 21:47:34 +00001384 /*
1385 Distribute quantization error using Floyd-Steinberg.
1386 */
1387 scanlines=(RealPixelPacket *) AcquireQuantumMemory(image->columns,
1388 2*sizeof(*scanlines));
1389 if (scanlines == (RealPixelPacket *) NULL)
1390 return(MagickFalse);
1391 p=cube_info;
1392 exception=(&image->exception);
1393 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +00001394 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00001395 {
1396 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00001397 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00001398
cristybb503372010-05-27 20:51:26 +00001399 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001400 i,
1401 x;
1402
1403 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001404 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001405
1406 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1407 if (q == (PixelPacket *) NULL)
1408 return(MagickFalse);
1409 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1410 current=scanlines+(y & 0x01)*image->columns;
1411 previous=scanlines+((y+1) & 0x01)*image->columns;
cristycee97112010-05-28 00:44:52 +00001412 v=(ssize_t) ((y & 0x01) ? -1 : 1);
cristybb503372010-05-27 20:51:26 +00001413 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00001414 {
cristybb503372010-05-27 20:51:26 +00001415 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
cristy3ed852e2009-09-05 21:47:34 +00001416 AssociateAlphaPixel(cube_info,q+u,&pixel);
1417 if (x > 0)
1418 {
1419 pixel.red+=7*current[u-v].red/16;
1420 pixel.green+=7*current[u-v].green/16;
1421 pixel.blue+=7*current[u-v].blue/16;
1422 if (cube_info->associate_alpha != MagickFalse)
1423 pixel.opacity+=7*current[u-v].opacity/16;
1424 }
1425 if (y > 0)
1426 {
cristybb503372010-05-27 20:51:26 +00001427 if (x < (ssize_t) (image->columns-1))
cristy3ed852e2009-09-05 21:47:34 +00001428 {
1429 pixel.red+=previous[u+v].red/16;
1430 pixel.green+=previous[u+v].green/16;
1431 pixel.blue+=previous[u+v].blue/16;
1432 if (cube_info->associate_alpha != MagickFalse)
1433 pixel.opacity+=previous[u+v].opacity/16;
1434 }
1435 pixel.red+=5*previous[u].red/16;
1436 pixel.green+=5*previous[u].green/16;
1437 pixel.blue+=5*previous[u].blue/16;
1438 if (cube_info->associate_alpha != MagickFalse)
1439 pixel.opacity+=5*previous[u].opacity/16;
1440 if (x > 0)
1441 {
1442 pixel.red+=3*previous[u-v].red/16;
1443 pixel.green+=3*previous[u-v].green/16;
1444 pixel.blue+=3*previous[u-v].blue/16;
1445 if (cube_info->associate_alpha != MagickFalse)
1446 pixel.opacity+=3*previous[u-v].opacity/16;
1447 }
1448 }
cristy75ffdb72010-01-07 17:40:12 +00001449 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1450 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1451 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristy3ed852e2009-09-05 21:47:34 +00001452 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001453 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
cristybb503372010-05-27 20:51:26 +00001454 i=(ssize_t) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
cristy75ffdb72010-01-07 17:40:12 +00001455 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1456 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
cristy3ed852e2009-09-05 21:47:34 +00001457 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001458 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
cristy3ed852e2009-09-05 21:47:34 +00001459 << 18);
1460 if (p->cache[i] < 0)
1461 {
1462 register NodeInfo
1463 *node_info;
1464
cristybb503372010-05-27 20:51:26 +00001465 register size_t
cristy3ed852e2009-09-05 21:47:34 +00001466 id;
1467
1468 /*
1469 Identify the deepest node containing the pixel's color.
1470 */
1471 node_info=p->root;
cristybb503372010-05-27 20:51:26 +00001472 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +00001473 {
1474 id=ColorToNodeId(cube_info,&pixel,index);
1475 if (node_info->child[id] == (NodeInfo *) NULL)
1476 break;
1477 node_info=node_info->child[id];
1478 }
1479 /*
1480 Find closest color among siblings and their children.
1481 */
1482 p->target=pixel;
1483 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
1484 1.0)+1.0);
1485 ClosestColor(image,p,node_info->parent);
cristybb503372010-05-27 20:51:26 +00001486 p->cache[i]=(ssize_t) p->color_number;
cristy3ed852e2009-09-05 21:47:34 +00001487 }
1488 /*
1489 Assign pixel to closest colormap entry.
1490 */
cristybb503372010-05-27 20:51:26 +00001491 index=(size_t) p->cache[i];
cristy3ed852e2009-09-05 21:47:34 +00001492 if (image->storage_class == PseudoClass)
1493 indexes[u]=(IndexPacket) index;
1494 if (cube_info->quantize_info->measure_error == MagickFalse)
1495 {
1496 (q+u)->red=image->colormap[index].red;
1497 (q+u)->green=image->colormap[index].green;
1498 (q+u)->blue=image->colormap[index].blue;
1499 if (cube_info->associate_alpha != MagickFalse)
1500 (q+u)->opacity=image->colormap[index].opacity;
1501 }
1502 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1503 return(MagickFalse);
1504 /*
1505 Store the error.
1506 */
1507 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1508 current[u].red=pixel.red-color.red;
1509 current[u].green=pixel.green-color.green;
1510 current[u].blue=pixel.blue-color.blue;
1511 if (cube_info->associate_alpha != MagickFalse)
1512 current[u].opacity=pixel.opacity-color.opacity;
1513 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1514 if (proceed == MagickFalse)
1515 return(MagickFalse);
1516 p->offset++;
1517 }
1518 }
1519 scanlines=(RealPixelPacket *) RelinquishMagickMemory(scanlines);
1520 image_view=DestroyCacheView(image_view);
1521 return(MagickTrue);
1522}
1523
1524static MagickBooleanType
1525 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1526
1527static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
cristybb503372010-05-27 20:51:26 +00001528 const size_t level,const unsigned int direction)
cristy3ed852e2009-09-05 21:47:34 +00001529{
1530 if (level == 1)
1531 switch (direction)
1532 {
1533 case WestGravity:
1534 {
1535 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1536 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1537 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1538 break;
1539 }
1540 case EastGravity:
1541 {
1542 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1543 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1544 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1545 break;
1546 }
1547 case NorthGravity:
1548 {
1549 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1550 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1551 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1552 break;
1553 }
1554 case SouthGravity:
1555 {
1556 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1557 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1558 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1559 break;
1560 }
1561 default:
1562 break;
1563 }
1564 else
1565 switch (direction)
1566 {
1567 case WestGravity:
1568 {
1569 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1570 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1571 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1572 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1573 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1574 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1575 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1576 break;
1577 }
1578 case EastGravity:
1579 {
1580 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1581 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1582 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1583 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1584 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1585 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1586 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1587 break;
1588 }
1589 case NorthGravity:
1590 {
1591 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1592 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1593 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1594 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1595 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1596 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1597 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1598 break;
1599 }
1600 case SouthGravity:
1601 {
1602 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1603 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1604 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1605 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1606 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1607 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1608 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1609 break;
1610 }
1611 default:
1612 break;
1613 }
1614}
1615
1616static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1617 CubeInfo *cube_info,const unsigned int direction)
1618{
1619#define DitherImageTag "Dither/Image"
1620
1621 MagickBooleanType
1622 proceed;
1623
1624 RealPixelPacket
1625 color,
1626 pixel;
1627
1628 register CubeInfo
1629 *p;
1630
cristybb503372010-05-27 20:51:26 +00001631 size_t
cristy3ed852e2009-09-05 21:47:34 +00001632 index;
1633
1634 p=cube_info;
cristybb503372010-05-27 20:51:26 +00001635 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1636 (p->y >= 0) && (p->y < (ssize_t) image->rows))
cristy3ed852e2009-09-05 21:47:34 +00001637 {
1638 ExceptionInfo
1639 *exception;
1640
1641 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00001642 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00001643
cristybb503372010-05-27 20:51:26 +00001644 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001645 i;
1646
1647 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001648 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001649
1650 /*
1651 Distribute error.
1652 */
1653 exception=(&image->exception);
1654 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1655 if (q == (PixelPacket *) NULL)
1656 return(MagickFalse);
1657 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1658 AssociateAlphaPixel(cube_info,q,&pixel);
1659 for (i=0; i < ErrorQueueLength; i++)
1660 {
1661 pixel.red+=p->weights[i]*p->error[i].red;
1662 pixel.green+=p->weights[i]*p->error[i].green;
1663 pixel.blue+=p->weights[i]*p->error[i].blue;
1664 if (cube_info->associate_alpha != MagickFalse)
1665 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1666 }
cristy75ffdb72010-01-07 17:40:12 +00001667 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1668 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1669 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristy3ed852e2009-09-05 21:47:34 +00001670 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001671 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
cristybb503372010-05-27 20:51:26 +00001672 i=(ssize_t) ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.red)) >> CacheShift) |
cristy75ffdb72010-01-07 17:40:12 +00001673 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.green)) >> CacheShift) << 6 |
1674 (ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.blue)) >> CacheShift) << 12);
cristy3ed852e2009-09-05 21:47:34 +00001675 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001676 i|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel.opacity)) >> CacheShift)
cristy3ed852e2009-09-05 21:47:34 +00001677 << 18);
1678 if (p->cache[i] < 0)
1679 {
1680 register NodeInfo
1681 *node_info;
1682
cristybb503372010-05-27 20:51:26 +00001683 register size_t
cristy3ed852e2009-09-05 21:47:34 +00001684 id;
1685
1686 /*
1687 Identify the deepest node containing the pixel's color.
1688 */
1689 node_info=p->root;
cristybb503372010-05-27 20:51:26 +00001690 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +00001691 {
1692 id=ColorToNodeId(cube_info,&pixel,index);
1693 if (node_info->child[id] == (NodeInfo *) NULL)
1694 break;
1695 node_info=node_info->child[id];
1696 }
1697 /*
1698 Find closest color among siblings and their children.
1699 */
1700 p->target=pixel;
1701 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1702 QuantumRange+1.0)+1.0);
1703 ClosestColor(image,p,node_info->parent);
cristybb503372010-05-27 20:51:26 +00001704 p->cache[i]=(ssize_t) p->color_number;
cristy3ed852e2009-09-05 21:47:34 +00001705 }
1706 /*
1707 Assign pixel to closest colormap entry.
1708 */
cristybb503372010-05-27 20:51:26 +00001709 index=(size_t) (1*p->cache[i]);
cristy3ed852e2009-09-05 21:47:34 +00001710 if (image->storage_class == PseudoClass)
1711 *indexes=(IndexPacket) index;
1712 if (cube_info->quantize_info->measure_error == MagickFalse)
1713 {
1714 q->red=image->colormap[index].red;
1715 q->green=image->colormap[index].green;
1716 q->blue=image->colormap[index].blue;
1717 if (cube_info->associate_alpha != MagickFalse)
1718 q->opacity=image->colormap[index].opacity;
1719 }
1720 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1721 return(MagickFalse);
1722 /*
1723 Propagate the error as the last entry of the error queue.
1724 */
1725 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1726 sizeof(p->error[0]));
1727 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1728 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1729 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1730 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1731 if (cube_info->associate_alpha != MagickFalse)
1732 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1733 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1734 if (proceed == MagickFalse)
1735 return(MagickFalse);
1736 p->offset++;
1737 }
1738 switch (direction)
1739 {
1740 case WestGravity: p->x--; break;
1741 case EastGravity: p->x++; break;
1742 case NorthGravity: p->y--; break;
1743 case SouthGravity: p->y++; break;
1744 }
1745 return(MagickTrue);
1746}
1747
cristybb503372010-05-27 20:51:26 +00001748static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
cristy3ed852e2009-09-05 21:47:34 +00001749{
1750 if (x > y)
1751 return(x);
1752 return(y);
1753}
1754
cristybb503372010-05-27 20:51:26 +00001755static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
cristy3ed852e2009-09-05 21:47:34 +00001756{
1757 if (x < y)
1758 return(x);
1759 return(y);
1760}
1761
1762static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1763{
cristyc4c8d132010-01-07 01:58:38 +00001764 CacheView
1765 *image_view;
1766
cristy3ed852e2009-09-05 21:47:34 +00001767 MagickBooleanType
1768 status;
1769
cristybb503372010-05-27 20:51:26 +00001770 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001771 i;
1772
cristybb503372010-05-27 20:51:26 +00001773 size_t
cristy3ed852e2009-09-05 21:47:34 +00001774 depth;
1775
cristy3ed852e2009-09-05 21:47:34 +00001776 if (cube_info->quantize_info->dither_method == FloydSteinbergDitherMethod)
1777 return(FloydSteinbergDither(image,cube_info));
1778 /*
cristycee97112010-05-28 00:44:52 +00001779 Distribute quantization error along a Hilbert curve.
cristy3ed852e2009-09-05 21:47:34 +00001780 */
1781 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1782 sizeof(*cube_info->error));
1783 cube_info->x=0;
1784 cube_info->y=0;
cristybb503372010-05-27 20:51:26 +00001785 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
cristy3ed852e2009-09-05 21:47:34 +00001786 for (depth=1; i != 0; depth++)
1787 i>>=1;
cristybb503372010-05-27 20:51:26 +00001788 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
cristy3ed852e2009-09-05 21:47:34 +00001789 depth++;
1790 cube_info->offset=0;
1791 cube_info->span=(MagickSizeType) image->columns*image->rows;
1792 image_view=AcquireCacheView(image);
1793 if (depth > 1)
1794 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1795 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1796 image_view=DestroyCacheView(image_view);
1797 return(status);
1798}
1799
1800/*
1801%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1802% %
1803% %
1804% %
1805+ G e t C u b e I n f o %
1806% %
1807% %
1808% %
1809%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1810%
1811% GetCubeInfo() initialize the Cube data structure.
1812%
1813% The format of the GetCubeInfo method is:
1814%
1815% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
cristybb503372010-05-27 20:51:26 +00001816% const size_t depth,const size_t maximum_colors)
cristy3ed852e2009-09-05 21:47:34 +00001817%
1818% A description of each parameter follows.
1819%
1820% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1821%
1822% o depth: Normally, this integer value is zero or one. A zero or
1823% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1824% A tree of this depth generally allows the best representation of the
1825% reference image with the least amount of memory and the fastest
1826% computational speed. In some cases, such as an image with low color
1827% dispersion (a few number of colors), a value other than
1828% Log4(number_colors) is required. To expand the color tree completely,
1829% use a value of 8.
1830%
1831% o maximum_colors: maximum colors.
1832%
1833*/
1834static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
cristybb503372010-05-27 20:51:26 +00001835 const size_t depth,const size_t maximum_colors)
cristy3ed852e2009-09-05 21:47:34 +00001836{
1837 CubeInfo
1838 *cube_info;
1839
1840 MagickRealType
1841 sum,
1842 weight;
1843
1844 size_t
1845 length;
1846
cristybb503372010-05-27 20:51:26 +00001847 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001848 i;
1849
1850 /*
1851 Initialize tree to describe color cube_info.
1852 */
cristy90823212009-12-12 20:48:33 +00001853 cube_info=(CubeInfo *) AcquireAlignedMemory(1,sizeof(*cube_info));
cristy3ed852e2009-09-05 21:47:34 +00001854 if (cube_info == (CubeInfo *) NULL)
1855 return((CubeInfo *) NULL);
1856 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1857 cube_info->depth=depth;
1858 if (cube_info->depth > MaxTreeDepth)
1859 cube_info->depth=MaxTreeDepth;
1860 if (cube_info->depth < 2)
1861 cube_info->depth=2;
1862 cube_info->maximum_colors=maximum_colors;
1863 /*
1864 Initialize root node.
1865 */
1866 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1867 if (cube_info->root == (NodeInfo *) NULL)
1868 return((CubeInfo *) NULL);
1869 cube_info->root->parent=cube_info->root;
1870 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1871 if (cube_info->quantize_info->dither == MagickFalse)
1872 return(cube_info);
1873 /*
1874 Initialize dither resources.
1875 */
1876 length=(size_t) (1UL << (4*(8-CacheShift)));
cristybb503372010-05-27 20:51:26 +00001877 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
cristy3ed852e2009-09-05 21:47:34 +00001878 sizeof(*cube_info->cache));
cristybb503372010-05-27 20:51:26 +00001879 if (cube_info->cache == (ssize_t *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00001880 return((CubeInfo *) NULL);
1881 /*
1882 Initialize color cache.
1883 */
cristybb503372010-05-27 20:51:26 +00001884 for (i=0; i < (ssize_t) length; i++)
cristy3ed852e2009-09-05 21:47:34 +00001885 cube_info->cache[i]=(-1);
1886 /*
cristycee97112010-05-28 00:44:52 +00001887 Distribute weights along a curve of exponential decay.
cristy3ed852e2009-09-05 21:47:34 +00001888 */
1889 weight=1.0;
1890 for (i=0; i < ErrorQueueLength; i++)
1891 {
1892 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
1893 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
1894 }
1895 /*
1896 Normalize the weighting factors.
1897 */
1898 weight=0.0;
1899 for (i=0; i < ErrorQueueLength; i++)
1900 weight+=cube_info->weights[i];
1901 sum=0.0;
1902 for (i=0; i < ErrorQueueLength; i++)
1903 {
1904 cube_info->weights[i]/=weight;
1905 sum+=cube_info->weights[i];
1906 }
1907 cube_info->weights[0]+=1.0-sum;
1908 return(cube_info);
1909}
1910
1911/*
1912%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1913% %
1914% %
1915% %
1916+ G e t N o d e I n f o %
1917% %
1918% %
1919% %
1920%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1921%
1922% GetNodeInfo() allocates memory for a new node in the color cube tree and
1923% presets all fields to zero.
1924%
1925% The format of the GetNodeInfo method is:
1926%
cristybb503372010-05-27 20:51:26 +00001927% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1928% const size_t level,NodeInfo *parent)
cristy3ed852e2009-09-05 21:47:34 +00001929%
1930% A description of each parameter follows.
1931%
1932% o node: The GetNodeInfo method returns a pointer to a queue of nodes.
1933%
1934% o id: Specifies the child number of the node.
1935%
1936% o level: Specifies the level in the storage_class the node resides.
1937%
1938*/
cristybb503372010-05-27 20:51:26 +00001939static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
1940 const size_t level,NodeInfo *parent)
cristy3ed852e2009-09-05 21:47:34 +00001941{
1942 NodeInfo
1943 *node_info;
1944
1945 if (cube_info->free_nodes == 0)
1946 {
1947 Nodes
1948 *nodes;
1949
1950 /*
1951 Allocate a new queue of nodes.
1952 */
cristy90823212009-12-12 20:48:33 +00001953 nodes=(Nodes *) AcquireAlignedMemory(1,sizeof(*nodes));
cristy3ed852e2009-09-05 21:47:34 +00001954 if (nodes == (Nodes *) NULL)
1955 return((NodeInfo *) NULL);
1956 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
1957 sizeof(*nodes->nodes));
1958 if (nodes->nodes == (NodeInfo *) NULL)
1959 return((NodeInfo *) NULL);
1960 nodes->next=cube_info->node_queue;
1961 cube_info->node_queue=nodes;
1962 cube_info->next_node=nodes->nodes;
1963 cube_info->free_nodes=NodesInAList;
1964 }
1965 cube_info->nodes++;
1966 cube_info->free_nodes--;
1967 node_info=cube_info->next_node++;
1968 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
1969 node_info->parent=parent;
1970 node_info->id=id;
1971 node_info->level=level;
1972 return(node_info);
1973}
1974
1975/*
1976%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1977% %
1978% %
1979% %
1980% G e t I m a g e Q u a n t i z e E r r o r %
1981% %
1982% %
1983% %
1984%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1985%
1986% GetImageQuantizeError() measures the difference between the original
1987% and quantized images. This difference is the total quantization error.
1988% The error is computed by summing over all pixels in an image the distance
1989% squared in RGB space between each reference pixel value and its quantized
1990% value. These values are computed:
1991%
1992% o mean_error_per_pixel: This value is the mean error for any single
1993% pixel in the image.
1994%
1995% o normalized_mean_square_error: This value is the normalized mean
1996% quantization error for any single pixel in the image. This distance
1997% measure is normalized to a range between 0 and 1. It is independent
1998% of the range of red, green, and blue values in the image.
1999%
2000% o normalized_maximum_square_error: Thsi value is the normalized
2001% maximum quantization error for any single pixel in the image. This
2002% distance measure is normalized to a range between 0 and 1. It is
2003% independent of the range of red, green, and blue values in your image.
2004%
2005% The format of the GetImageQuantizeError method is:
2006%
2007% MagickBooleanType GetImageQuantizeError(Image *image)
2008%
2009% A description of each parameter follows.
2010%
2011% o image: the image.
2012%
2013*/
2014MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2015{
cristyc4c8d132010-01-07 01:58:38 +00002016 CacheView
2017 *image_view;
2018
cristy3ed852e2009-09-05 21:47:34 +00002019 ExceptionInfo
2020 *exception;
2021
2022 IndexPacket
2023 *indexes;
2024
cristybb503372010-05-27 20:51:26 +00002025 ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002026 y;
2027
2028 MagickRealType
2029 alpha,
2030 area,
2031 beta,
2032 distance,
2033 maximum_error,
2034 mean_error,
2035 mean_error_per_pixel;
2036
cristybb503372010-05-27 20:51:26 +00002037 size_t
cristy3ed852e2009-09-05 21:47:34 +00002038 index;
2039
cristy3ed852e2009-09-05 21:47:34 +00002040 assert(image != (Image *) NULL);
2041 assert(image->signature == MagickSignature);
2042 if (image->debug != MagickFalse)
2043 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2044 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2045 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2046 if (image->storage_class == DirectClass)
2047 return(MagickTrue);
2048 alpha=1.0;
2049 beta=1.0;
2050 area=3.0*image->columns*image->rows;
2051 maximum_error=0.0;
2052 mean_error_per_pixel=0.0;
2053 mean_error=0.0;
2054 exception=(&image->exception);
2055 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +00002056 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00002057 {
2058 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00002059 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00002060
cristybb503372010-05-27 20:51:26 +00002061 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002062 x;
2063
2064 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2065 if (p == (const PixelPacket *) NULL)
2066 break;
2067 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00002068 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00002069 {
2070 index=1UL*indexes[x];
2071 if (image->matte != MagickFalse)
2072 {
cristy46f08202010-01-10 04:04:21 +00002073 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
cristy3ed852e2009-09-05 21:47:34 +00002074 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2075 image->colormap[index].opacity));
2076 }
2077 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2078 mean_error_per_pixel+=distance;
2079 mean_error+=distance*distance;
2080 if (distance > maximum_error)
2081 maximum_error=distance;
2082 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2083 mean_error_per_pixel+=distance;
2084 mean_error+=distance*distance;
2085 if (distance > maximum_error)
2086 maximum_error=distance;
2087 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2088 mean_error_per_pixel+=distance;
2089 mean_error+=distance*distance;
2090 if (distance > maximum_error)
2091 maximum_error=distance;
2092 p++;
2093 }
2094 }
2095 image_view=DestroyCacheView(image_view);
2096 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2097 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2098 mean_error/area;
2099 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2100 return(MagickTrue);
2101}
2102
2103/*
2104%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2105% %
2106% %
2107% %
2108% G e t Q u a n t i z e I n f o %
2109% %
2110% %
2111% %
2112%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2113%
2114% GetQuantizeInfo() initializes the QuantizeInfo structure.
2115%
2116% The format of the GetQuantizeInfo method is:
2117%
2118% GetQuantizeInfo(QuantizeInfo *quantize_info)
2119%
2120% A description of each parameter follows:
2121%
2122% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2123%
2124*/
2125MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2126{
2127 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2128 assert(quantize_info != (QuantizeInfo *) NULL);
2129 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2130 quantize_info->number_colors=256;
2131 quantize_info->dither=MagickTrue;
2132 quantize_info->dither_method=RiemersmaDitherMethod;
2133 quantize_info->colorspace=UndefinedColorspace;
2134 quantize_info->measure_error=MagickFalse;
2135 quantize_info->signature=MagickSignature;
2136}
2137
2138/*
2139%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2140% %
2141% %
2142% %
2143% P o s t e r i z e I m a g e %
2144% %
2145% %
2146% %
2147%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2148%
2149% PosterizeImage() reduces the image to a limited number of colors for a
2150% "poster" effect.
2151%
2152% The format of the PosterizeImage method is:
2153%
cristybb503372010-05-27 20:51:26 +00002154% MagickBooleanType PosterizeImage(Image *image,const size_t levels,
cristy3ed852e2009-09-05 21:47:34 +00002155% const MagickBooleanType dither)
2156%
2157% A description of each parameter follows:
2158%
2159% o image: Specifies a pointer to an Image structure.
2160%
2161% o levels: Number of color levels allowed in each channel. Very low values
2162% (2, 3, or 4) have the most visible effect.
2163%
2164% o dither: Set this integer value to something other than zero to
2165% dither the mapped image.
2166%
2167*/
2168MagickExport MagickBooleanType PosterizeImage(Image *image,
cristybb503372010-05-27 20:51:26 +00002169 const size_t levels,const MagickBooleanType dither)
cristy3ed852e2009-09-05 21:47:34 +00002170{
cristyc4c8d132010-01-07 01:58:38 +00002171 CacheView
2172 *posterize_view;
2173
cristy3ed852e2009-09-05 21:47:34 +00002174 ExceptionInfo
2175 *exception;
2176
2177 Image
2178 *posterize_image;
2179
2180 IndexPacket
2181 *indexes;
2182
cristybb503372010-05-27 20:51:26 +00002183 ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002184 j,
2185 k,
2186 l,
2187 n;
2188
2189 MagickBooleanType
2190 status;
2191
2192 QuantizeInfo
2193 *quantize_info;
2194
cristybb503372010-05-27 20:51:26 +00002195 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002196 i;
2197
2198 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00002199 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00002200
cristyd99b0962010-05-29 23:14:26 +00002201 size_t
2202 length;
2203
cristy3ed852e2009-09-05 21:47:34 +00002204 /*
2205 Posterize image.
2206 */
2207 assert(image != (Image *) NULL);
2208 assert(image->signature == MagickSignature);
2209 if (image->debug != MagickFalse)
2210 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2211 posterize_image=AcquireImage((ImageInfo *) NULL);
2212 if (posterize_image == (Image *) NULL)
2213 return(MagickFalse);
2214 l=1;
cristyd99b0962010-05-29 23:14:26 +00002215 length=(size_t) (levels*levels*levels);
cristyeaedf062010-05-29 22:36:02 +00002216 while ((l*l*l) < (ssize_t) MagickMin((ssize_t) length,MaxColormapSize+1))
cristy3ed852e2009-09-05 21:47:34 +00002217 l++;
cristybb503372010-05-27 20:51:26 +00002218 status=SetImageExtent(posterize_image,(size_t) (l*l*l),1);
cristy3ed852e2009-09-05 21:47:34 +00002219 if (status == MagickFalse)
2220 {
2221 posterize_image=DestroyImage(posterize_image);
2222 return(MagickFalse);
2223 }
2224 status=AcquireImageColormap(posterize_image,levels*levels*levels);
2225 if (status == MagickFalse)
2226 {
2227 posterize_image=DestroyImage(posterize_image);
2228 return(MagickFalse);
2229 }
2230 posterize_view=AcquireCacheView(posterize_image);
2231 exception=(&image->exception);
2232 q=QueueCacheViewAuthenticPixels(posterize_view,0,0,posterize_image->columns,1,
2233 exception);
2234 if (q == (PixelPacket *) NULL)
2235 {
2236 posterize_view=DestroyCacheView(posterize_view);
2237 posterize_image=DestroyImage(posterize_image);
2238 return(MagickFalse);
2239 }
2240 indexes=GetCacheViewAuthenticIndexQueue(posterize_view);
2241 n=0;
2242 for (i=0; i < l; i++)
2243 for (j=0; j < l; j++)
2244 for (k=0; k < l; k++)
2245 {
2246 posterize_image->colormap[n].red=(Quantum) (QuantumRange*i/
2247 MagickMax(l-1L,1L));
2248 posterize_image->colormap[n].green=(Quantum)
2249 (QuantumRange*j/MagickMax(l-1L,1L));
2250 posterize_image->colormap[n].blue=(Quantum) (QuantumRange*k/
2251 MagickMax(l-1L,1L));
2252 posterize_image->colormap[n].opacity=OpaqueOpacity;
2253 *q++=posterize_image->colormap[n];
2254 indexes[n]=(IndexPacket) n;
2255 n++;
2256 }
2257 if (SyncCacheViewAuthenticPixels(posterize_view,exception) == MagickFalse)
2258 {
2259 posterize_view=DestroyCacheView(posterize_view);
2260 posterize_image=DestroyImage(posterize_image);
2261 return(MagickFalse);
2262 }
2263 posterize_view=DestroyCacheView(posterize_view);
2264 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
2265 quantize_info->dither=dither;
2266 status=RemapImage(quantize_info,image,posterize_image);
2267 quantize_info=DestroyQuantizeInfo(quantize_info);
2268 posterize_image=DestroyImage(posterize_image);
2269 return(status);
2270}
2271
2272/*
2273%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2274% %
2275% %
2276% %
2277+ P r u n e C h i l d %
2278% %
2279% %
2280% %
2281%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2282%
2283% PruneChild() deletes the given node and merges its statistics into its
2284% parent.
2285%
2286% The format of the PruneSubtree method is:
2287%
2288% PruneChild(const Image *image,CubeInfo *cube_info,
2289% const NodeInfo *node_info)
2290%
2291% A description of each parameter follows.
2292%
2293% o image: the image.
2294%
2295% o cube_info: A pointer to the Cube structure.
2296%
2297% o node_info: pointer to node in color cube tree that is to be pruned.
2298%
2299*/
2300static void PruneChild(const Image *image,CubeInfo *cube_info,
2301 const NodeInfo *node_info)
2302{
2303 NodeInfo
2304 *parent;
2305
cristybb503372010-05-27 20:51:26 +00002306 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002307 i;
2308
cristybb503372010-05-27 20:51:26 +00002309 size_t
cristy3ed852e2009-09-05 21:47:34 +00002310 number_children;
2311
2312 /*
2313 Traverse any children.
2314 */
2315 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002316 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002317 if (node_info->child[i] != (NodeInfo *) NULL)
2318 PruneChild(image,cube_info,node_info->child[i]);
2319 /*
2320 Merge color statistics into parent.
2321 */
2322 parent=node_info->parent;
2323 parent->number_unique+=node_info->number_unique;
2324 parent->total_color.red+=node_info->total_color.red;
2325 parent->total_color.green+=node_info->total_color.green;
2326 parent->total_color.blue+=node_info->total_color.blue;
2327 parent->total_color.opacity+=node_info->total_color.opacity;
2328 parent->child[node_info->id]=(NodeInfo *) NULL;
2329 cube_info->nodes--;
2330}
2331
2332/*
2333%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2334% %
2335% %
2336% %
2337+ P r u n e L e v e l %
2338% %
2339% %
2340% %
2341%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2342%
2343% PruneLevel() deletes all nodes at the bottom level of the color tree merging
2344% their color statistics into their parent node.
2345%
2346% The format of the PruneLevel method is:
2347%
2348% PruneLevel(const Image *image,CubeInfo *cube_info,
2349% const NodeInfo *node_info)
2350%
2351% A description of each parameter follows.
2352%
2353% o image: the image.
2354%
2355% o cube_info: A pointer to the Cube structure.
2356%
2357% o node_info: pointer to node in color cube tree that is to be pruned.
2358%
2359*/
2360static void PruneLevel(const Image *image,CubeInfo *cube_info,
2361 const NodeInfo *node_info)
2362{
cristybb503372010-05-27 20:51:26 +00002363 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002364 i;
2365
cristybb503372010-05-27 20:51:26 +00002366 size_t
cristy3ed852e2009-09-05 21:47:34 +00002367 number_children;
2368
2369 /*
2370 Traverse any children.
2371 */
2372 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002373 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002374 if (node_info->child[i] != (NodeInfo *) NULL)
2375 PruneLevel(image,cube_info,node_info->child[i]);
2376 if (node_info->level == cube_info->depth)
2377 PruneChild(image,cube_info,node_info);
2378}
2379
2380/*
2381%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2382% %
2383% %
2384% %
2385+ P r u n e T o C u b e D e p t h %
2386% %
2387% %
2388% %
2389%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2390%
2391% PruneToCubeDepth() deletes any nodes at a depth greater than
2392% cube_info->depth while merging their color statistics into their parent
2393% node.
2394%
2395% The format of the PruneToCubeDepth method is:
2396%
2397% PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2398% const NodeInfo *node_info)
2399%
2400% A description of each parameter follows.
2401%
2402% o cube_info: A pointer to the Cube structure.
2403%
2404% o node_info: pointer to node in color cube tree that is to be pruned.
2405%
2406*/
2407static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2408 const NodeInfo *node_info)
2409{
cristybb503372010-05-27 20:51:26 +00002410 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002411 i;
2412
cristybb503372010-05-27 20:51:26 +00002413 size_t
cristy3ed852e2009-09-05 21:47:34 +00002414 number_children;
2415
2416 /*
2417 Traverse any children.
2418 */
2419 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002420 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002421 if (node_info->child[i] != (NodeInfo *) NULL)
2422 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2423 if (node_info->level > cube_info->depth)
2424 PruneChild(image,cube_info,node_info);
2425}
2426
2427/*
2428%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2429% %
2430% %
2431% %
2432% Q u a n t i z e I m a g e %
2433% %
2434% %
2435% %
2436%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2437%
2438% QuantizeImage() analyzes the colors within a reference image and chooses a
2439% fixed number of colors to represent the image. The goal of the algorithm
2440% is to minimize the color difference between the input and output image while
2441% minimizing the processing time.
2442%
2443% The format of the QuantizeImage method is:
2444%
2445% MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2446% Image *image)
2447%
2448% A description of each parameter follows:
2449%
2450% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2451%
2452% o image: the image.
2453%
2454*/
cristy0157aea2010-04-24 21:12:18 +00002455static MagickBooleanType DirectToColormapImage(Image *image,
2456 ExceptionInfo *exception)
2457{
2458 CacheView
2459 *image_view;
2460
cristybb503372010-05-27 20:51:26 +00002461 ssize_t
cristy0157aea2010-04-24 21:12:18 +00002462 y;
2463
2464 MagickBooleanType
2465 status;
2466
cristybb503372010-05-27 20:51:26 +00002467 register ssize_t
cristy0157aea2010-04-24 21:12:18 +00002468 i;
2469
cristybb503372010-05-27 20:51:26 +00002470 size_t
cristy0157aea2010-04-24 21:12:18 +00002471 number_colors;
2472
2473 status=MagickTrue;
cristybb503372010-05-27 20:51:26 +00002474 number_colors=(size_t) (image->columns*image->rows);
cristy0157aea2010-04-24 21:12:18 +00002475 if (AcquireImageColormap(image,number_colors) == MagickFalse)
2476 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2477 image->filename);
2478 i=0;
2479 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +00002480 for (y=0; y < (ssize_t) image->rows; y++)
cristy0157aea2010-04-24 21:12:18 +00002481 {
cristy07a20312010-04-25 00:36:07 +00002482 MagickBooleanType
2483 proceed;
2484
2485 register IndexPacket
2486 *restrict indexes;
2487
2488 register PixelPacket
2489 *restrict q;
cristy0157aea2010-04-24 21:12:18 +00002490
cristybb503372010-05-27 20:51:26 +00002491 register ssize_t
cristy0157aea2010-04-24 21:12:18 +00002492 x;
2493
cristy07a20312010-04-25 00:36:07 +00002494 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2495 if (q == (const PixelPacket *) NULL)
cristy0157aea2010-04-24 21:12:18 +00002496 break;
cristy07a20312010-04-25 00:36:07 +00002497 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00002498 for (x=0; x < (ssize_t) image->columns; x++)
cristy07a20312010-04-25 00:36:07 +00002499 {
cristycee97112010-05-28 00:44:52 +00002500 indexes[x]=(IndexPacket) i;
cristy07a20312010-04-25 00:36:07 +00002501 image->colormap[i++]=(*q++);
2502 }
2503 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2504 break;
cristycee97112010-05-28 00:44:52 +00002505 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
2506 image->rows);
cristy07a20312010-04-25 00:36:07 +00002507 if (proceed == MagickFalse)
2508 status=MagickFalse;
cristy0157aea2010-04-24 21:12:18 +00002509 }
2510 image_view=DestroyCacheView(image_view);
2511 return(status);
2512}
2513
cristy3ed852e2009-09-05 21:47:34 +00002514MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2515 Image *image)
2516{
2517 CubeInfo
2518 *cube_info;
2519
2520 MagickBooleanType
2521 status;
2522
cristybb503372010-05-27 20:51:26 +00002523 size_t
cristy3ed852e2009-09-05 21:47:34 +00002524 depth,
2525 maximum_colors;
2526
2527 assert(quantize_info != (const QuantizeInfo *) NULL);
2528 assert(quantize_info->signature == MagickSignature);
2529 assert(image != (Image *) NULL);
2530 assert(image->signature == MagickSignature);
2531 if (image->debug != MagickFalse)
2532 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2533 maximum_colors=quantize_info->number_colors;
2534 if (maximum_colors == 0)
2535 maximum_colors=MaxColormapSize;
2536 if (maximum_colors > MaxColormapSize)
2537 maximum_colors=MaxColormapSize;
cristy4ccd4c02010-04-25 00:43:15 +00002538 if ((image->columns*image->rows) <= maximum_colors)
2539 return(DirectToColormapImage(image,&image->exception));
cristy3ed852e2009-09-05 21:47:34 +00002540 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2541 (image->matte == MagickFalse))
2542 (void) SetGrayscaleImage(image);
2543 if ((image->storage_class == PseudoClass) &&
2544 (image->colors <= maximum_colors))
2545 return(MagickTrue);
2546 depth=quantize_info->tree_depth;
2547 if (depth == 0)
2548 {
cristybb503372010-05-27 20:51:26 +00002549 size_t
cristy3ed852e2009-09-05 21:47:34 +00002550 colors;
2551
2552 /*
2553 Depth of color tree is: Log4(colormap size)+2.
2554 */
2555 colors=maximum_colors;
2556 for (depth=1; colors != 0; depth++)
2557 colors>>=2;
2558 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2559 depth--;
2560 if ((image->matte != MagickFalse) && (depth > 5))
2561 depth--;
2562 }
2563 /*
2564 Initialize color cube.
2565 */
2566 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2567 if (cube_info == (CubeInfo *) NULL)
2568 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2569 image->filename);
2570 status=ClassifyImageColors(cube_info,image,&image->exception);
2571 if (status != MagickFalse)
2572 {
2573 /*
2574 Reduce the number of colors in the image.
2575 */
2576 ReduceImageColors(image,cube_info);
2577 status=AssignImageColors(image,cube_info);
2578 }
2579 DestroyCubeInfo(cube_info);
2580 return(status);
2581}
2582
2583/*
2584%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2585% %
2586% %
2587% %
2588% Q u a n t i z e I m a g e s %
2589% %
2590% %
2591% %
2592%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2593%
2594% QuantizeImages() analyzes the colors within a set of reference images and
2595% chooses a fixed number of colors to represent the set. The goal of the
2596% algorithm is to minimize the color difference between the input and output
2597% images while minimizing the processing time.
2598%
2599% The format of the QuantizeImages method is:
2600%
2601% MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2602% Image *images)
2603%
2604% A description of each parameter follows:
2605%
2606% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2607%
2608% o images: Specifies a pointer to a list of Image structures.
2609%
2610*/
2611MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2612 Image *images)
2613{
2614 CubeInfo
2615 *cube_info;
2616
2617 Image
2618 *image;
2619
2620 MagickBooleanType
2621 proceed,
2622 status;
2623
2624 MagickProgressMonitor
2625 progress_monitor;
2626
cristybb503372010-05-27 20:51:26 +00002627 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002628 i;
2629
cristybb503372010-05-27 20:51:26 +00002630 size_t
cristy3ed852e2009-09-05 21:47:34 +00002631 depth,
2632 maximum_colors,
2633 number_images;
2634
2635 assert(quantize_info != (const QuantizeInfo *) NULL);
2636 assert(quantize_info->signature == MagickSignature);
2637 assert(images != (Image *) NULL);
2638 assert(images->signature == MagickSignature);
2639 if (images->debug != MagickFalse)
2640 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2641 if (GetNextImageInList(images) == (Image *) NULL)
2642 {
2643 /*
2644 Handle a single image with QuantizeImage.
2645 */
2646 status=QuantizeImage(quantize_info,images);
2647 return(status);
2648 }
2649 status=MagickFalse;
2650 maximum_colors=quantize_info->number_colors;
2651 if (maximum_colors == 0)
2652 maximum_colors=MaxColormapSize;
2653 if (maximum_colors > MaxColormapSize)
2654 maximum_colors=MaxColormapSize;
2655 depth=quantize_info->tree_depth;
2656 if (depth == 0)
2657 {
cristybb503372010-05-27 20:51:26 +00002658 size_t
cristy3ed852e2009-09-05 21:47:34 +00002659 colors;
2660
2661 /*
2662 Depth of color tree is: Log4(colormap size)+2.
2663 */
2664 colors=maximum_colors;
2665 for (depth=1; colors != 0; depth++)
2666 colors>>=2;
2667 if (quantize_info->dither != MagickFalse)
2668 depth--;
2669 }
2670 /*
2671 Initialize color cube.
2672 */
2673 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2674 if (cube_info == (CubeInfo *) NULL)
2675 {
2676 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2677 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2678 return(MagickFalse);
2679 }
2680 number_images=GetImageListLength(images);
2681 image=images;
2682 for (i=0; image != (Image *) NULL; i++)
2683 {
2684 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2685 image->client_data);
2686 status=ClassifyImageColors(cube_info,image,&image->exception);
2687 if (status == MagickFalse)
2688 break;
2689 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
cristycee97112010-05-28 00:44:52 +00002690 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2691 number_images);
cristy3ed852e2009-09-05 21:47:34 +00002692 if (proceed == MagickFalse)
2693 break;
2694 image=GetNextImageInList(image);
2695 }
2696 if (status != MagickFalse)
2697 {
2698 /*
2699 Reduce the number of colors in an image sequence.
2700 */
2701 ReduceImageColors(images,cube_info);
2702 image=images;
2703 for (i=0; image != (Image *) NULL; i++)
2704 {
2705 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2706 NULL,image->client_data);
2707 status=AssignImageColors(image,cube_info);
2708 if (status == MagickFalse)
2709 break;
2710 (void) SetImageProgressMonitor(image,progress_monitor,
2711 image->client_data);
cristycee97112010-05-28 00:44:52 +00002712 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2713 number_images);
cristy3ed852e2009-09-05 21:47:34 +00002714 if (proceed == MagickFalse)
2715 break;
2716 image=GetNextImageInList(image);
2717 }
2718 }
2719 DestroyCubeInfo(cube_info);
2720 return(status);
2721}
2722
2723/*
2724%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2725% %
2726% %
2727% %
2728+ R e d u c e %
2729% %
2730% %
2731% %
2732%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2733%
2734% Reduce() traverses the color cube tree and prunes any node whose
2735% quantization error falls below a particular threshold.
2736%
2737% The format of the Reduce method is:
2738%
2739% Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2740%
2741% A description of each parameter follows.
2742%
2743% o image: the image.
2744%
2745% o cube_info: A pointer to the Cube structure.
2746%
2747% o node_info: pointer to node in color cube tree that is to be pruned.
2748%
2749*/
2750static void Reduce(const Image *image,CubeInfo *cube_info,
2751 const NodeInfo *node_info)
2752{
cristybb503372010-05-27 20:51:26 +00002753 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002754 i;
2755
cristybb503372010-05-27 20:51:26 +00002756 size_t
cristy3ed852e2009-09-05 21:47:34 +00002757 number_children;
2758
2759 /*
2760 Traverse any children.
2761 */
2762 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002763 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002764 if (node_info->child[i] != (NodeInfo *) NULL)
2765 Reduce(image,cube_info,node_info->child[i]);
2766 if (node_info->quantize_error <= cube_info->pruning_threshold)
2767 PruneChild(image,cube_info,node_info);
2768 else
2769 {
2770 /*
2771 Find minimum pruning threshold.
2772 */
2773 if (node_info->number_unique > 0)
2774 cube_info->colors++;
2775 if (node_info->quantize_error < cube_info->next_threshold)
2776 cube_info->next_threshold=node_info->quantize_error;
2777 }
2778}
2779
2780/*
2781%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2782% %
2783% %
2784% %
2785+ R e d u c e I m a g e C o l o r s %
2786% %
2787% %
2788% %
2789%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2790%
2791% ReduceImageColors() repeatedly prunes the tree until the number of nodes
2792% with n2 > 0 is less than or equal to the maximum number of colors allowed
2793% in the output image. On any given iteration over the tree, it selects
2794% those nodes whose E value is minimal for pruning and merges their
2795% color statistics upward. It uses a pruning threshold, Ep, to govern
2796% node selection as follows:
2797%
2798% Ep = 0
2799% while number of nodes with (n2 > 0) > required maximum number of colors
2800% prune all nodes such that E <= Ep
2801% Set Ep to minimum E in remaining nodes
2802%
2803% This has the effect of minimizing any quantization error when merging
2804% two nodes together.
2805%
2806% When a node to be pruned has offspring, the pruning procedure invokes
2807% itself recursively in order to prune the tree from the leaves upward.
2808% n2, Sr, Sg, and Sb in a node being pruned are always added to the
2809% corresponding data in that node's parent. This retains the pruned
2810% node's color characteristics for later averaging.
2811%
2812% For each node, n2 pixels exist for which that node represents the
2813% smallest volume in RGB space containing those pixel's colors. When n2
2814% > 0 the node will uniquely define a color in the output image. At the
2815% beginning of reduction, n2 = 0 for all nodes except a the leaves of
2816% the tree which represent colors present in the input image.
2817%
2818% The other pixel count, n1, indicates the total number of colors
2819% within the cubic volume which the node represents. This includes n1 -
2820% n2 pixels whose colors should be defined by nodes at a lower level in
2821% the tree.
2822%
2823% The format of the ReduceImageColors method is:
2824%
2825% ReduceImageColors(const Image *image,CubeInfo *cube_info)
2826%
2827% A description of each parameter follows.
2828%
2829% o image: the image.
2830%
2831% o cube_info: A pointer to the Cube structure.
2832%
2833*/
2834static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2835{
2836#define ReduceImageTag "Reduce/Image"
2837
2838 MagickBooleanType
2839 proceed;
2840
2841 MagickOffsetType
2842 offset;
2843
cristybb503372010-05-27 20:51:26 +00002844 size_t
cristy3ed852e2009-09-05 21:47:34 +00002845 span;
2846
2847 cube_info->next_threshold=0.0;
2848 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2849 {
2850 cube_info->pruning_threshold=cube_info->next_threshold;
2851 cube_info->next_threshold=cube_info->root->quantize_error-1;
2852 cube_info->colors=0;
2853 Reduce(image,cube_info,cube_info->root);
2854 offset=(MagickOffsetType) span-cube_info->colors;
2855 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2856 cube_info->maximum_colors+1);
2857 if (proceed == MagickFalse)
2858 break;
2859 }
2860}
2861
2862/*
2863%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2864% %
2865% %
2866% %
2867% R e m a p I m a g e %
2868% %
2869% %
2870% %
2871%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2872%
2873% RemapImage() replaces the colors of an image with the closest color from
2874% a reference image.
2875%
2876% The format of the RemapImage method is:
2877%
2878% MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2879% Image *image,const Image *remap_image)
2880%
2881% A description of each parameter follows:
2882%
2883% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2884%
2885% o image: the image.
2886%
2887% o remap_image: the reference image.
2888%
2889*/
2890MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2891 Image *image,const Image *remap_image)
2892{
2893 CubeInfo
2894 *cube_info;
2895
2896 MagickBooleanType
2897 status;
2898
2899 /*
2900 Initialize color cube.
2901 */
2902 assert(image != (Image *) NULL);
2903 assert(image->signature == MagickSignature);
2904 if (image->debug != MagickFalse)
2905 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2906 assert(remap_image != (Image *) NULL);
2907 assert(remap_image->signature == MagickSignature);
2908 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2909 quantize_info->number_colors);
2910 if (cube_info == (CubeInfo *) NULL)
2911 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2912 image->filename);
2913 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2914 if (status != MagickFalse)
2915 {
2916 /*
2917 Classify image colors from the reference image.
2918 */
2919 cube_info->quantize_info->number_colors=cube_info->colors;
2920 status=AssignImageColors(image,cube_info);
2921 }
2922 DestroyCubeInfo(cube_info);
2923 return(status);
2924}
2925
2926/*
2927%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2928% %
2929% %
2930% %
2931% R e m a p I m a g e s %
2932% %
2933% %
2934% %
2935%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2936%
2937% RemapImages() replaces the colors of a sequence of images with the
2938% closest color from a reference image.
2939%
2940% The format of the RemapImage method is:
2941%
2942% MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2943% Image *images,Image *remap_image)
2944%
2945% A description of each parameter follows:
2946%
2947% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2948%
2949% o images: the image sequence.
2950%
2951% o remap_image: the reference image.
2952%
2953*/
2954MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
2955 Image *images,const Image *remap_image)
2956{
2957 CubeInfo
2958 *cube_info;
2959
2960 Image
2961 *image;
2962
2963 MagickBooleanType
2964 status;
2965
2966 assert(images != (Image *) NULL);
2967 assert(images->signature == MagickSignature);
2968 if (images->debug != MagickFalse)
2969 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2970 image=images;
2971 if (remap_image == (Image *) NULL)
2972 {
2973 /*
2974 Create a global colormap for an image sequence.
2975 */
2976 status=QuantizeImages(quantize_info,images);
2977 return(status);
2978 }
2979 /*
2980 Classify image colors from the reference image.
2981 */
2982 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2983 quantize_info->number_colors);
2984 if (cube_info == (CubeInfo *) NULL)
2985 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2986 image->filename);
2987 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
2988 if (status != MagickFalse)
2989 {
2990 /*
2991 Classify image colors from the reference image.
2992 */
2993 cube_info->quantize_info->number_colors=cube_info->colors;
2994 image=images;
2995 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
2996 {
2997 status=AssignImageColors(image,cube_info);
2998 if (status == MagickFalse)
2999 break;
3000 }
3001 }
3002 DestroyCubeInfo(cube_info);
3003 return(status);
3004}
3005
3006/*
3007%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3008% %
3009% %
3010% %
3011% S e t G r a y s c a l e I m a g e %
3012% %
3013% %
3014% %
3015%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3016%
3017% SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3018%
3019% The format of the SetGrayscaleImage method is:
3020%
3021% MagickBooleanType SetGrayscaleImage(Image *image)
3022%
3023% A description of each parameter follows:
3024%
3025% o image: The image.
3026%
3027*/
3028
3029#if defined(__cplusplus) || defined(c_plusplus)
3030extern "C" {
3031#endif
3032
3033static int IntensityCompare(const void *x,const void *y)
3034{
cristybb503372010-05-27 20:51:26 +00003035 ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003036 intensity;
3037
3038 PixelPacket
3039 *color_1,
3040 *color_2;
3041
3042 color_1=(PixelPacket *) x;
3043 color_2=(PixelPacket *) y;
cristybb503372010-05-27 20:51:26 +00003044 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
cristy3ed852e2009-09-05 21:47:34 +00003045 PixelIntensityToQuantum(color_2);
cristycee97112010-05-28 00:44:52 +00003046 return((int) intensity);
cristy3ed852e2009-09-05 21:47:34 +00003047}
3048
3049#if defined(__cplusplus) || defined(c_plusplus)
3050}
3051#endif
3052
3053static MagickBooleanType SetGrayscaleImage(Image *image)
3054{
cristyc4c8d132010-01-07 01:58:38 +00003055 CacheView
3056 *image_view;
3057
cristy3ed852e2009-09-05 21:47:34 +00003058 ExceptionInfo
3059 *exception;
3060
cristybb503372010-05-27 20:51:26 +00003061 ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003062 j,
3063 y;
3064
3065 PixelPacket
3066 *colormap;
3067
cristybb503372010-05-27 20:51:26 +00003068 ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003069 *colormap_index;
3070
cristybb503372010-05-27 20:51:26 +00003071 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003072 i;
3073
3074 MagickBooleanType
3075 status;
3076
cristy3ed852e2009-09-05 21:47:34 +00003077 assert(image != (Image *) NULL);
3078 assert(image->signature == MagickSignature);
3079 if (image->type != GrayscaleType)
3080 (void) TransformImageColorspace(image,GRAYColorspace);
cristybb503372010-05-27 20:51:26 +00003081 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
cristy3ed852e2009-09-05 21:47:34 +00003082 sizeof(*colormap_index));
cristybb503372010-05-27 20:51:26 +00003083 if (colormap_index == (ssize_t *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00003084 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3085 image->filename);
3086 if (image->storage_class != PseudoClass)
3087 {
3088 ExceptionInfo
3089 *exception;
3090
cristybb503372010-05-27 20:51:26 +00003091 for (i=0; i <= (ssize_t) MaxMap; i++)
cristy3ed852e2009-09-05 21:47:34 +00003092 colormap_index[i]=(-1);
3093 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3094 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3095 image->filename);
3096 image->colors=0;
3097 status=MagickTrue;
3098 exception=(&image->exception);
3099 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003100#if defined(MAGICKCORE_OPENMP_SUPPORT)
3101 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003102#endif
cristybb503372010-05-27 20:51:26 +00003103 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00003104 {
3105 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00003106 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00003107
cristybb503372010-05-27 20:51:26 +00003108 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003109 x;
3110
3111 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00003112 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003113
3114 if (status == MagickFalse)
3115 continue;
3116 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3117 exception);
3118 if (q == (PixelPacket *) NULL)
3119 {
3120 status=MagickFalse;
3121 continue;
3122 }
3123 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00003124 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00003125 {
cristybb503372010-05-27 20:51:26 +00003126 register size_t
cristy3ed852e2009-09-05 21:47:34 +00003127 intensity;
3128
3129 intensity=ScaleQuantumToMap(q->red);
3130 if (colormap_index[intensity] < 0)
3131 {
cristyb5d5f722009-11-04 03:03:49 +00003132#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy3ed852e2009-09-05 21:47:34 +00003133 #pragma omp critical (MagickCore_SetGrayscaleImage)
3134#endif
3135 if (colormap_index[intensity] < 0)
3136 {
cristybb503372010-05-27 20:51:26 +00003137 colormap_index[intensity]=(ssize_t) image->colors;
cristy3ed852e2009-09-05 21:47:34 +00003138 image->colormap[image->colors]=(*q);
3139 image->colors++;
3140 }
3141 }
3142 indexes[x]=(IndexPacket) colormap_index[intensity];
3143 q++;
3144 }
3145 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3146 status=MagickFalse;
3147 }
3148 image_view=DestroyCacheView(image_view);
3149 }
cristybb503372010-05-27 20:51:26 +00003150 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00003151 image->colormap[i].opacity=(unsigned short) i;
3152 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3153 IntensityCompare);
3154 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3155 sizeof(*colormap));
3156 if (colormap == (PixelPacket *) NULL)
3157 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3158 image->filename);
3159 j=0;
3160 colormap[j]=image->colormap[0];
cristybb503372010-05-27 20:51:26 +00003161 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00003162 {
3163 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3164 {
3165 j++;
3166 colormap[j]=image->colormap[i];
3167 }
cristybb503372010-05-27 20:51:26 +00003168 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
cristy3ed852e2009-09-05 21:47:34 +00003169 }
cristybb503372010-05-27 20:51:26 +00003170 image->colors=(size_t) (j+1);
cristy3ed852e2009-09-05 21:47:34 +00003171 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3172 image->colormap=colormap;
3173 status=MagickTrue;
3174 exception=(&image->exception);
3175 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003176#if defined(MAGICKCORE_OPENMP_SUPPORT)
3177 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003178#endif
cristybb503372010-05-27 20:51:26 +00003179 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00003180 {
3181 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00003182 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00003183
cristybb503372010-05-27 20:51:26 +00003184 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003185 x;
3186
3187 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00003188 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003189
3190 if (status == MagickFalse)
3191 continue;
3192 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3193 if (q == (PixelPacket *) NULL)
3194 {
3195 status=MagickFalse;
3196 continue;
3197 }
3198 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00003199 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00003200 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3201 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3202 status=MagickFalse;
3203 }
3204 image_view=DestroyCacheView(image_view);
cristybb503372010-05-27 20:51:26 +00003205 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
cristy3ed852e2009-09-05 21:47:34 +00003206 image->type=GrayscaleType;
3207 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3208 image->type=BilevelType;
3209 return(status);
3210}