root / ImageMagick / trunk / www / quantize.html

Revision 12114, 17.9 kB (checked in by cristy, 28 hours ago)
Line 
1<?xml version="1.0" encoding="UTF-8"?>
2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
4<head>
5  <style type="text/css" media="screen,projection"><!--
6    @import url("../www/magick.css");
7  //--></style>
8  <meta name="verify-v1" content="g222frIIxcQTrvDR3NBRUSKP3AnMNoqxOkIniCEkV7U=" />
9  <link rel="meta" type="application/rdf+xml" title="ICI" href="http://imagemagick.org/ici.rdf" />
10  <title>ImageMagick: Color Reduction Utilizing Adaptive Spatial Subdivision</title>
11  <meta http-equiv="Content-Language" content="en-US"/>
12  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
13  <meta http-equiv="Reply-to" content="magick-users@imagemagick.org"/>
14  <meta name="Generator" content="PHP"/>
15  <meta name="Keywords" content="color, reduction, utilizing, adaptive, spatial, subdivision, ImageMagick, ImageMagic, MagickCore, MagickWand, PerlMagick, Magick++, RMagick, PythonMagick, JMagick, TclMagick, Image, Magick, Magic, Wand, ImageMagickObject"/>
16  <meta name="Description" content="ImageMagick® is a software suite to create, edit, and compose bitmap images. It can read, convert and write images in a variety of formats (about 100) including GIF, JPEG, JPEG-2000, PNG, PDF, PhotoCD, TIFF, and DPX. Use ImageMagick to translate, flip, mirror, rotate, scale, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.  ImageMagick is free software delivered as a ready-to-run binary distribution or as source code that you can freely use, copy, modify, and distribute. Its license is compatible with the GPL. It runs on all major operating systems.  The functionality of ImageMagick is typically utilized from the command line or you can use the features from programs written in your favorite programming language. Choose from these interfaces: MagickCore (C), MagickWand (C), ChMagick (Ch), Magick++ (C++), JMagick (Java), L-Magick (Lisp), PascalMagick (Pascal), PerlMagick (Perl), MagickWand for PHP (PHP), PythonMagick (Python), RMagick (Ruby), or TclMagick (Tcl/TK). With a language interface, use ImageMagick to modify or create images automagically and dynamically."/>
17  <meta name="Rating" content="GENERAL"/>
18  <meta name="Robots" content="INDEX, FOLLOW"/>
19  <meta name="Generator" content="ImageMagick Studio LLC"/>
20  <meta name="Author" content="ImageMagick Studio LLC"/>
21  <meta name="Revisit-after" content="2 DAYS"/>
22  <meta name="Resource-type" content="document"/>
23  <meta name="Copyright" content="Copyright (c) 1999-2008 ImageMagick Studio LLC"/>
24  <meta name="Distribution" content="Global"/>
25  <link rel="shortcut icon" href="../images/wand.ico"  type="images/vnd.microsoft.icon"/>
26</head>
27
28<body id="www-imagemagick-org">
29  <table id="titlebar" style="width: 100%;background-color: #f5f5f5" cellpadding="0" cellspacing="0" border="0" summary="ImageMagick">
30    <tbody>
31      <tr valign="top">
32        <td align="left"><a href="../index.html"><img id="titlebar-west" src="../images/script.png" alt="[ImageMagick]" width="350" height="60" vspace="28" name="titlebar-west"/></a></td>
33        <td align="left"><a href="https://secure.networkredux.com/affiliate/idevaffiliate.html?id=146" target="2121329349"><img id="titlebar-west" src="../images/networkredux.png" alt="[sponsor]" border="0" vspace="45" name="titlebar-west"/></a></td>
34        <td width="99%"><br /> </td>
35        <td style="background-color: white" align="right"><a href="../index.html"><img src="../images/sprite.jpg" alt="" width="114" height="118" border="0" name="titlebar-east"/></a></td>
36        <td style="background-color: white" align="right"><a href="http://www.imagemagick.org/discourse-server/" target="1636399126"><img id="titlebar-east" src="../images/logo.jpg" alt="" width="114" height="118" border="0" name="titlebar-east"/></a></td>
37      </tr>
38    </tbody>
39  </table>
40
41  <table style="width: 100%" border="0" cellpadding="0" cellspacing="0" summary="">
42  <tbody>
43
44    <tr valign="top" style="height: 100%;">
45      <td id="menu" width="1%" height="100%">
46      <p><a href="#main">Skip to page contents</a></p>
47      <font size="-1">
48      <span>[</span>
49      <a href="../index.html">About ImageMagick</a>
50  <span>]</span><br /><span>[</span>
51      <a href="../www/command-line-tools.html">Command-line Tools</a>
52      <a href="../www/command-line-processing.html" class="sub">Processing</a>
53      <a href="../www/command-line-options.html" class="sub">Options</a>
54      <a href="http://www.imagemagick.org/Usage/" target="2082249934" class="sub">Usage</a>
55      <a href="../www/api.html">Program Interfaces</a>
56      <a href="../www/magick-wand.html" class="sub">MagickWand</a>
57      <a href="../www/magick-core.html" class="sub">MagickCore</a>
58      <a href="../www/perl-magick.html" class="sub">PerlMagick</a>
59      <a href="../www/Magick++/" target="1975198698" class="sub">Magick++</a>
60      <a href="../www/architecture.html">Architecture</a>
61  <span>]</span><br /><span>[</span>
62      <a href="../www/install-source.html">Install from Source</a>
63      <a href="../www/install-source.html#unix" class="sub">Unix</a>
64      <a href="../www/install-source.html#windows" class="sub">Windows</a>
65      <a href="../www/binary-releases.html">Binary Releases</a>
66      <a href="../www/binary-releases.html#unix" class="sub">Unix</a>
67      <a href="../www/binary-releases.html#macosx" class="sub">Mac OS X</a>
68      <a href="../www/binary-releases.html#windows" class="sub">Windows</a>
69      <a href="../www/resources.html">Resources</a>
70  <span>]</span><br /><span>[</span>
71      <a href="../www/download.html">Download</a>
72  <span>]</span><br /><span>[</span>
73      <a href="../www/sitemap.html">Site Map</a>
74                        <a href="../www/links.html" class="sub">Links</a>
75  <span>]</span><br /><span>[</span>
76      <a href="../www/sponsors.html">Sponsors:</a>
77      <fieldset>
78  <a href="http://www.neue.autoteile-info.de/auspuff.html" class="sponsor" target="sponsor">Auspuff</a><!-- 200811010100 -->
79      <br />
80      <a href="http://www.posters555.com" class="sponsor" target="sponsor">Poster</a><!-- 200903010800 -->
81      <br />
82      <a href="http://www.iceposter.com" class="sponsor" target="sponsor">Posters</a><!-- 200812010200 -->
83      <br />
84      <a href="http://meta-preisvergleich.de" class="sponsor" target="sponsor">Preisvergleich</a><!-- 200810010120 -->
85      <br />
86      <a href="http://www.imade-art.de"><img src="../images/imade_art2.jpg" alt="[Kunst bei imade-art]" width="116" height="28" border="0" name="Kunst bei imade-art"/></a> <!-- 200811010160 -->
87      </fieldset>
88      <span>]</span>
89      </font>
90      </td>
91
92      <td id="main" valign="top">
93<p class="navigation-index">[<a href="#describe">Algorithm Description</a> &bull; <a href="#measure">Measuring Color Reduction Error</a>]</p>
94
95<p>This document describes how ImageMagick performs color reduction on an image. To fully understand this document, you should have a knowledge of basic imaging techniques and the tree data structure and terminology.</p>
96
97<div style="margin: auto;">
98  <h2><a name="describe"></a>Algorithm Description</h2>
99</div>
100
101<p>For purposes of color allocation, an image is a set of <em>n</em> pixels, where each pixel is a point in RGB space. RGB space is a 3-dimensional vector space, and each pixel, <em>p(i)</em>, is defined by an ordered triple of red, green, and blue coordinates, (<em>r(i)</em>, <em>g(i)</em>, <em>b(i)</em>).</p>
102
103<p>Each primary color component (<em>red</em>, <em>green</em>, or <em>blue</em>) represents an intensity which varies linearly from 0 to a maximum value, <em>Cmax</em>, which corresponds to full saturation of that color. Color allocation is defined over a domain consisting of the cube in RGB space with opposite vertices at (0, 0, 0) and (<em>Cmax</em>, <em>Cmax</em>, <em>Cmax</em>).  ImageMagick requires <em>Cmax</em>= <em>255</em>.</p>
104
105<p>The algorithm maps this domain onto a tree in which each node represents a cube within that domain. In the following discussion, these cubes are defined by the coordinate of two opposite vertices: The vertex nearest the origin in RGB space and the vertex farthest from the origin.</p>
106
107<p>The tree's root node represents the entire domain, (0,0,0) through (<em>Cmax</em>, <em>Cmax</em>, <em>Cmax</em>). Each lower level in the tree is generated by subdividing one node's cube into eight smaller cubes of equal size. This corresponds to bisecting the parent cube with planes passing through the midpoints of each edge.</p>
108
109<p>The basic algorithm operates in three phases:</p>
110
111<ol>
112  <li>Classification</li>
113  <li>Reduction</li>
114  <li>Assignment</li>
115</ol>
116
117<p><b>Classification</b><p>
118
119<p>Classification builds a color description tree for the image. Reduction collapses the tree until the number it represents, at most, is the number of colors desired in the output image. Assignment defines the output image's color map and sets each pixel's color by reclassification in the reduced tree.  <em>Our goal is to minimize the numerical discrepancies between the original colors and quantized colors</em>. To learn more about quantization error, see <a href="#measure">Measuring Color Reduction Error</a>.</p>
120
121<p>Classification begins by initializing a color description tree of sufficient depth to represent each possible input color in a leaf. However, it is impractical to generate a fully-formed color description tree in the classification phase for realistic values of <em>Cmax</em>. If color components in the input image are quantized to <em>k</em>-bit precision, so that <em>Cmax</em> = <em>2^k-1</em>, the tree would need <em>k</em> levels below the root node to allow representing each possible input color in a leaf.  This becomes prohibitive because the tree's total number of nodes:</p>
122
123<pre class="text">
124  total nodes = 1+Sum(8^i), i=1,k
125
126  For k=8,
127  nodes = 1 + (8^1+8^2+....+8^8)
128                 8^8 - 1
129        = 1 + 8.-----------
130                   8 - 1
131        = 19,173,961
132</pre>
133
134<p>Therefore, to avoid building a fully populated tree, ImageMagick:</p>
135
136<ol>
137  <li>initializes data structures for nodes only as they are needed;</li>
138  <li>chooses a maximum depth for the tree as a function of the desired number of colors in the output image (currently <em>based-two</em> logarithm of <em>Cmax</em>).</li>
139</ol>
140
141<pre class="text">
142  For Cmax=255,
143                     
144  Maximum tree depth = log (256) 
145                          2
146                     = log (256) / log (2)
147                          e           e
148                     = 8
149</pre>
150
151<p>A tree of this depth generally allows the best representation of the source image with the fastest computational speed and the least amount of memory. However, the default depth is inappropriate for some images. Therefore, the caller can request a specific tree depth.</p>
152
153<p>For each pixel in the input image, classification scans downward from the root of the color description tree. At each level of the tree, it identifies the single node which represents a cube in RGB space containing the pixels' color. It updates the following data for each such node:</p>
154
155<ul>
156<dt>n1</dt>
157        <dd>number of pixels whose color is contained in the RGB cube which this node represents;</dd><br />
158<dt>n2</dt>
159  <dd>number of pixels whose color is not represented in a node at lower depth in the tree; initially, <em>n2=0</em> for all nodes except leaves of the tree.</dd><br />
160<dt>Sr,Sg,Sb</dt>
161  <dd>sums of the <em>red</em>, <em>green</em>, and <em>blue</em> component values for all pixels not classified at a lower depth. The combination of these sums and <em>n2</em> will ultimately characterize the mean color of a set of pixels represented by this node.</dd><br />
162<dt>E</dt>
163  <dd>the distance squared in RGB space between each pixel contained within a node and the nodes' center. This represents the quantization error for a node.</dd>
164</ul>
165
166<p><b>Reduction</b><p>
167
168<p>Reduction repeatedly prunes the tree until the number of nodes with <em>n2</em> &gt; <em>0</em> is less than or equal to the maximum number of colors allowed in the output image. On any given iteration over the tree, it selects those nodes whose <em>E</em> value is minimal for pruning and merges their color statistics upward. It uses a pruning threshold, <em>Ep</em>, to govern node selection as follows:</p> 
169
170<pre class="text">
171  Ep = 0
172  while number of nodes with (n2 &gt; 0) &gt; required maximum number of colors
173     prune all nodes such that E &lt;= Ep
174     Set Ep  to minimum E in remaining nodes
175</pre>
176
177<p>This has the effect of minimizing any quantization error when merging two nodes together.</p>
178
179<p>When a node to be pruned has offspring, the pruning procedure invokes itself recursively in order to prune the tree from the leaves upward. The values of <em>n2</em>, <em>Sr</em>, <em>Sg</em>, and <em>Sb</em> in a node being pruned are always added to the corresponding data in that node's parent. This retains the pruned node's color characteristics for later averaging.</p>
180
181<p>For each node, <em>n2</em> pixels exist for which that node represents the smallest volume in RGB space containing those pixel's colors. When <em>n2</em> &gt; <em>0</em> the node will uniquely define a color in the output image. At the beginning of reduction, <em>n2</em> = <em>0</em> for all nodes except the leaves of the tree which represent colors present in the input image.</p>
182
183<p>The other pixel count, <em>n1</em>, indicates the total number of colors within the cubic volume which the node represents. This includes <em>n1</em> - <em>n2</em> pixels whose colors should be defined by nodes at a lower level in the tree.</p>
184
185<p><b>Assignment</b><p>
186
187<p>Assignment generates the output image from the pruned tree. The output image consists of two parts:</p>
188<ol>
189  <li>A color map, which is an array of color descriptions (RGB triples) for each color present in the output image.</li>
190
191  <li>A pixel array, which represents each pixel as an index into the color map array.</li>
192</ol>
193
194<p>First, the assignment phase makes one pass over the pruned color description tree to establish the image's color map. For each node with <em>n2</em> &gt; <em>0</em>, it divides <em>Sr</em>, <em>Sg</em>, and <em>Sb</em> by <em>n2</em>. This produces the mean color of all pixels that classify no lower than this node. Each of these colors becomes an entry in the color map.</p>
195
196<p>Finally, the assignment phase reclassifies each pixel in the pruned tree to identify the deepest node containing the pixel's color. The pixel's value in the pixel array becomes the index of this node's mean color in the color map.</p>
197
198<p>Empirical evidence suggests that the distances in color spaces such as YUV, or YIQ correspond to perceptual color differences more closely than do distances in RGB space.  These color spaces may give better results when color reducing an image. Here the algorithm is as described except each pixel is a point in the alternate color space. For convenience, the color components are normalized to the range 0 to a maximum value, <em>Cmax</em>. The color reduction can then proceed as described.</p>
199
200<div style="margin: auto;">
201  <h2><a name="measure"></a>Measuring Color Reduction Error</h2>
202</div>
203
204<p>Depending on the image, the color reduction error may be obvious or invisible. Images with high spatial frequencies (such as hair or grass) will show error much less than pictures with large smoothly shaded areas (such as faces). This because the high-frequency contour edges introduced by the color reduction process are masked by the high frequencies in the image.</p>
205
206<p>To measure the difference between the original and color reduced images (the total color reduction error), ImageMagick sums over all pixels in an image the distance squared in RGB space between each original pixel value and its color reduced value. ImageMagick prints several error measurements including the mean error per pixel, the normalized mean error, and the normalized maximum error.</p>
207
208<p>The normalized error measurement can be used to compare images.  In general, the closer the mean error is to zero the more the quantized image resembles the source image. Ideally, the error should be perceptually-based, since the human eye is the final judge of quantization quality.</p>
209
210<p>These errors are measured and printed when the <a href="../www/command-line-options.html#colors">-colors</a> and <a href="../www/command-line-options.html#verbose">-verbose</a> options are specified on the <a href="../www/convert.html">convert</a> command line:</p>
211
212<ul>
213<dt>mean error per pixel</dt>
214  <dd>is the mean error for any single pixel in the image.</dd><br />
215<dt>normalized mean square error</dt>
216  <dd>is the normalized mean square quantization error for any single pixel in the image. This distance measure is normalized to a range between 0 and 1. It is independent of the range of red, green, and blue values in the image.</dd><br />
217<dt>normalized maximum square error</dt>
218  <dd>is the largest normalized square quantization error for any single pixel in the image. This distance measure is normalized to a range between of red, green, and blue values in the image.</dd>
219</ul>
220      </td>
221      <td id="margin" width="1%" height="100%" valign="top" align="right">&nbsp;</td>
222    </tr>
223  </tbody>
224  </table>
225  <div id="linkbar">
226    <span id="linkbar-west">
227      <font size="-1">
228      <a href="http://www.downloadroute.com/" target="903667060">Downloads and Opinions</a><!-- 200810010100 -->
229      </font>
230    </span>
231    <span id="linkbar-center">
232      <a href="http://www.imagemagick.org/discourse-server/" target="191040520">Discourse Server</a> &bull;
233      <a href="../www/mailing-list.html">Mailing Lists</a> &bull;
234      <a href="http://cafe.imagemagick.org" target="1978293702">Cafe</a> &bull;
235    <a href="http://studio.webbyland.com/ImageMagick/MagickStudio/scripts/MagickStudio.cgi" target="407436086">Studio</a>
236    </span>
237  </div>
238  <div id="footer">
239    <span id="footer-west">&copy; 1999-2008 ImageMagick Studio LLC</span>
240  </div>
241  <div style="clear: both; margin: 0; width: 100%; "></div>
242</body>
243</html>
Note: See TracBrowser for help on using the browser.