blob: 8754664611002477edaa5a772d0467b63428d0f8 [file] [log] [blame]
cristy3ed852e2009-09-05 21:47:34 +00001/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% %
6% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
7% Q Q U U A A NN N T I ZZ E %
8% Q Q U U AAAAA N N N T I ZZZ EEEEE %
9% Q QQ U U A A N NN T I ZZ E %
10% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
11% %
12% %
13% MagickCore Methods to Reduce the Number of Unique Colors in an Image %
14% %
15% Software Design %
16% John Cristy %
17% July 1992 %
18% %
19% %
cristy7e41fe82010-12-04 23:12:08 +000020% Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization %
cristy3ed852e2009-09-05 21:47:34 +000021% dedicated to making software imaging solutions freely available. %
22% %
23% You may not use this file except in compliance with the License. You may %
24% obtain a copy of the License at %
25% %
26% http://www.imagemagick.org/script/license.php %
27% %
28% Unless required by applicable law or agreed to in writing, software %
29% distributed under the License is distributed on an "AS IS" BASIS, %
30% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31% See the License for the specific language governing permissions and %
32% limitations under the License. %
33% %
34%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35%
36% Realism in computer graphics typically requires using 24 bits/pixel to
37% generate an image. Yet many graphic display devices do not contain the
38% amount of memory necessary to match the spatial and color resolution of
39% the human eye. The Quantize methods takes a 24 bit image and reduces
40% the number of colors so it can be displayed on raster device with less
41% bits per pixel. In most instances, the quantized image closely
42% resembles the original reference image.
43%
44% A reduction of colors in an image is also desirable for image
45% transmission and real-time animation.
46%
47% QuantizeImage() takes a standard RGB or monochrome images and quantizes
48% them down to some fixed number of colors.
49%
50% For purposes of color allocation, an image is a set of n pixels, where
51% each pixel is a point in RGB space. RGB space is a 3-dimensional
52% vector space, and each pixel, Pi, is defined by an ordered triple of
53% red, green, and blue coordinates, (Ri, Gi, Bi).
54%
55% Each primary color component (red, green, or blue) represents an
56% intensity which varies linearly from 0 to a maximum value, Cmax, which
57% corresponds to full saturation of that color. Color allocation is
58% defined over a domain consisting of the cube in RGB space with opposite
59% vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
60% 255.
61%
62% The algorithm maps this domain onto a tree in which each node
63% represents a cube within that domain. In the following discussion
64% these cubes are defined by the coordinate of two opposite vertices:
65% The vertex nearest the origin in RGB space and the vertex farthest from
66% the origin.
67%
68% The tree's root node represents the entire domain, (0,0,0) through
69% (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
70% subdividing one node's cube into eight smaller cubes of equal size.
71% This corresponds to bisecting the parent cube with planes passing
72% through the midpoints of each edge.
73%
74% The basic algorithm operates in three phases: Classification,
75% Reduction, and Assignment. Classification builds a color description
76% tree for the image. Reduction collapses the tree until the number it
77% represents, at most, the number of colors desired in the output image.
78% Assignment defines the output image's color map and sets each pixel's
79% color by restorage_class in the reduced tree. Our goal is to minimize
80% the numerical discrepancies between the original colors and quantized
81% colors (quantization error).
82%
83% Classification begins by initializing a color description tree of
84% sufficient depth to represent each possible input color in a leaf.
85% However, it is impractical to generate a fully-formed color description
86% tree in the storage_class phase for realistic values of Cmax. If
87% colors components in the input image are quantized to k-bit precision,
88% so that Cmax= 2k-1, the tree would need k levels below the root node to
89% allow representing each possible input color in a leaf. This becomes
90% prohibitive because the tree's total number of nodes is 1 +
91% sum(i=1, k, 8k).
92%
93% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
94% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
95% Initializes data structures for nodes only as they are needed; (2)
96% Chooses a maximum depth for the tree as a function of the desired
97% number of colors in the output image (currently log2(colormap size)).
98%
99% For each pixel in the input image, storage_class scans downward from
100% the root of the color description tree. At each level of the tree it
101% identifies the single node which represents a cube in RGB space
102% containing the pixel's color. It updates the following data for each
103% such node:
104%
105% n1: Number of pixels whose color is contained in the RGB cube which
106% this node represents;
107%
108% n2: Number of pixels whose color is not represented in a node at
109% lower depth in the tree; initially, n2 = 0 for all nodes except
110% leaves of the tree.
111%
112% Sr, Sg, Sb: Sums of the red, green, and blue component values for all
113% pixels not classified at a lower depth. The combination of these sums
114% and n2 will ultimately characterize the mean color of a set of
115% pixels represented by this node.
116%
117% E: the distance squared in RGB space between each pixel contained
118% within a node and the nodes' center. This represents the
119% quantization error for a node.
120%
121% Reduction repeatedly prunes the tree until the number of nodes with n2
122% > 0 is less than or equal to the maximum number of colors allowed in
123% the output image. On any given iteration over the tree, it selects
124% those nodes whose E count is minimal for pruning and merges their color
125% statistics upward. It uses a pruning threshold, Ep, to govern node
126% selection as follows:
127%
128% Ep = 0
129% while number of nodes with (n2 > 0) > required maximum number of colors
130% prune all nodes such that E <= Ep
131% Set Ep to minimum E in remaining nodes
132%
133% This has the effect of minimizing any quantization error when merging
134% two nodes together.
135%
136% When a node to be pruned has offspring, the pruning procedure invokes
137% itself recursively in order to prune the tree from the leaves upward.
138% n2, Sr, Sg, and Sb in a node being pruned are always added to the
139% corresponding data in that node's parent. This retains the pruned
140% node's color characteristics for later averaging.
141%
142% For each node, n2 pixels exist for which that node represents the
143% smallest volume in RGB space containing those pixel's colors. When n2
144% > 0 the node will uniquely define a color in the output image. At the
145% beginning of reduction, n2 = 0 for all nodes except a the leaves of
146% the tree which represent colors present in the input image.
147%
148% The other pixel count, n1, indicates the total number of colors within
149% the cubic volume which the node represents. This includes n1 - n2
150% pixels whose colors should be defined by nodes at a lower level in the
151% tree.
152%
153% Assignment generates the output image from the pruned tree. The output
154% image consists of two parts: (1) A color map, which is an array of
155% color descriptions (RGB triples) for each color present in the output
156% image; (2) A pixel array, which represents each pixel as an index
157% into the color map array.
158%
159% First, the assignment phase makes one pass over the pruned color
160% description tree to establish the image's color map. For each node
161% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
162% color of all pixels that classify no lower than this node. Each of
163% these colors becomes an entry in the color map.
164%
165% Finally, the assignment phase reclassifies each pixel in the pruned
166% tree to identify the deepest node containing the pixel's color. The
167% pixel's value in the pixel array becomes the index of this node's mean
168% color in the color map.
169%
170% This method is based on a similar algorithm written by Paul Raveling.
171%
172*/
173
174/*
175 Include declarations.
176*/
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"
cristye9717ac2011-02-20 16:17:17 +0000198#include "magick/thread-private.h"
cristy3ed852e2009-09-05 21:47:34 +0000199
200/*
201 Define declarations.
202*/
cristye1287512010-06-19 17:38:25 +0000203#if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
cristy3ed852e2009-09-05 21:47:34 +0000204#define CacheShift 2
cristye1287512010-06-19 17:38:25 +0000205#else
206#define CacheShift 3
207#endif
cristy3ed852e2009-09-05 21:47:34 +0000208#define ErrorQueueLength 16
209#define MaxNodes 266817
210#define MaxTreeDepth 8
211#define NodesInAList 1920
212
213/*
214 Typdef declarations.
215*/
216typedef struct _RealPixelPacket
217{
218 MagickRealType
219 red,
220 green,
221 blue,
222 opacity;
223} RealPixelPacket;
224
225typedef struct _NodeInfo
226{
227 struct _NodeInfo
228 *parent,
229 *child[16];
230
231 MagickSizeType
232 number_unique;
233
234 RealPixelPacket
235 total_color;
236
237 MagickRealType
238 quantize_error;
239
cristybb503372010-05-27 20:51:26 +0000240 size_t
cristy3ed852e2009-09-05 21:47:34 +0000241 color_number,
242 id,
243 level;
244} NodeInfo;
245
246typedef struct _Nodes
247{
248 NodeInfo
249 *nodes;
250
251 struct _Nodes
252 *next;
253} Nodes;
254
255typedef struct _CubeInfo
256{
257 NodeInfo
258 *root;
259
cristybb503372010-05-27 20:51:26 +0000260 size_t
cristy3ed852e2009-09-05 21:47:34 +0000261 colors,
262 maximum_colors;
263
cristybb503372010-05-27 20:51:26 +0000264 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000265 transparent_index;
266
267 MagickSizeType
268 transparent_pixels;
269
270 RealPixelPacket
271 target;
272
273 MagickRealType
274 distance,
275 pruning_threshold,
276 next_threshold;
277
cristybb503372010-05-27 20:51:26 +0000278 size_t
cristy3ed852e2009-09-05 21:47:34 +0000279 nodes,
280 free_nodes,
281 color_number;
282
283 NodeInfo
284 *next_node;
285
286 Nodes
287 *node_queue;
288
cristybb503372010-05-27 20:51:26 +0000289 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000290 *cache;
291
292 RealPixelPacket
293 error[ErrorQueueLength];
294
295 MagickRealType
296 weights[ErrorQueueLength];
297
298 QuantizeInfo
299 *quantize_info;
300
301 MagickBooleanType
302 associate_alpha;
303
cristybb503372010-05-27 20:51:26 +0000304 ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000305 x,
306 y;
307
cristybb503372010-05-27 20:51:26 +0000308 size_t
cristy3ed852e2009-09-05 21:47:34 +0000309 depth;
310
311 MagickOffsetType
312 offset;
313
314 MagickSizeType
315 span;
316} CubeInfo;
317
318/*
319 Method prototypes.
320*/
321static CubeInfo
cristybb503372010-05-27 20:51:26 +0000322 *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
cristy3ed852e2009-09-05 21:47:34 +0000323
324static NodeInfo
cristybb503372010-05-27 20:51:26 +0000325 *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
cristy3ed852e2009-09-05 21:47:34 +0000326
327static MagickBooleanType
328 AssignImageColors(Image *,CubeInfo *),
329 ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
330 DitherImage(Image *,CubeInfo *),
331 SetGrayscaleImage(Image *);
332
cristybb503372010-05-27 20:51:26 +0000333static size_t
cristy3ed852e2009-09-05 21:47:34 +0000334 DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
335
336static void
337 ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
338 DestroyCubeInfo(CubeInfo *),
339 PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
340 PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
341 ReduceImageColors(const Image *,CubeInfo *);
342
343/*
344%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
345% %
346% %
347% %
348% A c q u i r e Q u a n t i z e I n f o %
349% %
350% %
351% %
352%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
353%
354% AcquireQuantizeInfo() allocates the QuantizeInfo structure.
355%
356% The format of the AcquireQuantizeInfo method is:
357%
358% QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
359%
360% A description of each parameter follows:
361%
362% o image_info: the image info.
363%
364*/
365MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
366{
367 QuantizeInfo
368 *quantize_info;
369
cristy73bd4a52010-10-05 11:24:23 +0000370 quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
cristy3ed852e2009-09-05 21:47:34 +0000371 if (quantize_info == (QuantizeInfo *) NULL)
372 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
373 GetQuantizeInfo(quantize_info);
374 if (image_info != (ImageInfo *) NULL)
375 {
376 const char
377 *option;
378
379 quantize_info->dither=image_info->dither;
380 option=GetImageOption(image_info,"dither");
381 if (option != (const char *) NULL)
382 quantize_info->dither_method=(DitherMethod) ParseMagickOption(
383 MagickDitherOptions,MagickFalse,option);
384 quantize_info->measure_error=image_info->verbose;
385 }
386 return(quantize_info);
387}
388
389/*
390%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
391% %
392% %
393% %
394+ A s s i g n I m a g e C o l o r s %
395% %
396% %
397% %
398%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399%
400% AssignImageColors() generates the output image from the pruned tree. The
401% output image consists of two parts: (1) A color map, which is an array
402% of color descriptions (RGB triples) for each color present in the
403% output image; (2) A pixel array, which represents each pixel as an
404% index into the color map array.
405%
406% First, the assignment phase makes one pass over the pruned color
407% description tree to establish the image's color map. For each node
408% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
409% color of all pixels that classify no lower than this node. Each of
410% these colors becomes an entry in the color map.
411%
412% Finally, the assignment phase reclassifies each pixel in the pruned
413% tree to identify the deepest node containing the pixel's color. The
414% pixel's value in the pixel array becomes the index of this node's mean
415% color in the color map.
416%
417% The format of the AssignImageColors() method is:
418%
419% MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
420%
421% A description of each parameter follows.
422%
423% o image: the image.
424%
425% o cube_info: A pointer to the Cube structure.
426%
427*/
428
429static inline void AssociateAlphaPixel(const CubeInfo *cube_info,
430 const PixelPacket *pixel,RealPixelPacket *alpha_pixel)
431{
432 MagickRealType
433 alpha;
434
435 if ((cube_info->associate_alpha == MagickFalse) ||
436 (pixel->opacity == OpaqueOpacity))
437 {
438 alpha_pixel->red=(MagickRealType) pixel->red;
439 alpha_pixel->green=(MagickRealType) pixel->green;
440 alpha_pixel->blue=(MagickRealType) pixel->blue;
441 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
442 return;
443 }
444 alpha=(MagickRealType) (QuantumScale*(QuantumRange-pixel->opacity));
445 alpha_pixel->red=alpha*pixel->red;
446 alpha_pixel->green=alpha*pixel->green;
447 alpha_pixel->blue=alpha*pixel->blue;
448 alpha_pixel->opacity=(MagickRealType) pixel->opacity;
449}
450
cristy75ffdb72010-01-07 17:40:12 +0000451static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
cristy3ed852e2009-09-05 21:47:34 +0000452{
453 if (value <= 0.0)
454 return((Quantum) 0);
455 if (value >= QuantumRange)
456 return((Quantum) QuantumRange);
457 return((Quantum) (value+0.5));
458}
459
cristybb503372010-05-27 20:51:26 +0000460static inline size_t ColorToNodeId(const CubeInfo *cube_info,
461 const RealPixelPacket *pixel,size_t index)
cristy3ed852e2009-09-05 21:47:34 +0000462{
cristybb503372010-05-27 20:51:26 +0000463 size_t
cristy3ed852e2009-09-05 21:47:34 +0000464 id;
465
cristybb503372010-05-27 20:51:26 +0000466 id=(size_t) (
cristy75ffdb72010-01-07 17:40:12 +0000467 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x1) |
468 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x1) << 1 |
469 ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x1) << 2);
cristy3ed852e2009-09-05 21:47:34 +0000470 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +0000471 id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->opacity)) >> index) & 0x1)
cristy3ed852e2009-09-05 21:47:34 +0000472 << 3;
473 return(id);
474}
475
476static inline MagickBooleanType IsSameColor(const Image *image,
477 const PixelPacket *p,const PixelPacket *q)
478{
479 if ((p->red != q->red) || (p->green != q->green) || (p->blue != q->blue))
480 return(MagickFalse);
481 if ((image->matte != MagickFalse) && (p->opacity != q->opacity))
482 return(MagickFalse);
483 return(MagickTrue);
484}
485
486static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
487{
488#define AssignImageTag "Assign/Image"
489
cristyecc31b12011-02-13 00:32:29 +0000490 ssize_t
cristyecc31b12011-02-13 00:32:29 +0000491 y;
492
cristy3ed852e2009-09-05 21:47:34 +0000493 /*
494 Allocate image colormap.
495 */
496 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
497 (cube_info->quantize_info->colorspace != CMYKColorspace))
498 (void) TransformImageColorspace((Image *) image,
499 cube_info->quantize_info->colorspace);
500 else
501 if ((image->colorspace != GRAYColorspace) &&
502 (image->colorspace != RGBColorspace) &&
503 (image->colorspace != CMYColorspace))
504 (void) TransformImageColorspace((Image *) image,RGBColorspace);
505 if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
506 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
507 image->filename);
508 image->colors=0;
509 cube_info->transparent_pixels=0;
510 cube_info->transparent_index=(-1);
511 (void) DefineImageColormap(image,cube_info,cube_info->root);
512 /*
513 Create a reduced color image.
514 */
515 if ((cube_info->quantize_info->dither != MagickFalse) &&
cristyd5acfd12010-06-15 00:11:38 +0000516 (cube_info->quantize_info->dither_method != NoDitherMethod))
cristy3ed852e2009-09-05 21:47:34 +0000517 (void) DitherImage(image,cube_info);
518 else
519 {
cristy3ed852e2009-09-05 21:47:34 +0000520 CacheView
521 *image_view;
522
cristye9717ac2011-02-20 16:17:17 +0000523 ExceptionInfo
524 *exception;
525
526 MagickBooleanType
527 status;
528
529 status=MagickTrue;
cristy3ed852e2009-09-05 21:47:34 +0000530 exception=(&image->exception);
531 image_view=AcquireCacheView(image);
cristye9717ac2011-02-20 16:17:17 +0000532#if defined(MAGICKCORE_OPENMP_SUPPORT)
533 #pragma omp parallel for schedule(dynamic,4) shared(status)
534#endif
cristybb503372010-05-27 20:51:26 +0000535 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000536 {
cristye9717ac2011-02-20 16:17:17 +0000537 CubeInfo
538 cube;
539
cristy3ed852e2009-09-05 21:47:34 +0000540 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +0000541 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +0000542
543 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000544 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000545
cristye9717ac2011-02-20 16:17:17 +0000546 register ssize_t
547 x;
548
549 ssize_t
550 count;
551
552 if (status == MagickFalse)
553 continue;
cristy3ed852e2009-09-05 21:47:34 +0000554 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
555 exception);
556 if (q == (PixelPacket *) NULL)
cristye9717ac2011-02-20 16:17:17 +0000557 {
558 status=MagickFalse;
559 continue;
560 }
cristy3ed852e2009-09-05 21:47:34 +0000561 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristye9717ac2011-02-20 16:17:17 +0000562 cube=(*cube_info);
cristybb503372010-05-27 20:51:26 +0000563 for (x=0; x < (ssize_t) image->columns; x+=count)
cristy3ed852e2009-09-05 21:47:34 +0000564 {
cristye9717ac2011-02-20 16:17:17 +0000565 RealPixelPacket
566 pixel;
567
568 register const NodeInfo
569 *node_info;
570
571 register ssize_t
572 i;
573
574 size_t
575 id,
576 index;
577
cristy3ed852e2009-09-05 21:47:34 +0000578 /*
579 Identify the deepest node containing the pixel's color.
580 */
cristybb503372010-05-27 20:51:26 +0000581 for (count=1; (x+count) < (ssize_t) image->columns; count++)
cristy3ed852e2009-09-05 21:47:34 +0000582 if (IsSameColor(image,q,q+count) == MagickFalse)
583 break;
cristye9717ac2011-02-20 16:17:17 +0000584 AssociateAlphaPixel(&cube,q,&pixel);
585 node_info=cube.root;
cristybb503372010-05-27 20:51:26 +0000586 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +0000587 {
cristye9717ac2011-02-20 16:17:17 +0000588 id=ColorToNodeId(&cube,&pixel,index);
cristy3ed852e2009-09-05 21:47:34 +0000589 if (node_info->child[id] == (NodeInfo *) NULL)
590 break;
591 node_info=node_info->child[id];
592 }
593 /*
594 Find closest color among siblings and their children.
595 */
cristye9717ac2011-02-20 16:17:17 +0000596 cube.target=pixel;
597 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
cristy3ed852e2009-09-05 21:47:34 +0000598 (QuantumRange+1.0)+1.0);
cristye9717ac2011-02-20 16:17:17 +0000599 ClosestColor(image,&cube,node_info->parent);
600 index=cube.color_number;
cristybb503372010-05-27 20:51:26 +0000601 for (i=0; i < (ssize_t) count; i++)
cristy3ed852e2009-09-05 21:47:34 +0000602 {
603 if (image->storage_class == PseudoClass)
604 indexes[x+i]=(IndexPacket) index;
cristye9717ac2011-02-20 16:17:17 +0000605 if (cube.quantize_info->measure_error == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +0000606 {
607 q->red=image->colormap[index].red;
608 q->green=image->colormap[index].green;
609 q->blue=image->colormap[index].blue;
cristye9717ac2011-02-20 16:17:17 +0000610 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +0000611 q->opacity=image->colormap[index].opacity;
612 }
613 q++;
614 }
615 }
616 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
cristye9717ac2011-02-20 16:17:17 +0000617 status=MagickFalse;
618 if (image->progress_monitor != (MagickProgressMonitor) NULL)
619 {
620 MagickBooleanType
621 proceed;
622
623#if defined(MAGICKCORE_OPENMP_SUPPORT)
624 #pragma omp critical (MagickCore_AssignImageColors)
625#endif
626 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
627 image->rows);
628 if (proceed == MagickFalse)
629 status=MagickFalse;
630 }
cristy3ed852e2009-09-05 21:47:34 +0000631 }
632 image_view=DestroyCacheView(image_view);
633 }
634 if (cube_info->quantize_info->measure_error != MagickFalse)
635 (void) GetImageQuantizeError(image);
636 if ((cube_info->quantize_info->number_colors == 2) &&
637 (cube_info->quantize_info->colorspace == GRAYColorspace))
638 {
639 Quantum
640 intensity;
641
642 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000643 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +0000644
cristye9717ac2011-02-20 16:17:17 +0000645 register ssize_t
646 i;
647
cristy3ed852e2009-09-05 21:47:34 +0000648 /*
649 Monochrome image.
650 */
651 q=image->colormap;
cristybb503372010-05-27 20:51:26 +0000652 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +0000653 {
654 intensity=(Quantum) (PixelIntensity(q) < ((MagickRealType)
655 QuantumRange/2.0) ? 0 : QuantumRange);
656 q->red=intensity;
657 q->green=intensity;
658 q->blue=intensity;
659 q++;
660 }
661 }
662 (void) SyncImage(image);
663 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
664 (cube_info->quantize_info->colorspace != CMYKColorspace))
665 (void) TransformImageColorspace((Image *) image,RGBColorspace);
666 return(MagickTrue);
667}
668
669/*
670%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
671% %
672% %
673% %
674+ C l a s s i f y I m a g e C o l o r s %
675% %
676% %
677% %
678%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
679%
680% ClassifyImageColors() begins by initializing a color description tree
681% of sufficient depth to represent each possible input color in a leaf.
682% However, it is impractical to generate a fully-formed color
683% description tree in the storage_class phase for realistic values of
684% Cmax. If colors components in the input image are quantized to k-bit
685% precision, so that Cmax= 2k-1, the tree would need k levels below the
686% root node to allow representing each possible input color in a leaf.
687% This becomes prohibitive because the tree's total number of nodes is
688% 1 + sum(i=1,k,8k).
689%
690% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
691% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
692% Initializes data structures for nodes only as they are needed; (2)
693% Chooses a maximum depth for the tree as a function of the desired
694% number of colors in the output image (currently log2(colormap size)).
695%
696% For each pixel in the input image, storage_class scans downward from
697% the root of the color description tree. At each level of the tree it
698% identifies the single node which represents a cube in RGB space
699% containing It updates the following data for each such node:
700%
701% n1 : Number of pixels whose color is contained in the RGB cube
702% which this node represents;
703%
704% n2 : Number of pixels whose color is not represented in a node at
705% lower depth in the tree; initially, n2 = 0 for all nodes except
706% leaves of the tree.
707%
708% Sr, Sg, Sb : Sums of the red, green, and blue component values for
709% all pixels not classified at a lower depth. The combination of
710% these sums and n2 will ultimately characterize the mean color of a
711% set of pixels represented by this node.
712%
713% E: the distance squared in RGB space between each pixel contained
714% within a node and the nodes' center. This represents the quantization
715% error for a node.
716%
717% The format of the ClassifyImageColors() method is:
718%
719% MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
720% const Image *image,ExceptionInfo *exception)
721%
722% A description of each parameter follows.
723%
724% o cube_info: A pointer to the Cube structure.
725%
726% o image: the image.
727%
728*/
729
730static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
731{
732 MagickBooleanType
733 associate_alpha;
734
735 associate_alpha=image->matte;
736 if (cube_info->quantize_info->colorspace == TransparentColorspace)
737 associate_alpha=MagickFalse;
738 if ((cube_info->quantize_info->number_colors == 2) &&
739 (cube_info->quantize_info->colorspace == GRAYColorspace))
740 associate_alpha=MagickFalse;
741 cube_info->associate_alpha=associate_alpha;
742}
743
744static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
745 const Image *image,ExceptionInfo *exception)
746{
747#define ClassifyImageTag "Classify/Image"
748
cristyc4c8d132010-01-07 01:58:38 +0000749 CacheView
750 *image_view;
751
cristy3ed852e2009-09-05 21:47:34 +0000752 MagickBooleanType
753 proceed;
754
755 MagickRealType
756 bisect;
757
758 NodeInfo
759 *node_info;
760
761 RealPixelPacket
762 error,
763 mid,
764 midpoint,
765 pixel;
766
767 size_t
cristyecc31b12011-02-13 00:32:29 +0000768 count,
cristy3ed852e2009-09-05 21:47:34 +0000769 id,
770 index,
771 level;
772
cristyecc31b12011-02-13 00:32:29 +0000773 ssize_t
774 y;
775
cristy3ed852e2009-09-05 21:47:34 +0000776 /*
777 Classify the first cube_info->maximum_colors colors to a tree depth of 8.
778 */
779 SetAssociatedAlpha(image,cube_info);
780 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
781 (cube_info->quantize_info->colorspace != CMYKColorspace))
782 (void) TransformImageColorspace((Image *) image,
783 cube_info->quantize_info->colorspace);
784 else
785 if ((image->colorspace != GRAYColorspace) &&
786 (image->colorspace != CMYColorspace) &&
787 (image->colorspace != RGBColorspace))
788 (void) TransformImageColorspace((Image *) image,RGBColorspace);
789 midpoint.red=(MagickRealType) QuantumRange/2.0;
790 midpoint.green=(MagickRealType) QuantumRange/2.0;
791 midpoint.blue=(MagickRealType) QuantumRange/2.0;
792 midpoint.opacity=(MagickRealType) QuantumRange/2.0;
793 error.opacity=0.0;
794 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +0000795 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000796 {
797 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000798 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000799
cristybb503372010-05-27 20:51:26 +0000800 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000801 x;
802
803 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
804 if (p == (const PixelPacket *) NULL)
805 break;
806 if (cube_info->nodes > MaxNodes)
807 {
808 /*
809 Prune one level if the color tree is too large.
810 */
811 PruneLevel(image,cube_info,cube_info->root);
812 cube_info->depth--;
813 }
cristybb503372010-05-27 20:51:26 +0000814 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
cristy3ed852e2009-09-05 21:47:34 +0000815 {
816 /*
817 Start at the root and descend the color cube tree.
818 */
cristybb66d9c2010-10-09 01:40:31 +0000819 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
cristy3ed852e2009-09-05 21:47:34 +0000820 if (IsSameColor(image,p,p+count) == MagickFalse)
821 break;
822 AssociateAlphaPixel(cube_info,p,&pixel);
823 index=MaxTreeDepth-1;
824 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
825 mid=midpoint;
826 node_info=cube_info->root;
827 for (level=1; level <= MaxTreeDepth; level++)
828 {
829 bisect*=0.5;
830 id=ColorToNodeId(cube_info,&pixel,index);
831 mid.red+=(id & 1) != 0 ? bisect : -bisect;
832 mid.green+=(id & 2) != 0 ? bisect : -bisect;
833 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
834 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
835 if (node_info->child[id] == (NodeInfo *) NULL)
836 {
837 /*
838 Set colors of new node to contain pixel.
839 */
840 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
841 if (node_info->child[id] == (NodeInfo *) NULL)
842 (void) ThrowMagickException(exception,GetMagickModule(),
843 ResourceLimitError,"MemoryAllocationFailed","`%s'",
844 image->filename);
845 if (level == MaxTreeDepth)
846 cube_info->colors++;
847 }
848 /*
849 Approximate the quantization error represented by this node.
850 */
851 node_info=node_info->child[id];
852 error.red=QuantumScale*(pixel.red-mid.red);
853 error.green=QuantumScale*(pixel.green-mid.green);
854 error.blue=QuantumScale*(pixel.blue-mid.blue);
855 if (cube_info->associate_alpha != MagickFalse)
856 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
857 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
858 count*error.green*error.green+count*error.blue*error.blue+
859 count*error.opacity*error.opacity));
860 cube_info->root->quantize_error+=node_info->quantize_error;
861 index--;
862 }
863 /*
864 Sum RGB for this leaf for later derivation of the mean cube color.
865 */
866 node_info->number_unique+=count;
867 node_info->total_color.red+=count*QuantumScale*pixel.red;
868 node_info->total_color.green+=count*QuantumScale*pixel.green;
869 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
870 if (cube_info->associate_alpha != MagickFalse)
871 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
872 p+=count;
873 }
874 if (cube_info->colors > cube_info->maximum_colors)
875 {
876 PruneToCubeDepth(image,cube_info,cube_info->root);
877 break;
878 }
cristycee97112010-05-28 00:44:52 +0000879 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
880 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000881 if (proceed == MagickFalse)
882 break;
883 }
cristybb503372010-05-27 20:51:26 +0000884 for (y++; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +0000885 {
886 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +0000887 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +0000888
cristybb503372010-05-27 20:51:26 +0000889 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +0000890 x;
891
892 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
893 if (p == (const PixelPacket *) NULL)
894 break;
895 if (cube_info->nodes > MaxNodes)
896 {
897 /*
898 Prune one level if the color tree is too large.
899 */
900 PruneLevel(image,cube_info,cube_info->root);
901 cube_info->depth--;
902 }
cristybb503372010-05-27 20:51:26 +0000903 for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
cristy3ed852e2009-09-05 21:47:34 +0000904 {
905 /*
906 Start at the root and descend the color cube tree.
907 */
cristybb66d9c2010-10-09 01:40:31 +0000908 for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
cristy3ed852e2009-09-05 21:47:34 +0000909 if (IsSameColor(image,p,p+count) == MagickFalse)
910 break;
911 AssociateAlphaPixel(cube_info,p,&pixel);
912 index=MaxTreeDepth-1;
913 bisect=((MagickRealType) QuantumRange+1.0)/2.0;
914 mid=midpoint;
915 node_info=cube_info->root;
916 for (level=1; level <= cube_info->depth; level++)
917 {
918 bisect*=0.5;
919 id=ColorToNodeId(cube_info,&pixel,index);
920 mid.red+=(id & 1) != 0 ? bisect : -bisect;
921 mid.green+=(id & 2) != 0 ? bisect : -bisect;
922 mid.blue+=(id & 4) != 0 ? bisect : -bisect;
923 mid.opacity+=(id & 8) != 0 ? bisect : -bisect;
924 if (node_info->child[id] == (NodeInfo *) NULL)
925 {
926 /*
927 Set colors of new node to contain pixel.
928 */
929 node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
930 if (node_info->child[id] == (NodeInfo *) NULL)
931 (void) ThrowMagickException(exception,GetMagickModule(),
932 ResourceLimitError,"MemoryAllocationFailed","%s",
933 image->filename);
934 if (level == cube_info->depth)
935 cube_info->colors++;
936 }
937 /*
938 Approximate the quantization error represented by this node.
939 */
940 node_info=node_info->child[id];
941 error.red=QuantumScale*(pixel.red-mid.red);
942 error.green=QuantumScale*(pixel.green-mid.green);
943 error.blue=QuantumScale*(pixel.blue-mid.blue);
944 if (cube_info->associate_alpha != MagickFalse)
945 error.opacity=QuantumScale*(pixel.opacity-mid.opacity);
946 node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
cristy83b6e792011-01-26 15:46:06 +0000947 count*error.green*error.green+count*error.blue*error.blue+
cristy3ed852e2009-09-05 21:47:34 +0000948 count*error.opacity*error.opacity));
949 cube_info->root->quantize_error+=node_info->quantize_error;
950 index--;
951 }
952 /*
953 Sum RGB for this leaf for later derivation of the mean cube color.
954 */
955 node_info->number_unique+=count;
956 node_info->total_color.red+=count*QuantumScale*pixel.red;
957 node_info->total_color.green+=count*QuantumScale*pixel.green;
958 node_info->total_color.blue+=count*QuantumScale*pixel.blue;
959 if (cube_info->associate_alpha != MagickFalse)
960 node_info->total_color.opacity+=count*QuantumScale*pixel.opacity;
961 p+=count;
962 }
cristycee97112010-05-28 00:44:52 +0000963 proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
964 image->rows);
cristy3ed852e2009-09-05 21:47:34 +0000965 if (proceed == MagickFalse)
966 break;
967 }
968 image_view=DestroyCacheView(image_view);
969 if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
970 (cube_info->quantize_info->colorspace != CMYKColorspace))
971 (void) TransformImageColorspace((Image *) image,RGBColorspace);
972 return(MagickTrue);
973}
974
975/*
976%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
977% %
978% %
979% %
980% C l o n e Q u a n t i z e I n f o %
981% %
982% %
983% %
984%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
985%
986% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
987% or if quantize info is NULL, a new one.
988%
989% The format of the CloneQuantizeInfo method is:
990%
991% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
992%
993% A description of each parameter follows:
994%
995% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
996% quantize info, or if image info is NULL a new one.
997%
998% o quantize_info: a structure of type info.
999%
1000*/
1001MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
1002{
1003 QuantizeInfo
1004 *clone_info;
1005
cristy73bd4a52010-10-05 11:24:23 +00001006 clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
cristy3ed852e2009-09-05 21:47:34 +00001007 if (clone_info == (QuantizeInfo *) NULL)
1008 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
1009 GetQuantizeInfo(clone_info);
1010 if (quantize_info == (QuantizeInfo *) NULL)
1011 return(clone_info);
1012 clone_info->number_colors=quantize_info->number_colors;
1013 clone_info->tree_depth=quantize_info->tree_depth;
1014 clone_info->dither=quantize_info->dither;
1015 clone_info->dither_method=quantize_info->dither_method;
1016 clone_info->colorspace=quantize_info->colorspace;
1017 clone_info->measure_error=quantize_info->measure_error;
1018 return(clone_info);
1019}
1020
1021/*
1022%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1023% %
1024% %
1025% %
1026+ C l o s e s t C o l o r %
1027% %
1028% %
1029% %
1030%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1031%
1032% ClosestColor() traverses the color cube tree at a particular node and
1033% determines which colormap entry best represents the input color.
1034%
1035% The format of the ClosestColor method is:
1036%
1037% void ClosestColor(const Image *image,CubeInfo *cube_info,
1038% const NodeInfo *node_info)
1039%
1040% A description of each parameter follows.
1041%
1042% o image: the image.
1043%
1044% o cube_info: A pointer to the Cube structure.
1045%
1046% o node_info: the address of a structure of type NodeInfo which points to a
1047% node in the color cube tree that is to be pruned.
1048%
1049*/
1050static void ClosestColor(const Image *image,CubeInfo *cube_info,
1051 const NodeInfo *node_info)
1052{
cristybb503372010-05-27 20:51:26 +00001053 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001054 i;
1055
cristybb503372010-05-27 20:51:26 +00001056 size_t
cristy3ed852e2009-09-05 21:47:34 +00001057 number_children;
1058
1059 /*
1060 Traverse any children.
1061 */
1062 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00001063 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00001064 if (node_info->child[i] != (NodeInfo *) NULL)
1065 ClosestColor(image,cube_info,node_info->child[i]);
1066 if (node_info->number_unique != 0)
1067 {
1068 MagickRealType
1069 pixel;
1070
1071 register MagickRealType
1072 alpha,
1073 beta,
1074 distance;
1075
1076 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001077 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00001078
1079 register RealPixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001080 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001081
1082 /*
1083 Determine if this color is "closest".
1084 */
1085 p=image->colormap+node_info->color_number;
1086 q=(&cube_info->target);
1087 alpha=1.0;
1088 beta=1.0;
cristy847620f2011-02-09 02:24:21 +00001089 if (cube_info->associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001090 {
cristy46f08202010-01-10 04:04:21 +00001091 alpha=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(p));
1092 beta=(MagickRealType) (QuantumScale*GetAlphaPixelComponent(q));
cristy3ed852e2009-09-05 21:47:34 +00001093 }
1094 pixel=alpha*p->red-beta*q->red;
1095 distance=pixel*pixel;
cristy36fbc3b2011-02-09 02:30:04 +00001096 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001097 {
1098 pixel=alpha*p->green-beta*q->green;
1099 distance+=pixel*pixel;
cristy36fbc3b2011-02-09 02:30:04 +00001100 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001101 {
1102 pixel=alpha*p->blue-beta*q->blue;
1103 distance+=pixel*pixel;
cristy36fbc3b2011-02-09 02:30:04 +00001104 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001105 {
1106 pixel=alpha-beta;
1107 distance+=pixel*pixel;
cristyc4080402011-02-09 02:55:58 +00001108 if (distance <= cube_info->distance)
cristy3ed852e2009-09-05 21:47:34 +00001109 {
1110 cube_info->distance=distance;
1111 cube_info->color_number=node_info->color_number;
1112 }
1113 }
1114 }
1115 }
1116 }
1117}
1118
1119/*
1120%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1121% %
1122% %
1123% %
1124% C o m p r e s s I m a g e C o l o r m a p %
1125% %
1126% %
1127% %
1128%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1129%
1130% CompressImageColormap() compresses an image colormap by removing any
1131% duplicate or unused color entries.
1132%
1133% The format of the CompressImageColormap method is:
1134%
1135% MagickBooleanType CompressImageColormap(Image *image)
1136%
1137% A description of each parameter follows:
1138%
1139% o image: the image.
1140%
1141*/
1142MagickExport MagickBooleanType CompressImageColormap(Image *image)
1143{
1144 QuantizeInfo
1145 quantize_info;
1146
1147 assert(image != (Image *) NULL);
1148 assert(image->signature == MagickSignature);
1149 if (image->debug != MagickFalse)
1150 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1151 if (IsPaletteImage(image,&image->exception) == MagickFalse)
1152 return(MagickFalse);
1153 GetQuantizeInfo(&quantize_info);
1154 quantize_info.number_colors=image->colors;
1155 quantize_info.tree_depth=MaxTreeDepth;
1156 return(QuantizeImage(&quantize_info,image));
1157}
1158
1159/*
1160%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1161% %
1162% %
1163% %
1164+ D e f i n e I m a g e C o l o r m a p %
1165% %
1166% %
1167% %
1168%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1169%
1170% DefineImageColormap() traverses the color cube tree and notes each colormap
1171% entry. A colormap entry is any node in the color cube tree where the
1172% of unique colors is not zero. DefineImageColormap() returns the number of
1173% colors in the image colormap.
1174%
1175% The format of the DefineImageColormap method is:
1176%
cristybb503372010-05-27 20:51:26 +00001177% size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
cristy3ed852e2009-09-05 21:47:34 +00001178% NodeInfo *node_info)
1179%
1180% A description of each parameter follows.
1181%
1182% o image: the image.
1183%
1184% o cube_info: A pointer to the Cube structure.
1185%
1186% o node_info: the address of a structure of type NodeInfo which points to a
1187% node in the color cube tree that is to be pruned.
1188%
1189*/
cristybb503372010-05-27 20:51:26 +00001190static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
cristy3ed852e2009-09-05 21:47:34 +00001191 NodeInfo *node_info)
1192{
cristybb503372010-05-27 20:51:26 +00001193 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001194 i;
1195
cristybb503372010-05-27 20:51:26 +00001196 size_t
cristy3ed852e2009-09-05 21:47:34 +00001197 number_children;
1198
1199 /*
1200 Traverse any children.
1201 */
1202 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00001203 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00001204 if (node_info->child[i] != (NodeInfo *) NULL)
cristycee97112010-05-28 00:44:52 +00001205 (void) DefineImageColormap(image,cube_info,node_info->child[i]);
cristy3ed852e2009-09-05 21:47:34 +00001206 if (node_info->number_unique != 0)
1207 {
1208 register MagickRealType
1209 alpha;
1210
1211 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001212 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001213
1214 /*
1215 Colormap entry is defined by the mean color in this cube.
1216 */
1217 q=image->colormap+image->colors;
1218 alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
1219 alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
1220 if (cube_info->associate_alpha == MagickFalse)
1221 {
cristyce70c172010-01-07 17:15:30 +00001222 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001223 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001224 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001225 node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001226 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001227 node_info->total_color.blue));
cristyce70c172010-01-07 17:15:30 +00001228 SetOpacityPixelComponent(q,OpaqueOpacity);
cristy3ed852e2009-09-05 21:47:34 +00001229 }
1230 else
1231 {
1232 MagickRealType
1233 opacity;
1234
1235 opacity=(MagickRealType) (alpha*QuantumRange*
1236 node_info->total_color.opacity);
cristyce70c172010-01-07 17:15:30 +00001237 q->opacity=ClampToQuantum(opacity);
cristy3ed852e2009-09-05 21:47:34 +00001238 if (q->opacity == OpaqueOpacity)
1239 {
cristyce70c172010-01-07 17:15:30 +00001240 q->red=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001241 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001242 q->green=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001243 node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001244 q->blue=ClampToQuantum((MagickRealType) (alpha*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001245 node_info->total_color.blue));
1246 }
1247 else
1248 {
1249 MagickRealType
1250 gamma;
1251
1252 gamma=(MagickRealType) (QuantumScale*(QuantumRange-
1253 (MagickRealType) q->opacity));
1254 gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
cristyce70c172010-01-07 17:15:30 +00001255 q->red=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001256 node_info->total_color.red));
cristyce70c172010-01-07 17:15:30 +00001257 q->green=ClampToQuantum((MagickRealType) (alpha*gamma*
cristy3ed852e2009-09-05 21:47:34 +00001258 QuantumRange*node_info->total_color.green));
cristyce70c172010-01-07 17:15:30 +00001259 q->blue=ClampToQuantum((MagickRealType) (alpha*gamma*QuantumRange*
cristy3ed852e2009-09-05 21:47:34 +00001260 node_info->total_color.blue));
1261 if (node_info->number_unique > cube_info->transparent_pixels)
1262 {
1263 cube_info->transparent_pixels=node_info->number_unique;
cristybb503372010-05-27 20:51:26 +00001264 cube_info->transparent_index=(ssize_t) image->colors;
cristy3ed852e2009-09-05 21:47:34 +00001265 }
1266 }
1267 }
1268 node_info->color_number=image->colors++;
1269 }
1270 return(image->colors);
1271}
1272
1273/*
1274%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1275% %
1276% %
1277% %
1278+ D e s t r o y C u b e I n f o %
1279% %
1280% %
1281% %
1282%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1283%
1284% DestroyCubeInfo() deallocates memory associated with an image.
1285%
1286% The format of the DestroyCubeInfo method is:
1287%
1288% DestroyCubeInfo(CubeInfo *cube_info)
1289%
1290% A description of each parameter follows:
1291%
1292% o cube_info: the address of a structure of type CubeInfo.
1293%
1294*/
1295static void DestroyCubeInfo(CubeInfo *cube_info)
1296{
1297 register Nodes
1298 *nodes;
1299
1300 /*
1301 Release color cube tree storage.
1302 */
1303 do
1304 {
1305 nodes=cube_info->node_queue->next;
1306 cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
1307 cube_info->node_queue->nodes);
1308 cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
1309 cube_info->node_queue);
1310 cube_info->node_queue=nodes;
1311 } while (cube_info->node_queue != (Nodes *) NULL);
cristybb503372010-05-27 20:51:26 +00001312 if (cube_info->cache != (ssize_t *) NULL)
1313 cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
cristy3ed852e2009-09-05 21:47:34 +00001314 cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
1315 cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
1316}
1317
1318/*
1319%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1320% %
1321% %
1322% %
1323% D e s t r o y Q u a n t i z e I n f o %
1324% %
1325% %
1326% %
1327%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1328%
1329% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
1330% structure.
1331%
1332% The format of the DestroyQuantizeInfo method is:
1333%
1334% QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1335%
1336% A description of each parameter follows:
1337%
1338% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1339%
1340*/
1341MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
1342{
1343 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1344 assert(quantize_info != (QuantizeInfo *) NULL);
1345 assert(quantize_info->signature == MagickSignature);
1346 quantize_info->signature=(~MagickSignature);
1347 quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
1348 return(quantize_info);
1349}
1350
1351/*
1352%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1353% %
1354% %
1355% %
1356+ D i t h e r I m a g e %
1357% %
1358% %
1359% %
1360%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1361%
1362% DitherImage() distributes the difference between an original image and
1363% the corresponding color reduced algorithm to neighboring pixels using
1364% serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
1365% MagickTrue if the image is dithered otherwise MagickFalse.
1366%
1367% The format of the DitherImage method is:
1368%
1369% MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1370%
1371% A description of each parameter follows.
1372%
1373% o image: the image.
1374%
1375% o cube_info: A pointer to the Cube structure.
1376%
1377*/
1378
cristye9717ac2011-02-20 16:17:17 +00001379static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
1380{
1381 register ssize_t
1382 i;
1383
1384 assert(pixels != (RealPixelPacket **) NULL);
1385 for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
1386 if (pixels[i] != (RealPixelPacket *) NULL)
1387 pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
1388 pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
1389 return(pixels);
1390}
1391
1392static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
1393{
1394 RealPixelPacket
1395 **pixels;
1396
1397 register ssize_t
1398 i;
1399
1400 size_t
1401 number_threads;
1402
1403 number_threads=GetOpenMPMaximumThreads();
1404 pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
1405 sizeof(*pixels));
1406 if (pixels == (RealPixelPacket **) NULL)
1407 return((RealPixelPacket **) NULL);
1408 (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
1409 for (i=0; i < (ssize_t) number_threads; i++)
1410 {
1411 pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
1412 2*sizeof(**pixels));
1413 if (pixels[i] == (RealPixelPacket *) NULL)
1414 return(DestroyPixelThreadSet(pixels));
1415 }
1416 return(pixels);
1417}
1418
cristyca972de2010-06-20 23:37:02 +00001419static inline ssize_t CacheOffset(CubeInfo *cube_info,
1420 const RealPixelPacket *pixel)
1421{
1422#define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
1423#define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
1424#define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
1425#define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
1426
1427 ssize_t
1428 offset;
1429
1430 offset=(ssize_t)
cristy15893a42010-11-20 18:57:15 +00001431 (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
cristyca972de2010-06-20 23:37:02 +00001432 GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
cristy15893a42010-11-20 18:57:15 +00001433 BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
cristyca972de2010-06-20 23:37:02 +00001434 if (cube_info->associate_alpha != MagickFalse)
cristy15893a42010-11-20 18:57:15 +00001435 offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
1436 pixel->opacity)));
cristyca972de2010-06-20 23:37:02 +00001437 return(offset);
1438}
1439
cristy3ed852e2009-09-05 21:47:34 +00001440static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
1441{
1442#define DitherImageTag "Dither/Image"
1443
cristyc4c8d132010-01-07 01:58:38 +00001444 CacheView
1445 *image_view;
1446
cristy3ed852e2009-09-05 21:47:34 +00001447 ExceptionInfo
1448 *exception;
1449
cristy3ed852e2009-09-05 21:47:34 +00001450 MagickBooleanType
cristye9717ac2011-02-20 16:17:17 +00001451 status;
cristy3ed852e2009-09-05 21:47:34 +00001452
1453 RealPixelPacket
cristye9717ac2011-02-20 16:17:17 +00001454 **pixels;
cristy3ed852e2009-09-05 21:47:34 +00001455
cristy847620f2011-02-09 02:24:21 +00001456 ssize_t
cristy847620f2011-02-09 02:24:21 +00001457 y;
1458
cristy3ed852e2009-09-05 21:47:34 +00001459 /*
1460 Distribute quantization error using Floyd-Steinberg.
1461 */
cristye9717ac2011-02-20 16:17:17 +00001462 pixels=AcquirePixelThreadSet(image->columns);
1463 if (pixels == (RealPixelPacket **) NULL)
cristy3ed852e2009-09-05 21:47:34 +00001464 return(MagickFalse);
cristy3ed852e2009-09-05 21:47:34 +00001465 exception=(&image->exception);
cristye9717ac2011-02-20 16:17:17 +00001466 status=MagickTrue;
cristy3ed852e2009-09-05 21:47:34 +00001467 image_view=AcquireCacheView(image);
cristy00cbdd62011-02-20 17:29:26 +00001468#if defined(MAGICKCORE_OPENMP_SUPPORT)
1469 #pragma omp parallel for schedule(dynamic,4) shared(status)
1470#endif
cristybb503372010-05-27 20:51:26 +00001471 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00001472 {
cristye9717ac2011-02-20 16:17:17 +00001473 const int
1474 id = GetOpenMPThreadId();
1475
1476 CubeInfo
1477 cube;
1478
1479 RealPixelPacket
1480 *current,
1481 *previous;
1482
cristy3ed852e2009-09-05 21:47:34 +00001483 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00001484 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00001485
cristyecc31b12011-02-13 00:32:29 +00001486 register PixelPacket
1487 *restrict q;
1488
cristybb503372010-05-27 20:51:26 +00001489 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001490 x;
1491
cristye9717ac2011-02-20 16:17:17 +00001492 size_t
1493 index;
1494
1495 ssize_t
1496 v;
1497
1498 if (status == MagickFalse)
1499 continue;
cristy3ed852e2009-09-05 21:47:34 +00001500 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1501 if (q == (PixelPacket *) NULL)
cristye9717ac2011-02-20 16:17:17 +00001502 {
1503 status=MagickFalse;
cristy00cbdd62011-02-20 17:29:26 +00001504 continue;
cristye9717ac2011-02-20 16:17:17 +00001505 }
cristy3ed852e2009-09-05 21:47:34 +00001506 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristye9717ac2011-02-20 16:17:17 +00001507 cube=(*cube_info);
1508 current=pixels[id]+(y & 0x01)*image->columns;
1509 previous=pixels[id]+((y+1) & 0x01)*image->columns;
cristycee97112010-05-28 00:44:52 +00001510 v=(ssize_t) ((y & 0x01) ? -1 : 1);
cristybb503372010-05-27 20:51:26 +00001511 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00001512 {
cristye9717ac2011-02-20 16:17:17 +00001513 RealPixelPacket
1514 color,
1515 pixel;
1516
1517 register ssize_t
1518 i;
1519
1520 ssize_t
1521 u;
1522
cristybb503372010-05-27 20:51:26 +00001523 u=(y & 0x01) ? (ssize_t) image->columns-1-x : x;
cristye9717ac2011-02-20 16:17:17 +00001524 AssociateAlphaPixel(&cube,q+u,&pixel);
cristy3ed852e2009-09-05 21:47:34 +00001525 if (x > 0)
1526 {
1527 pixel.red+=7*current[u-v].red/16;
1528 pixel.green+=7*current[u-v].green/16;
1529 pixel.blue+=7*current[u-v].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001530 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001531 pixel.opacity+=7*current[u-v].opacity/16;
1532 }
1533 if (y > 0)
1534 {
cristybb503372010-05-27 20:51:26 +00001535 if (x < (ssize_t) (image->columns-1))
cristy3ed852e2009-09-05 21:47:34 +00001536 {
1537 pixel.red+=previous[u+v].red/16;
1538 pixel.green+=previous[u+v].green/16;
1539 pixel.blue+=previous[u+v].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001540 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001541 pixel.opacity+=previous[u+v].opacity/16;
1542 }
1543 pixel.red+=5*previous[u].red/16;
1544 pixel.green+=5*previous[u].green/16;
1545 pixel.blue+=5*previous[u].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001546 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001547 pixel.opacity+=5*previous[u].opacity/16;
1548 if (x > 0)
1549 {
1550 pixel.red+=3*previous[u-v].red/16;
1551 pixel.green+=3*previous[u-v].green/16;
1552 pixel.blue+=3*previous[u-v].blue/16;
cristye9717ac2011-02-20 16:17:17 +00001553 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001554 pixel.opacity+=3*previous[u-v].opacity/16;
1555 }
1556 }
cristy75ffdb72010-01-07 17:40:12 +00001557 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1558 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1559 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristye9717ac2011-02-20 16:17:17 +00001560 if (cube.associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001561 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
cristye9717ac2011-02-20 16:17:17 +00001562 i=CacheOffset(&cube,&pixel);
1563 if (cube.cache[i] < 0)
cristy3ed852e2009-09-05 21:47:34 +00001564 {
1565 register NodeInfo
1566 *node_info;
1567
cristybb503372010-05-27 20:51:26 +00001568 register size_t
cristy3ed852e2009-09-05 21:47:34 +00001569 id;
1570
1571 /*
1572 Identify the deepest node containing the pixel's color.
1573 */
cristye9717ac2011-02-20 16:17:17 +00001574 node_info=cube.root;
cristybb503372010-05-27 20:51:26 +00001575 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +00001576 {
cristye9717ac2011-02-20 16:17:17 +00001577 id=ColorToNodeId(&cube,&pixel,index);
cristy3ed852e2009-09-05 21:47:34 +00001578 if (node_info->child[id] == (NodeInfo *) NULL)
1579 break;
1580 node_info=node_info->child[id];
1581 }
1582 /*
1583 Find closest color among siblings and their children.
1584 */
cristye9717ac2011-02-20 16:17:17 +00001585 cube.target=pixel;
1586 cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
cristy3ed852e2009-09-05 21:47:34 +00001587 1.0)+1.0);
cristye9717ac2011-02-20 16:17:17 +00001588 ClosestColor(image,&cube,node_info->parent);
1589 cube.cache[i]=(ssize_t) cube.color_number;
cristy3ed852e2009-09-05 21:47:34 +00001590 }
1591 /*
1592 Assign pixel to closest colormap entry.
1593 */
cristye9717ac2011-02-20 16:17:17 +00001594 index=(size_t) cube.cache[i];
cristy3ed852e2009-09-05 21:47:34 +00001595 if (image->storage_class == PseudoClass)
1596 indexes[u]=(IndexPacket) index;
cristye9717ac2011-02-20 16:17:17 +00001597 if (cube.quantize_info->measure_error == MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001598 {
1599 (q+u)->red=image->colormap[index].red;
1600 (q+u)->green=image->colormap[index].green;
1601 (q+u)->blue=image->colormap[index].blue;
cristye9717ac2011-02-20 16:17:17 +00001602 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001603 (q+u)->opacity=image->colormap[index].opacity;
1604 }
1605 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
cristye9717ac2011-02-20 16:17:17 +00001606 status=MagickFalse;
cristy3ed852e2009-09-05 21:47:34 +00001607 /*
1608 Store the error.
1609 */
cristye9717ac2011-02-20 16:17:17 +00001610 AssociateAlphaPixel(&cube,image->colormap+index,&color);
cristy3ed852e2009-09-05 21:47:34 +00001611 current[u].red=pixel.red-color.red;
1612 current[u].green=pixel.green-color.green;
1613 current[u].blue=pixel.blue-color.blue;
cristye9717ac2011-02-20 16:17:17 +00001614 if (cube.associate_alpha != MagickFalse)
cristy3ed852e2009-09-05 21:47:34 +00001615 current[u].opacity=pixel.opacity-color.opacity;
cristye9717ac2011-02-20 16:17:17 +00001616 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1617 {
1618 MagickBooleanType
1619 proceed;
1620
1621#if defined(MAGICKCORE_OPENMP_SUPPORT)
1622 #pragma omp critical (MagickCore_FloydSteinbergDither)
1623#endif
1624 proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
1625 image->rows);
1626 if (proceed == MagickFalse)
1627 status=MagickFalse;
1628 }
cristy3ed852e2009-09-05 21:47:34 +00001629 }
1630 }
cristy3ed852e2009-09-05 21:47:34 +00001631 image_view=DestroyCacheView(image_view);
cristye9717ac2011-02-20 16:17:17 +00001632 pixels=DestroyPixelThreadSet(pixels);
cristy3ed852e2009-09-05 21:47:34 +00001633 return(MagickTrue);
1634}
1635
1636static MagickBooleanType
1637 RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
1638
1639static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
cristybb503372010-05-27 20:51:26 +00001640 const size_t level,const unsigned int direction)
cristy3ed852e2009-09-05 21:47:34 +00001641{
1642 if (level == 1)
1643 switch (direction)
1644 {
1645 case WestGravity:
1646 {
1647 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1648 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1649 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1650 break;
1651 }
1652 case EastGravity:
1653 {
1654 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1655 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1656 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1657 break;
1658 }
1659 case NorthGravity:
1660 {
1661 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1662 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1663 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1664 break;
1665 }
1666 case SouthGravity:
1667 {
1668 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1669 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1670 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1671 break;
1672 }
1673 default:
1674 break;
1675 }
1676 else
1677 switch (direction)
1678 {
1679 case WestGravity:
1680 {
1681 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1682 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1683 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1684 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1685 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1686 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1687 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1688 break;
1689 }
1690 case EastGravity:
1691 {
1692 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1693 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1694 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1695 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1696 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1697 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1698 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1699 break;
1700 }
1701 case NorthGravity:
1702 {
1703 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1704 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1705 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1706 (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
1707 Riemersma(image,image_view,cube_info,level-1,NorthGravity);
1708 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1709 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1710 break;
1711 }
1712 case SouthGravity:
1713 {
1714 Riemersma(image,image_view,cube_info,level-1,EastGravity);
1715 (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
1716 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1717 (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
1718 Riemersma(image,image_view,cube_info,level-1,SouthGravity);
1719 (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
1720 Riemersma(image,image_view,cube_info,level-1,WestGravity);
1721 break;
1722 }
1723 default:
1724 break;
1725 }
1726}
1727
1728static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
1729 CubeInfo *cube_info,const unsigned int direction)
1730{
1731#define DitherImageTag "Dither/Image"
1732
1733 MagickBooleanType
1734 proceed;
1735
1736 RealPixelPacket
1737 color,
1738 pixel;
1739
1740 register CubeInfo
1741 *p;
1742
cristybb503372010-05-27 20:51:26 +00001743 size_t
cristy3ed852e2009-09-05 21:47:34 +00001744 index;
1745
1746 p=cube_info;
cristybb503372010-05-27 20:51:26 +00001747 if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
1748 (p->y >= 0) && (p->y < (ssize_t) image->rows))
cristy3ed852e2009-09-05 21:47:34 +00001749 {
1750 ExceptionInfo
1751 *exception;
1752
1753 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00001754 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00001755
cristy3ed852e2009-09-05 21:47:34 +00001756 register PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00001757 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00001758
cristyecc31b12011-02-13 00:32:29 +00001759 register ssize_t
1760 i;
1761
cristy3ed852e2009-09-05 21:47:34 +00001762 /*
1763 Distribute error.
1764 */
1765 exception=(&image->exception);
1766 q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
1767 if (q == (PixelPacket *) NULL)
1768 return(MagickFalse);
1769 indexes=GetCacheViewAuthenticIndexQueue(image_view);
1770 AssociateAlphaPixel(cube_info,q,&pixel);
1771 for (i=0; i < ErrorQueueLength; i++)
1772 {
1773 pixel.red+=p->weights[i]*p->error[i].red;
1774 pixel.green+=p->weights[i]*p->error[i].green;
1775 pixel.blue+=p->weights[i]*p->error[i].blue;
1776 if (cube_info->associate_alpha != MagickFalse)
1777 pixel.opacity+=p->weights[i]*p->error[i].opacity;
1778 }
cristy75ffdb72010-01-07 17:40:12 +00001779 pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
1780 pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
1781 pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
cristy3ed852e2009-09-05 21:47:34 +00001782 if (cube_info->associate_alpha != MagickFalse)
cristy75ffdb72010-01-07 17:40:12 +00001783 pixel.opacity=(MagickRealType) ClampToUnsignedQuantum(pixel.opacity);
cristyca972de2010-06-20 23:37:02 +00001784 i=CacheOffset(cube_info,&pixel);
cristy3ed852e2009-09-05 21:47:34 +00001785 if (p->cache[i] < 0)
1786 {
1787 register NodeInfo
1788 *node_info;
1789
cristybb503372010-05-27 20:51:26 +00001790 register size_t
cristy3ed852e2009-09-05 21:47:34 +00001791 id;
1792
1793 /*
1794 Identify the deepest node containing the pixel's color.
1795 */
1796 node_info=p->root;
cristybb503372010-05-27 20:51:26 +00001797 for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
cristy3ed852e2009-09-05 21:47:34 +00001798 {
1799 id=ColorToNodeId(cube_info,&pixel,index);
1800 if (node_info->child[id] == (NodeInfo *) NULL)
1801 break;
1802 node_info=node_info->child[id];
1803 }
cristyecc31b12011-02-13 00:32:29 +00001804 node_info=node_info->parent;
cristy3ed852e2009-09-05 21:47:34 +00001805 /*
1806 Find closest color among siblings and their children.
1807 */
1808 p->target=pixel;
1809 p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
1810 QuantumRange+1.0)+1.0);
1811 ClosestColor(image,p,node_info->parent);
cristybb503372010-05-27 20:51:26 +00001812 p->cache[i]=(ssize_t) p->color_number;
cristy3ed852e2009-09-05 21:47:34 +00001813 }
1814 /*
1815 Assign pixel to closest colormap entry.
1816 */
cristybb503372010-05-27 20:51:26 +00001817 index=(size_t) (1*p->cache[i]);
cristy3ed852e2009-09-05 21:47:34 +00001818 if (image->storage_class == PseudoClass)
1819 *indexes=(IndexPacket) index;
1820 if (cube_info->quantize_info->measure_error == MagickFalse)
1821 {
1822 q->red=image->colormap[index].red;
1823 q->green=image->colormap[index].green;
1824 q->blue=image->colormap[index].blue;
1825 if (cube_info->associate_alpha != MagickFalse)
1826 q->opacity=image->colormap[index].opacity;
1827 }
1828 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1829 return(MagickFalse);
1830 /*
1831 Propagate the error as the last entry of the error queue.
1832 */
1833 (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
1834 sizeof(p->error[0]));
1835 AssociateAlphaPixel(cube_info,image->colormap+index,&color);
1836 p->error[ErrorQueueLength-1].red=pixel.red-color.red;
1837 p->error[ErrorQueueLength-1].green=pixel.green-color.green;
1838 p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
1839 if (cube_info->associate_alpha != MagickFalse)
1840 p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity;
1841 proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
1842 if (proceed == MagickFalse)
1843 return(MagickFalse);
1844 p->offset++;
1845 }
1846 switch (direction)
1847 {
1848 case WestGravity: p->x--; break;
1849 case EastGravity: p->x++; break;
1850 case NorthGravity: p->y--; break;
1851 case SouthGravity: p->y++; break;
1852 }
1853 return(MagickTrue);
1854}
1855
cristybb503372010-05-27 20:51:26 +00001856static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
cristy3ed852e2009-09-05 21:47:34 +00001857{
1858 if (x > y)
1859 return(x);
1860 return(y);
1861}
1862
cristybb503372010-05-27 20:51:26 +00001863static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
cristy3ed852e2009-09-05 21:47:34 +00001864{
1865 if (x < y)
1866 return(x);
1867 return(y);
1868}
1869
1870static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
1871{
cristyc4c8d132010-01-07 01:58:38 +00001872 CacheView
1873 *image_view;
1874
cristy3ed852e2009-09-05 21:47:34 +00001875 MagickBooleanType
1876 status;
1877
cristybb503372010-05-27 20:51:26 +00001878 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001879 i;
1880
cristybb503372010-05-27 20:51:26 +00001881 size_t
cristy3ed852e2009-09-05 21:47:34 +00001882 depth;
1883
cristyfb7e9cd2011-02-20 16:26:15 +00001884 if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
cristy3ed852e2009-09-05 21:47:34 +00001885 return(FloydSteinbergDither(image,cube_info));
1886 /*
cristycee97112010-05-28 00:44:52 +00001887 Distribute quantization error along a Hilbert curve.
cristy3ed852e2009-09-05 21:47:34 +00001888 */
1889 (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
1890 sizeof(*cube_info->error));
1891 cube_info->x=0;
1892 cube_info->y=0;
cristybb503372010-05-27 20:51:26 +00001893 i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
cristy3ed852e2009-09-05 21:47:34 +00001894 for (depth=1; i != 0; depth++)
1895 i>>=1;
cristybb503372010-05-27 20:51:26 +00001896 if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
cristy3ed852e2009-09-05 21:47:34 +00001897 depth++;
1898 cube_info->offset=0;
1899 cube_info->span=(MagickSizeType) image->columns*image->rows;
1900 image_view=AcquireCacheView(image);
1901 if (depth > 1)
1902 Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
1903 status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
1904 image_view=DestroyCacheView(image_view);
1905 return(status);
1906}
1907
1908/*
1909%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1910% %
1911% %
1912% %
1913+ G e t C u b e I n f o %
1914% %
1915% %
1916% %
1917%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1918%
1919% GetCubeInfo() initialize the Cube data structure.
1920%
1921% The format of the GetCubeInfo method is:
1922%
1923% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
cristybb503372010-05-27 20:51:26 +00001924% const size_t depth,const size_t maximum_colors)
cristy3ed852e2009-09-05 21:47:34 +00001925%
1926% A description of each parameter follows.
1927%
1928% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
1929%
1930% o depth: Normally, this integer value is zero or one. A zero or
1931% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
1932% A tree of this depth generally allows the best representation of the
1933% reference image with the least amount of memory and the fastest
1934% computational speed. In some cases, such as an image with low color
1935% dispersion (a few number of colors), a value other than
1936% Log4(number_colors) is required. To expand the color tree completely,
1937% use a value of 8.
1938%
1939% o maximum_colors: maximum colors.
1940%
1941*/
1942static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
cristybb503372010-05-27 20:51:26 +00001943 const size_t depth,const size_t maximum_colors)
cristy3ed852e2009-09-05 21:47:34 +00001944{
1945 CubeInfo
1946 *cube_info;
1947
1948 MagickRealType
1949 sum,
1950 weight;
1951
cristybb503372010-05-27 20:51:26 +00001952 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00001953 i;
1954
cristyecc31b12011-02-13 00:32:29 +00001955 size_t
1956 length;
1957
cristy3ed852e2009-09-05 21:47:34 +00001958 /*
1959 Initialize tree to describe color cube_info.
1960 */
cristy73bd4a52010-10-05 11:24:23 +00001961 cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
cristy3ed852e2009-09-05 21:47:34 +00001962 if (cube_info == (CubeInfo *) NULL)
1963 return((CubeInfo *) NULL);
1964 (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
1965 cube_info->depth=depth;
1966 if (cube_info->depth > MaxTreeDepth)
1967 cube_info->depth=MaxTreeDepth;
1968 if (cube_info->depth < 2)
1969 cube_info->depth=2;
1970 cube_info->maximum_colors=maximum_colors;
1971 /*
1972 Initialize root node.
1973 */
1974 cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
1975 if (cube_info->root == (NodeInfo *) NULL)
1976 return((CubeInfo *) NULL);
1977 cube_info->root->parent=cube_info->root;
1978 cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
1979 if (cube_info->quantize_info->dither == MagickFalse)
1980 return(cube_info);
1981 /*
1982 Initialize dither resources.
1983 */
1984 length=(size_t) (1UL << (4*(8-CacheShift)));
cristybb503372010-05-27 20:51:26 +00001985 cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
cristy3ed852e2009-09-05 21:47:34 +00001986 sizeof(*cube_info->cache));
cristybb503372010-05-27 20:51:26 +00001987 if (cube_info->cache == (ssize_t *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00001988 return((CubeInfo *) NULL);
1989 /*
1990 Initialize color cache.
1991 */
cristybb503372010-05-27 20:51:26 +00001992 for (i=0; i < (ssize_t) length; i++)
cristy3ed852e2009-09-05 21:47:34 +00001993 cube_info->cache[i]=(-1);
1994 /*
cristycee97112010-05-28 00:44:52 +00001995 Distribute weights along a curve of exponential decay.
cristy3ed852e2009-09-05 21:47:34 +00001996 */
1997 weight=1.0;
1998 for (i=0; i < ErrorQueueLength; i++)
1999 {
2000 cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
2001 weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
2002 }
2003 /*
2004 Normalize the weighting factors.
2005 */
2006 weight=0.0;
2007 for (i=0; i < ErrorQueueLength; i++)
2008 weight+=cube_info->weights[i];
2009 sum=0.0;
2010 for (i=0; i < ErrorQueueLength; i++)
2011 {
2012 cube_info->weights[i]/=weight;
2013 sum+=cube_info->weights[i];
2014 }
2015 cube_info->weights[0]+=1.0-sum;
2016 return(cube_info);
2017}
2018
2019/*
2020%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2021% %
2022% %
2023% %
2024+ G e t N o d e I n f o %
2025% %
2026% %
2027% %
2028%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2029%
2030% GetNodeInfo() allocates memory for a new node in the color cube tree and
2031% presets all fields to zero.
2032%
2033% The format of the GetNodeInfo method is:
2034%
cristybb503372010-05-27 20:51:26 +00002035% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2036% const size_t level,NodeInfo *parent)
cristy3ed852e2009-09-05 21:47:34 +00002037%
2038% A description of each parameter follows.
2039%
2040% o node: The GetNodeInfo method returns a pointer to a queue of nodes.
2041%
2042% o id: Specifies the child number of the node.
2043%
2044% o level: Specifies the level in the storage_class the node resides.
2045%
2046*/
cristybb503372010-05-27 20:51:26 +00002047static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
2048 const size_t level,NodeInfo *parent)
cristy3ed852e2009-09-05 21:47:34 +00002049{
2050 NodeInfo
2051 *node_info;
2052
2053 if (cube_info->free_nodes == 0)
2054 {
2055 Nodes
2056 *nodes;
2057
2058 /*
2059 Allocate a new queue of nodes.
2060 */
cristy73bd4a52010-10-05 11:24:23 +00002061 nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
cristy3ed852e2009-09-05 21:47:34 +00002062 if (nodes == (Nodes *) NULL)
2063 return((NodeInfo *) NULL);
2064 nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
2065 sizeof(*nodes->nodes));
2066 if (nodes->nodes == (NodeInfo *) NULL)
2067 return((NodeInfo *) NULL);
2068 nodes->next=cube_info->node_queue;
2069 cube_info->node_queue=nodes;
2070 cube_info->next_node=nodes->nodes;
2071 cube_info->free_nodes=NodesInAList;
2072 }
2073 cube_info->nodes++;
2074 cube_info->free_nodes--;
2075 node_info=cube_info->next_node++;
2076 (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
2077 node_info->parent=parent;
2078 node_info->id=id;
2079 node_info->level=level;
2080 return(node_info);
2081}
2082
2083/*
2084%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2085% %
2086% %
2087% %
2088% G e t I m a g e Q u a n t i z e E r r o r %
2089% %
2090% %
2091% %
2092%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2093%
2094% GetImageQuantizeError() measures the difference between the original
2095% and quantized images. This difference is the total quantization error.
2096% The error is computed by summing over all pixels in an image the distance
2097% squared in RGB space between each reference pixel value and its quantized
2098% value. These values are computed:
2099%
2100% o mean_error_per_pixel: This value is the mean error for any single
2101% pixel in the image.
2102%
2103% o normalized_mean_square_error: This value is the normalized mean
2104% quantization error for any single pixel in the image. This distance
2105% measure is normalized to a range between 0 and 1. It is independent
2106% of the range of red, green, and blue values in the image.
2107%
2108% o normalized_maximum_square_error: Thsi value is the normalized
2109% maximum quantization error for any single pixel in the image. This
2110% distance measure is normalized to a range between 0 and 1. It is
2111% independent of the range of red, green, and blue values in your image.
2112%
2113% The format of the GetImageQuantizeError method is:
2114%
2115% MagickBooleanType GetImageQuantizeError(Image *image)
2116%
2117% A description of each parameter follows.
2118%
2119% o image: the image.
2120%
2121*/
2122MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
2123{
cristyc4c8d132010-01-07 01:58:38 +00002124 CacheView
2125 *image_view;
2126
cristy3ed852e2009-09-05 21:47:34 +00002127 ExceptionInfo
2128 *exception;
2129
2130 IndexPacket
2131 *indexes;
2132
cristy3ed852e2009-09-05 21:47:34 +00002133 MagickRealType
2134 alpha,
2135 area,
2136 beta,
2137 distance,
2138 maximum_error,
2139 mean_error,
2140 mean_error_per_pixel;
2141
cristybb503372010-05-27 20:51:26 +00002142 size_t
cristy3ed852e2009-09-05 21:47:34 +00002143 index;
2144
cristyecc31b12011-02-13 00:32:29 +00002145 ssize_t
2146 y;
2147
cristy3ed852e2009-09-05 21:47:34 +00002148 assert(image != (Image *) NULL);
2149 assert(image->signature == MagickSignature);
2150 if (image->debug != MagickFalse)
2151 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2152 image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
2153 (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
2154 if (image->storage_class == DirectClass)
2155 return(MagickTrue);
2156 alpha=1.0;
2157 beta=1.0;
2158 area=3.0*image->columns*image->rows;
2159 maximum_error=0.0;
2160 mean_error_per_pixel=0.0;
2161 mean_error=0.0;
2162 exception=(&image->exception);
2163 image_view=AcquireCacheView(image);
cristybb503372010-05-27 20:51:26 +00002164 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00002165 {
2166 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00002167 *restrict p;
cristy3ed852e2009-09-05 21:47:34 +00002168
cristybb503372010-05-27 20:51:26 +00002169 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002170 x;
2171
2172 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2173 if (p == (const PixelPacket *) NULL)
2174 break;
2175 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00002176 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00002177 {
2178 index=1UL*indexes[x];
2179 if (image->matte != MagickFalse)
2180 {
cristy46f08202010-01-10 04:04:21 +00002181 alpha=(MagickRealType) (QuantumScale*(GetAlphaPixelComponent(p)));
cristy3ed852e2009-09-05 21:47:34 +00002182 beta=(MagickRealType) (QuantumScale*(QuantumRange-
2183 image->colormap[index].opacity));
2184 }
2185 distance=fabs(alpha*p->red-beta*image->colormap[index].red);
2186 mean_error_per_pixel+=distance;
2187 mean_error+=distance*distance;
2188 if (distance > maximum_error)
2189 maximum_error=distance;
2190 distance=fabs(alpha*p->green-beta*image->colormap[index].green);
2191 mean_error_per_pixel+=distance;
2192 mean_error+=distance*distance;
2193 if (distance > maximum_error)
2194 maximum_error=distance;
2195 distance=fabs(alpha*p->blue-beta*image->colormap[index].blue);
2196 mean_error_per_pixel+=distance;
2197 mean_error+=distance*distance;
2198 if (distance > maximum_error)
2199 maximum_error=distance;
2200 p++;
2201 }
2202 }
2203 image_view=DestroyCacheView(image_view);
2204 image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
2205 image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
2206 mean_error/area;
2207 image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
2208 return(MagickTrue);
2209}
2210
2211/*
2212%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2213% %
2214% %
2215% %
2216% G e t Q u a n t i z e I n f o %
2217% %
2218% %
2219% %
2220%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2221%
2222% GetQuantizeInfo() initializes the QuantizeInfo structure.
2223%
2224% The format of the GetQuantizeInfo method is:
2225%
2226% GetQuantizeInfo(QuantizeInfo *quantize_info)
2227%
2228% A description of each parameter follows:
2229%
2230% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
2231%
2232*/
2233MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
2234{
2235 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
2236 assert(quantize_info != (QuantizeInfo *) NULL);
2237 (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
2238 quantize_info->number_colors=256;
2239 quantize_info->dither=MagickTrue;
2240 quantize_info->dither_method=RiemersmaDitherMethod;
2241 quantize_info->colorspace=UndefinedColorspace;
2242 quantize_info->measure_error=MagickFalse;
2243 quantize_info->signature=MagickSignature;
2244}
2245
2246/*
2247%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2248% %
2249% %
2250% %
cristyd1a2c0f2011-02-09 14:14:50 +00002251% P o s t e r i z e I m a g e C h a n n e l %
cristy3ed852e2009-09-05 21:47:34 +00002252% %
2253% %
2254% %
2255%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2256%
2257% PosterizeImage() reduces the image to a limited number of colors for a
2258% "poster" effect.
2259%
2260% The format of the PosterizeImage method is:
2261%
cristybb503372010-05-27 20:51:26 +00002262% MagickBooleanType PosterizeImage(Image *image,const size_t levels,
cristy3ed852e2009-09-05 21:47:34 +00002263% const MagickBooleanType dither)
cristyd1a2c0f2011-02-09 14:14:50 +00002264% MagickBooleanType PosterizeImageChannel(Image *image,
2265% const ChannelType channel,const size_t levels,
2266% const MagickBooleanType dither)
cristy3ed852e2009-09-05 21:47:34 +00002267%
2268% A description of each parameter follows:
2269%
2270% o image: Specifies a pointer to an Image structure.
2271%
2272% o levels: Number of color levels allowed in each channel. Very low values
2273% (2, 3, or 4) have the most visible effect.
2274%
cristy847620f2011-02-09 02:24:21 +00002275% o dither: Set this integer value to something other than zero to dither
2276% the mapped image.
cristy3ed852e2009-09-05 21:47:34 +00002277%
2278*/
cristyd1a2c0f2011-02-09 14:14:50 +00002279
cristy4d727152011-02-10 19:57:21 +00002280static inline ssize_t MagickRound(MagickRealType x)
2281{
2282 /*
cristyecc31b12011-02-13 00:32:29 +00002283 Round the fraction to nearest integer.
cristy4d727152011-02-10 19:57:21 +00002284 */
2285 if (x >= 0.0)
2286 return((ssize_t) (x+0.5));
2287 return((ssize_t) (x-0.5));
2288}
2289
cristyd1a2c0f2011-02-09 14:14:50 +00002290MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
2291 const MagickBooleanType dither)
cristy3ed852e2009-09-05 21:47:34 +00002292{
cristyd1a2c0f2011-02-09 14:14:50 +00002293 MagickBooleanType
2294 status;
2295
2296 status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
2297 return(status);
2298}
2299
2300MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
2301 const ChannelType channel,const size_t levels,const MagickBooleanType dither)
2302{
2303#define PosterizeImageTag "Posterize/Image"
cristy4d727152011-02-10 19:57:21 +00002304#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
cristy3e9cad02011-02-20 01:42:00 +00002305 QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
cristyd1a2c0f2011-02-09 14:14:50 +00002306
cristyc4c8d132010-01-07 01:58:38 +00002307 CacheView
cristyd1a2c0f2011-02-09 14:14:50 +00002308 *image_view;
cristyc4c8d132010-01-07 01:58:38 +00002309
cristy3ed852e2009-09-05 21:47:34 +00002310 ExceptionInfo
2311 *exception;
2312
cristy3ed852e2009-09-05 21:47:34 +00002313 MagickBooleanType
2314 status;
2315
cristyd1a2c0f2011-02-09 14:14:50 +00002316 MagickOffsetType
2317 progress;
2318
cristy3ed852e2009-09-05 21:47:34 +00002319 QuantizeInfo
2320 *quantize_info;
2321
cristy847620f2011-02-09 02:24:21 +00002322 register ssize_t
2323 i;
2324
cristy847620f2011-02-09 02:24:21 +00002325 ssize_t
cristyd1a2c0f2011-02-09 14:14:50 +00002326 y;
cristy847620f2011-02-09 02:24:21 +00002327
cristy3ed852e2009-09-05 21:47:34 +00002328 assert(image != (Image *) NULL);
2329 assert(image->signature == MagickSignature);
2330 if (image->debug != MagickFalse)
2331 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
cristyd1a2c0f2011-02-09 14:14:50 +00002332 if (image->storage_class == PseudoClass)
2333#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy00cbdd62011-02-20 17:29:26 +00002334 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
cristyd1a2c0f2011-02-09 14:14:50 +00002335#endif
2336 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00002337 {
cristyd1a2c0f2011-02-09 14:14:50 +00002338 /*
2339 Posterize colormap.
2340 */
2341 if ((channel & RedChannel) != 0)
2342 image->colormap[i].red=PosterizePixel(image->colormap[i].red);
2343 if ((channel & GreenChannel) != 0)
2344 image->colormap[i].green=PosterizePixel(image->colormap[i].green);
2345 if ((channel & BlueChannel) != 0)
2346 image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
2347 if ((channel & OpacityChannel) != 0)
2348 image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity);
cristy3ed852e2009-09-05 21:47:34 +00002349 }
cristyd1a2c0f2011-02-09 14:14:50 +00002350 /*
2351 Posterize image.
2352 */
2353 status=MagickTrue;
2354 progress=0;
cristy3ed852e2009-09-05 21:47:34 +00002355 exception=(&image->exception);
cristyd1a2c0f2011-02-09 14:14:50 +00002356 image_view=AcquireCacheView(image);
2357#if defined(MAGICKCORE_OPENMP_SUPPORT)
2358 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2359#endif
2360 for (y=0; y < (ssize_t) image->rows; y++)
2361 {
2362 register IndexPacket
2363 *restrict indexes;
2364
2365 register PixelPacket
2366 *restrict q;
2367
2368 register ssize_t
2369 x;
2370
2371 if (status == MagickFalse)
2372 continue;
2373 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2374 if (q == (PixelPacket *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00002375 {
cristyd1a2c0f2011-02-09 14:14:50 +00002376 status=MagickFalse;
2377 continue;
cristy3ed852e2009-09-05 21:47:34 +00002378 }
cristyd1a2c0f2011-02-09 14:14:50 +00002379 indexes=GetCacheViewAuthenticIndexQueue(image_view);
2380 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00002381 {
cristyd1a2c0f2011-02-09 14:14:50 +00002382 if ((channel & RedChannel) != 0)
2383 q->red=PosterizePixel(q->red);
2384 if ((channel & GreenChannel) != 0)
2385 q->green=PosterizePixel(q->green);
2386 if ((channel & BlueChannel) != 0)
2387 q->blue=PosterizePixel(q->blue);
2388 if (((channel & OpacityChannel) != 0) &&
2389 (image->matte == MagickTrue))
2390 q->opacity=PosterizePixel(q->opacity);
2391 if (((channel & IndexChannel) != 0) &&
2392 (image->colorspace == CMYKColorspace))
2393 indexes[x]=PosterizePixel(indexes[x]);
2394 q++;
cristy3ed852e2009-09-05 21:47:34 +00002395 }
cristyd1a2c0f2011-02-09 14:14:50 +00002396 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2397 status=MagickFalse;
2398 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2399 {
2400 MagickBooleanType
2401 proceed;
2402
2403#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy00cbdd62011-02-20 17:29:26 +00002404 #pragma omp critical (MagickCore_PosterizeImageChannel)
cristyd1a2c0f2011-02-09 14:14:50 +00002405#endif
2406 proceed=SetImageProgress(image,PosterizeImageTag,progress++,
2407 image->rows);
2408 if (proceed == MagickFalse)
2409 status=MagickFalse;
2410 }
2411 }
2412 image_view=DestroyCacheView(image_view);
cristy3ed852e2009-09-05 21:47:34 +00002413 quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
cristyd1a2c0f2011-02-09 14:14:50 +00002414 quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
2415 levels,MaxColormapSize+1);
cristy3ed852e2009-09-05 21:47:34 +00002416 quantize_info->dither=dither;
cristy3e9cad02011-02-20 01:42:00 +00002417 quantize_info->tree_depth=MaxTreeDepth;
cristyd1a2c0f2011-02-09 14:14:50 +00002418 status=QuantizeImage(quantize_info,image);
cristy3ed852e2009-09-05 21:47:34 +00002419 quantize_info=DestroyQuantizeInfo(quantize_info);
cristy3ed852e2009-09-05 21:47:34 +00002420 return(status);
2421}
2422
2423/*
2424%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2425% %
2426% %
2427% %
2428+ P r u n e C h i l d %
2429% %
2430% %
2431% %
2432%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2433%
2434% PruneChild() deletes the given node and merges its statistics into its
2435% parent.
2436%
2437% The format of the PruneSubtree method is:
2438%
2439% PruneChild(const Image *image,CubeInfo *cube_info,
2440% const NodeInfo *node_info)
2441%
2442% A description of each parameter follows.
2443%
2444% o image: the image.
2445%
2446% o cube_info: A pointer to the Cube structure.
2447%
2448% o node_info: pointer to node in color cube tree that is to be pruned.
2449%
2450*/
2451static void PruneChild(const Image *image,CubeInfo *cube_info,
2452 const NodeInfo *node_info)
2453{
2454 NodeInfo
2455 *parent;
2456
cristybb503372010-05-27 20:51:26 +00002457 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002458 i;
2459
cristybb503372010-05-27 20:51:26 +00002460 size_t
cristy3ed852e2009-09-05 21:47:34 +00002461 number_children;
2462
2463 /*
2464 Traverse any children.
2465 */
2466 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002467 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002468 if (node_info->child[i] != (NodeInfo *) NULL)
2469 PruneChild(image,cube_info,node_info->child[i]);
2470 /*
2471 Merge color statistics into parent.
2472 */
2473 parent=node_info->parent;
2474 parent->number_unique+=node_info->number_unique;
2475 parent->total_color.red+=node_info->total_color.red;
2476 parent->total_color.green+=node_info->total_color.green;
2477 parent->total_color.blue+=node_info->total_color.blue;
2478 parent->total_color.opacity+=node_info->total_color.opacity;
2479 parent->child[node_info->id]=(NodeInfo *) NULL;
2480 cube_info->nodes--;
2481}
2482
2483/*
2484%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2485% %
2486% %
2487% %
2488+ P r u n e L e v e l %
2489% %
2490% %
2491% %
2492%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2493%
2494% PruneLevel() deletes all nodes at the bottom level of the color tree merging
2495% their color statistics into their parent node.
2496%
2497% The format of the PruneLevel method is:
2498%
2499% PruneLevel(const Image *image,CubeInfo *cube_info,
2500% const NodeInfo *node_info)
2501%
2502% A description of each parameter follows.
2503%
2504% o image: the image.
2505%
2506% o cube_info: A pointer to the Cube structure.
2507%
2508% o node_info: pointer to node in color cube tree that is to be pruned.
2509%
2510*/
2511static void PruneLevel(const Image *image,CubeInfo *cube_info,
2512 const NodeInfo *node_info)
2513{
cristybb503372010-05-27 20:51:26 +00002514 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002515 i;
2516
cristybb503372010-05-27 20:51:26 +00002517 size_t
cristy3ed852e2009-09-05 21:47:34 +00002518 number_children;
2519
2520 /*
2521 Traverse any children.
2522 */
2523 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002524 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002525 if (node_info->child[i] != (NodeInfo *) NULL)
2526 PruneLevel(image,cube_info,node_info->child[i]);
2527 if (node_info->level == cube_info->depth)
2528 PruneChild(image,cube_info,node_info);
2529}
2530
2531/*
2532%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2533% %
2534% %
2535% %
2536+ P r u n e T o C u b e D e p t h %
2537% %
2538% %
2539% %
2540%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2541%
2542% PruneToCubeDepth() deletes any nodes at a depth greater than
2543% cube_info->depth while merging their color statistics into their parent
2544% node.
2545%
2546% The format of the PruneToCubeDepth method is:
2547%
2548% PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2549% const NodeInfo *node_info)
2550%
2551% A description of each parameter follows.
2552%
2553% o cube_info: A pointer to the Cube structure.
2554%
2555% o node_info: pointer to node in color cube tree that is to be pruned.
2556%
2557*/
2558static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
2559 const NodeInfo *node_info)
2560{
cristybb503372010-05-27 20:51:26 +00002561 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002562 i;
2563
cristybb503372010-05-27 20:51:26 +00002564 size_t
cristy3ed852e2009-09-05 21:47:34 +00002565 number_children;
2566
2567 /*
2568 Traverse any children.
2569 */
2570 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002571 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002572 if (node_info->child[i] != (NodeInfo *) NULL)
2573 PruneToCubeDepth(image,cube_info,node_info->child[i]);
2574 if (node_info->level > cube_info->depth)
2575 PruneChild(image,cube_info,node_info);
2576}
2577
2578/*
2579%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2580% %
2581% %
2582% %
2583% Q u a n t i z e I m a g e %
2584% %
2585% %
2586% %
2587%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2588%
2589% QuantizeImage() analyzes the colors within a reference image and chooses a
2590% fixed number of colors to represent the image. The goal of the algorithm
2591% is to minimize the color difference between the input and output image while
2592% minimizing the processing time.
2593%
2594% The format of the QuantizeImage method is:
2595%
2596% MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2597% Image *image)
2598%
2599% A description of each parameter follows:
2600%
2601% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2602%
2603% o image: the image.
2604%
2605*/
2606MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
2607 Image *image)
2608{
2609 CubeInfo
2610 *cube_info;
2611
2612 MagickBooleanType
2613 status;
2614
cristybb503372010-05-27 20:51:26 +00002615 size_t
cristy3ed852e2009-09-05 21:47:34 +00002616 depth,
2617 maximum_colors;
2618
2619 assert(quantize_info != (const QuantizeInfo *) NULL);
2620 assert(quantize_info->signature == MagickSignature);
2621 assert(image != (Image *) NULL);
2622 assert(image->signature == MagickSignature);
2623 if (image->debug != MagickFalse)
2624 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2625 maximum_colors=quantize_info->number_colors;
2626 if (maximum_colors == 0)
2627 maximum_colors=MaxColormapSize;
2628 if (maximum_colors > MaxColormapSize)
2629 maximum_colors=MaxColormapSize;
cristy8e752752011-04-16 13:48:22 +00002630 if ((IsGrayImage(image,&image->exception) != MagickFalse) &&
2631 (image->matte == MagickFalse))
2632 (void) SetGrayscaleImage(image);
cristy3ed852e2009-09-05 21:47:34 +00002633 if ((image->storage_class == PseudoClass) &&
2634 (image->colors <= maximum_colors))
2635 return(MagickTrue);
2636 depth=quantize_info->tree_depth;
2637 if (depth == 0)
2638 {
cristybb503372010-05-27 20:51:26 +00002639 size_t
cristy3ed852e2009-09-05 21:47:34 +00002640 colors;
2641
2642 /*
2643 Depth of color tree is: Log4(colormap size)+2.
2644 */
2645 colors=maximum_colors;
2646 for (depth=1; colors != 0; depth++)
2647 colors>>=2;
2648 if ((quantize_info->dither != MagickFalse) && (depth > 2))
2649 depth--;
2650 if ((image->matte != MagickFalse) && (depth > 5))
2651 depth--;
2652 }
2653 /*
2654 Initialize color cube.
2655 */
2656 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2657 if (cube_info == (CubeInfo *) NULL)
2658 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2659 image->filename);
2660 status=ClassifyImageColors(cube_info,image,&image->exception);
2661 if (status != MagickFalse)
2662 {
2663 /*
2664 Reduce the number of colors in the image.
2665 */
2666 ReduceImageColors(image,cube_info);
2667 status=AssignImageColors(image,cube_info);
2668 }
2669 DestroyCubeInfo(cube_info);
2670 return(status);
2671}
2672
2673/*
2674%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2675% %
2676% %
2677% %
2678% Q u a n t i z e I m a g e s %
2679% %
2680% %
2681% %
2682%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2683%
2684% QuantizeImages() analyzes the colors within a set of reference images and
2685% chooses a fixed number of colors to represent the set. The goal of the
2686% algorithm is to minimize the color difference between the input and output
2687% images while minimizing the processing time.
2688%
2689% The format of the QuantizeImages method is:
2690%
2691% MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2692% Image *images)
2693%
2694% A description of each parameter follows:
2695%
2696% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2697%
2698% o images: Specifies a pointer to a list of Image structures.
2699%
2700*/
2701MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
2702 Image *images)
2703{
2704 CubeInfo
2705 *cube_info;
2706
2707 Image
2708 *image;
2709
2710 MagickBooleanType
2711 proceed,
2712 status;
2713
2714 MagickProgressMonitor
2715 progress_monitor;
2716
cristybb503372010-05-27 20:51:26 +00002717 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002718 i;
2719
cristybb503372010-05-27 20:51:26 +00002720 size_t
cristy3ed852e2009-09-05 21:47:34 +00002721 depth,
2722 maximum_colors,
2723 number_images;
2724
2725 assert(quantize_info != (const QuantizeInfo *) NULL);
2726 assert(quantize_info->signature == MagickSignature);
2727 assert(images != (Image *) NULL);
2728 assert(images->signature == MagickSignature);
2729 if (images->debug != MagickFalse)
2730 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2731 if (GetNextImageInList(images) == (Image *) NULL)
2732 {
2733 /*
2734 Handle a single image with QuantizeImage.
2735 */
2736 status=QuantizeImage(quantize_info,images);
2737 return(status);
2738 }
2739 status=MagickFalse;
2740 maximum_colors=quantize_info->number_colors;
2741 if (maximum_colors == 0)
2742 maximum_colors=MaxColormapSize;
2743 if (maximum_colors > MaxColormapSize)
2744 maximum_colors=MaxColormapSize;
2745 depth=quantize_info->tree_depth;
2746 if (depth == 0)
2747 {
cristybb503372010-05-27 20:51:26 +00002748 size_t
cristy3ed852e2009-09-05 21:47:34 +00002749 colors;
2750
2751 /*
2752 Depth of color tree is: Log4(colormap size)+2.
2753 */
2754 colors=maximum_colors;
2755 for (depth=1; colors != 0; depth++)
2756 colors>>=2;
2757 if (quantize_info->dither != MagickFalse)
2758 depth--;
2759 }
2760 /*
2761 Initialize color cube.
2762 */
2763 cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
2764 if (cube_info == (CubeInfo *) NULL)
2765 {
2766 (void) ThrowMagickException(&images->exception,GetMagickModule(),
2767 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2768 return(MagickFalse);
2769 }
2770 number_images=GetImageListLength(images);
2771 image=images;
2772 for (i=0; image != (Image *) NULL; i++)
2773 {
2774 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
2775 image->client_data);
2776 status=ClassifyImageColors(cube_info,image,&image->exception);
2777 if (status == MagickFalse)
2778 break;
2779 (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
cristycee97112010-05-28 00:44:52 +00002780 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2781 number_images);
cristy3ed852e2009-09-05 21:47:34 +00002782 if (proceed == MagickFalse)
2783 break;
2784 image=GetNextImageInList(image);
2785 }
2786 if (status != MagickFalse)
2787 {
2788 /*
2789 Reduce the number of colors in an image sequence.
2790 */
2791 ReduceImageColors(images,cube_info);
2792 image=images;
2793 for (i=0; image != (Image *) NULL; i++)
2794 {
2795 progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
2796 NULL,image->client_data);
2797 status=AssignImageColors(image,cube_info);
2798 if (status == MagickFalse)
2799 break;
2800 (void) SetImageProgressMonitor(image,progress_monitor,
2801 image->client_data);
cristycee97112010-05-28 00:44:52 +00002802 proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
2803 number_images);
cristy3ed852e2009-09-05 21:47:34 +00002804 if (proceed == MagickFalse)
2805 break;
2806 image=GetNextImageInList(image);
2807 }
2808 }
2809 DestroyCubeInfo(cube_info);
2810 return(status);
2811}
2812
2813/*
2814%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2815% %
2816% %
2817% %
2818+ R e d u c e %
2819% %
2820% %
2821% %
2822%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2823%
2824% Reduce() traverses the color cube tree and prunes any node whose
2825% quantization error falls below a particular threshold.
2826%
2827% The format of the Reduce method is:
2828%
2829% Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
2830%
2831% A description of each parameter follows.
2832%
2833% o image: the image.
2834%
2835% o cube_info: A pointer to the Cube structure.
2836%
2837% o node_info: pointer to node in color cube tree that is to be pruned.
2838%
2839*/
2840static void Reduce(const Image *image,CubeInfo *cube_info,
2841 const NodeInfo *node_info)
2842{
cristybb503372010-05-27 20:51:26 +00002843 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00002844 i;
2845
cristybb503372010-05-27 20:51:26 +00002846 size_t
cristy3ed852e2009-09-05 21:47:34 +00002847 number_children;
2848
2849 /*
2850 Traverse any children.
2851 */
2852 number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
cristybb503372010-05-27 20:51:26 +00002853 for (i=0; i < (ssize_t) number_children; i++)
cristy3ed852e2009-09-05 21:47:34 +00002854 if (node_info->child[i] != (NodeInfo *) NULL)
2855 Reduce(image,cube_info,node_info->child[i]);
2856 if (node_info->quantize_error <= cube_info->pruning_threshold)
2857 PruneChild(image,cube_info,node_info);
2858 else
2859 {
2860 /*
2861 Find minimum pruning threshold.
2862 */
2863 if (node_info->number_unique > 0)
2864 cube_info->colors++;
2865 if (node_info->quantize_error < cube_info->next_threshold)
2866 cube_info->next_threshold=node_info->quantize_error;
2867 }
2868}
2869
2870/*
2871%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2872% %
2873% %
2874% %
2875+ R e d u c e I m a g e C o l o r s %
2876% %
2877% %
2878% %
2879%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2880%
2881% ReduceImageColors() repeatedly prunes the tree until the number of nodes
2882% with n2 > 0 is less than or equal to the maximum number of colors allowed
2883% in the output image. On any given iteration over the tree, it selects
2884% those nodes whose E value is minimal for pruning and merges their
2885% color statistics upward. It uses a pruning threshold, Ep, to govern
2886% node selection as follows:
2887%
2888% Ep = 0
2889% while number of nodes with (n2 > 0) > required maximum number of colors
2890% prune all nodes such that E <= Ep
2891% Set Ep to minimum E in remaining nodes
2892%
2893% This has the effect of minimizing any quantization error when merging
2894% two nodes together.
2895%
2896% When a node to be pruned has offspring, the pruning procedure invokes
2897% itself recursively in order to prune the tree from the leaves upward.
2898% n2, Sr, Sg, and Sb in a node being pruned are always added to the
2899% corresponding data in that node's parent. This retains the pruned
2900% node's color characteristics for later averaging.
2901%
2902% For each node, n2 pixels exist for which that node represents the
2903% smallest volume in RGB space containing those pixel's colors. When n2
2904% > 0 the node will uniquely define a color in the output image. At the
2905% beginning of reduction, n2 = 0 for all nodes except a the leaves of
2906% the tree which represent colors present in the input image.
2907%
2908% The other pixel count, n1, indicates the total number of colors
2909% within the cubic volume which the node represents. This includes n1 -
2910% n2 pixels whose colors should be defined by nodes at a lower level in
2911% the tree.
2912%
2913% The format of the ReduceImageColors method is:
2914%
2915% ReduceImageColors(const Image *image,CubeInfo *cube_info)
2916%
2917% A description of each parameter follows.
2918%
2919% o image: the image.
2920%
2921% o cube_info: A pointer to the Cube structure.
2922%
2923*/
2924static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
2925{
2926#define ReduceImageTag "Reduce/Image"
2927
2928 MagickBooleanType
2929 proceed;
2930
2931 MagickOffsetType
2932 offset;
2933
cristybb503372010-05-27 20:51:26 +00002934 size_t
cristy3ed852e2009-09-05 21:47:34 +00002935 span;
2936
2937 cube_info->next_threshold=0.0;
2938 for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
2939 {
2940 cube_info->pruning_threshold=cube_info->next_threshold;
2941 cube_info->next_threshold=cube_info->root->quantize_error-1;
2942 cube_info->colors=0;
2943 Reduce(image,cube_info,cube_info->root);
2944 offset=(MagickOffsetType) span-cube_info->colors;
2945 proceed=SetImageProgress(image,ReduceImageTag,offset,span-
2946 cube_info->maximum_colors+1);
2947 if (proceed == MagickFalse)
2948 break;
2949 }
2950}
2951
2952/*
2953%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2954% %
2955% %
2956% %
2957% R e m a p I m a g e %
2958% %
2959% %
2960% %
2961%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2962%
2963% RemapImage() replaces the colors of an image with the closest color from
2964% a reference image.
2965%
2966% The format of the RemapImage method is:
2967%
2968% MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2969% Image *image,const Image *remap_image)
2970%
2971% A description of each parameter follows:
2972%
2973% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
2974%
2975% o image: the image.
2976%
2977% o remap_image: the reference image.
2978%
2979*/
2980MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
2981 Image *image,const Image *remap_image)
2982{
2983 CubeInfo
2984 *cube_info;
2985
2986 MagickBooleanType
2987 status;
2988
2989 /*
2990 Initialize color cube.
2991 */
2992 assert(image != (Image *) NULL);
2993 assert(image->signature == MagickSignature);
2994 if (image->debug != MagickFalse)
2995 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2996 assert(remap_image != (Image *) NULL);
2997 assert(remap_image->signature == MagickSignature);
2998 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
2999 quantize_info->number_colors);
3000 if (cube_info == (CubeInfo *) NULL)
3001 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3002 image->filename);
3003 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3004 if (status != MagickFalse)
3005 {
3006 /*
3007 Classify image colors from the reference image.
3008 */
3009 cube_info->quantize_info->number_colors=cube_info->colors;
3010 status=AssignImageColors(image,cube_info);
3011 }
3012 DestroyCubeInfo(cube_info);
3013 return(status);
3014}
3015
3016/*
3017%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3018% %
3019% %
3020% %
3021% R e m a p I m a g e s %
3022% %
3023% %
3024% %
3025%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3026%
3027% RemapImages() replaces the colors of a sequence of images with the
3028% closest color from a reference image.
3029%
3030% The format of the RemapImage method is:
3031%
3032% MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3033% Image *images,Image *remap_image)
3034%
3035% A description of each parameter follows:
3036%
3037% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
3038%
3039% o images: the image sequence.
3040%
3041% o remap_image: the reference image.
3042%
3043*/
3044MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
3045 Image *images,const Image *remap_image)
3046{
3047 CubeInfo
3048 *cube_info;
3049
3050 Image
3051 *image;
3052
3053 MagickBooleanType
3054 status;
3055
3056 assert(images != (Image *) NULL);
3057 assert(images->signature == MagickSignature);
3058 if (images->debug != MagickFalse)
3059 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
3060 image=images;
3061 if (remap_image == (Image *) NULL)
3062 {
3063 /*
3064 Create a global colormap for an image sequence.
3065 */
3066 status=QuantizeImages(quantize_info,images);
3067 return(status);
3068 }
3069 /*
3070 Classify image colors from the reference image.
3071 */
3072 cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
3073 quantize_info->number_colors);
3074 if (cube_info == (CubeInfo *) NULL)
3075 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3076 image->filename);
3077 status=ClassifyImageColors(cube_info,remap_image,&image->exception);
3078 if (status != MagickFalse)
3079 {
3080 /*
3081 Classify image colors from the reference image.
3082 */
3083 cube_info->quantize_info->number_colors=cube_info->colors;
3084 image=images;
3085 for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
3086 {
3087 status=AssignImageColors(image,cube_info);
3088 if (status == MagickFalse)
3089 break;
3090 }
3091 }
3092 DestroyCubeInfo(cube_info);
3093 return(status);
3094}
3095
3096/*
3097%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3098% %
3099% %
3100% %
3101% S e t G r a y s c a l e I m a g e %
3102% %
3103% %
3104% %
3105%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3106%
3107% SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
3108%
3109% The format of the SetGrayscaleImage method is:
3110%
3111% MagickBooleanType SetGrayscaleImage(Image *image)
3112%
3113% A description of each parameter follows:
3114%
3115% o image: The image.
3116%
3117*/
3118
3119#if defined(__cplusplus) || defined(c_plusplus)
3120extern "C" {
3121#endif
3122
3123static int IntensityCompare(const void *x,const void *y)
3124{
cristy3ed852e2009-09-05 21:47:34 +00003125 PixelPacket
3126 *color_1,
3127 *color_2;
3128
cristyecc31b12011-02-13 00:32:29 +00003129 ssize_t
3130 intensity;
3131
cristy3ed852e2009-09-05 21:47:34 +00003132 color_1=(PixelPacket *) x;
3133 color_2=(PixelPacket *) y;
cristybb503372010-05-27 20:51:26 +00003134 intensity=PixelIntensityToQuantum(color_1)-(ssize_t)
cristy3ed852e2009-09-05 21:47:34 +00003135 PixelIntensityToQuantum(color_2);
cristycee97112010-05-28 00:44:52 +00003136 return((int) intensity);
cristy3ed852e2009-09-05 21:47:34 +00003137}
3138
3139#if defined(__cplusplus) || defined(c_plusplus)
3140}
3141#endif
3142
3143static MagickBooleanType SetGrayscaleImage(Image *image)
3144{
cristyc4c8d132010-01-07 01:58:38 +00003145 CacheView
3146 *image_view;
3147
cristy3ed852e2009-09-05 21:47:34 +00003148 ExceptionInfo
3149 *exception;
3150
cristyecc31b12011-02-13 00:32:29 +00003151 MagickBooleanType
3152 status;
cristy3ed852e2009-09-05 21:47:34 +00003153
3154 PixelPacket
3155 *colormap;
3156
cristybb503372010-05-27 20:51:26 +00003157 register ssize_t
cristy3ed852e2009-09-05 21:47:34 +00003158 i;
3159
cristyecc31b12011-02-13 00:32:29 +00003160 ssize_t
3161 *colormap_index,
3162 j,
3163 y;
cristy3ed852e2009-09-05 21:47:34 +00003164
cristy3ed852e2009-09-05 21:47:34 +00003165 assert(image != (Image *) NULL);
3166 assert(image->signature == MagickSignature);
3167 if (image->type != GrayscaleType)
3168 (void) TransformImageColorspace(image,GRAYColorspace);
cristybb503372010-05-27 20:51:26 +00003169 colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
cristy3ed852e2009-09-05 21:47:34 +00003170 sizeof(*colormap_index));
cristybb503372010-05-27 20:51:26 +00003171 if (colormap_index == (ssize_t *) NULL)
cristy3ed852e2009-09-05 21:47:34 +00003172 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3173 image->filename);
3174 if (image->storage_class != PseudoClass)
3175 {
3176 ExceptionInfo
3177 *exception;
3178
cristybb503372010-05-27 20:51:26 +00003179 for (i=0; i <= (ssize_t) MaxMap; i++)
cristy3ed852e2009-09-05 21:47:34 +00003180 colormap_index[i]=(-1);
3181 if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
3182 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3183 image->filename);
3184 image->colors=0;
3185 status=MagickTrue;
3186 exception=(&image->exception);
3187 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003188#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy00cbdd62011-02-20 17:29:26 +00003189 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003190#endif
cristybb503372010-05-27 20:51:26 +00003191 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00003192 {
3193 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00003194 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00003195
cristy3ed852e2009-09-05 21:47:34 +00003196 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00003197 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003198
cristyecc31b12011-02-13 00:32:29 +00003199 register ssize_t
3200 x;
3201
cristy3ed852e2009-09-05 21:47:34 +00003202 if (status == MagickFalse)
3203 continue;
3204 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
3205 exception);
3206 if (q == (PixelPacket *) NULL)
3207 {
3208 status=MagickFalse;
3209 continue;
3210 }
3211 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00003212 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00003213 {
cristybb503372010-05-27 20:51:26 +00003214 register size_t
cristy3ed852e2009-09-05 21:47:34 +00003215 intensity;
3216
3217 intensity=ScaleQuantumToMap(q->red);
3218 if (colormap_index[intensity] < 0)
3219 {
cristyb5d5f722009-11-04 03:03:49 +00003220#if defined(MAGICKCORE_OPENMP_SUPPORT)
cristy3ed852e2009-09-05 21:47:34 +00003221 #pragma omp critical (MagickCore_SetGrayscaleImage)
3222#endif
3223 if (colormap_index[intensity] < 0)
3224 {
cristybb503372010-05-27 20:51:26 +00003225 colormap_index[intensity]=(ssize_t) image->colors;
cristy3ed852e2009-09-05 21:47:34 +00003226 image->colormap[image->colors]=(*q);
3227 image->colors++;
3228 }
3229 }
3230 indexes[x]=(IndexPacket) colormap_index[intensity];
3231 q++;
3232 }
3233 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3234 status=MagickFalse;
3235 }
3236 image_view=DestroyCacheView(image_view);
3237 }
cristybb503372010-05-27 20:51:26 +00003238 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00003239 image->colormap[i].opacity=(unsigned short) i;
3240 qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
3241 IntensityCompare);
3242 colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
3243 sizeof(*colormap));
3244 if (colormap == (PixelPacket *) NULL)
3245 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3246 image->filename);
3247 j=0;
3248 colormap[j]=image->colormap[0];
cristybb503372010-05-27 20:51:26 +00003249 for (i=0; i < (ssize_t) image->colors; i++)
cristy3ed852e2009-09-05 21:47:34 +00003250 {
3251 if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse)
3252 {
3253 j++;
3254 colormap[j]=image->colormap[i];
3255 }
cristybb503372010-05-27 20:51:26 +00003256 colormap_index[(ssize_t) image->colormap[i].opacity]=j;
cristy3ed852e2009-09-05 21:47:34 +00003257 }
cristybb503372010-05-27 20:51:26 +00003258 image->colors=(size_t) (j+1);
cristy3ed852e2009-09-05 21:47:34 +00003259 image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
3260 image->colormap=colormap;
3261 status=MagickTrue;
3262 exception=(&image->exception);
3263 image_view=AcquireCacheView(image);
cristyb5d5f722009-11-04 03:03:49 +00003264#if defined(MAGICKCORE_OPENMP_SUPPORT)
3265 #pragma omp parallel for schedule(dynamic,4) shared(status)
cristy3ed852e2009-09-05 21:47:34 +00003266#endif
cristybb503372010-05-27 20:51:26 +00003267 for (y=0; y < (ssize_t) image->rows; y++)
cristy3ed852e2009-09-05 21:47:34 +00003268 {
3269 register IndexPacket
cristyc47d1f82009-11-26 01:44:43 +00003270 *restrict indexes;
cristy3ed852e2009-09-05 21:47:34 +00003271
cristy3ed852e2009-09-05 21:47:34 +00003272 register const PixelPacket
cristyc47d1f82009-11-26 01:44:43 +00003273 *restrict q;
cristy3ed852e2009-09-05 21:47:34 +00003274
cristyecc31b12011-02-13 00:32:29 +00003275 register ssize_t
3276 x;
3277
cristy3ed852e2009-09-05 21:47:34 +00003278 if (status == MagickFalse)
3279 continue;
3280 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3281 if (q == (PixelPacket *) NULL)
3282 {
3283 status=MagickFalse;
3284 continue;
3285 }
3286 indexes=GetCacheViewAuthenticIndexQueue(image_view);
cristybb503372010-05-27 20:51:26 +00003287 for (x=0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +00003288 indexes[x]=(IndexPacket) colormap_index[ScaleQuantumToMap(indexes[x])];
3289 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3290 status=MagickFalse;
3291 }
3292 image_view=DestroyCacheView(image_view);
cristybb503372010-05-27 20:51:26 +00003293 colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
cristy3ed852e2009-09-05 21:47:34 +00003294 image->type=GrayscaleType;
3295 if (IsMonochromeImage(image,&image->exception) != MagickFalse)
3296 image->type=BilevelType;
3297 return(status);
3298}