blob: 6305bf03818288a146fd41e8970ed67be3992e71 [file] [log] [blame]
<!-- Copyright 2008 Lubomir Bourdev and Hailin Jin
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
-->
<!--
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
Some files are held under additional license.
Please see "http://stlab.adobe.com/licenses.html" for more information.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<TITLE>Generic Image Library: Generic Image Library Tutorial</TITLE>
<META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/>
<LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0" style='width: 100%; margin: 0; padding: 0'><tr>
<td width="100%" valign="top" style='padding-left: 10px; padding-right: 10px; padding-bottom: 10px'>
<div class="qindex"><a class="qindex" href="index.html">Modules</a>
| <a class="qindex" href="classes.html">Alphabetical List</a>
| <a class="qindex" href="annotated.html">Class List</a>
| <a class="qindex" href="dirs.html">Directories</a>
| <a class="qindex" href="files.html">File List</a>
| <a class="qindex" href="../index.html">GIL Home Page</a>
</div>
<!-- End Header -->
<!-- Generated by Doxygen 1.5.6 -->
<div class="contents">
<h1><a class="anchor" name="GILTutorial">Generic Image Library Tutorial </a></h1><dl class="author" compact><dt><b>Author:</b></dt><dd>Lubomir Bourdev (<a href="mailto:lbourdev@adobe.com">lbourdev@adobe.com</a>) and Hailin Jin (<a href="mailto:hljin@adobe.com">hljin@adobe.com</a>) <br>
Adobe Systems Incorporated</dd></dl>
<dl class="version" compact><dt><b>Version:</b></dt><dd>2.1 </dd></dl>
<dl class="date" compact><dt><b>Date:</b></dt><dd>September 15, 2007</dd></dl>
The Generic Image Library (GIL) is a C++ library that abstracts image representations from algorithms and allows writing code that can work on a variety of images with performance similar to hand-writing for a specific image type. <p>
This document will give you a jump-start in using GIL. It does not discuss the underlying design of the library and does not cover all aspects of it. You can find a detailed library design document on the main GIL web page at <a href="http://stlab.adobe.com/gil">http://stlab.adobe.com/gil</a><p>
<ul>
<li><a class="el" href="giltutorial.html#InstallSec">Installation</a></li><li><a class="el" href="giltutorial.html#ExampleSec">Example - Computing the Image Gradient</a><ul>
<li><a class="el" href="giltutorial.html#InterfaceSec">Interface and Glue Code</a></li><li><a class="el" href="giltutorial.html#FirstImplementationSec">First Implementation</a></li><li><a class="el" href="giltutorial.html#LocatorsSec">Using Locators</a></li><li><a class="el" href="giltutorial.html#GenericVersionSec">Creating a Generic Version of GIL Algorithms</a></li><li><a class="el" href="giltutorial.html#ImageViewTransformationSec">Image View Transformations</a></li><li><a class="el" href="giltutorial.html#OneDIteratorsSec">1D pixel iterators</a></li><li><a class="el" href="giltutorial.html#STLEquivalentsSec">STL Equivalent Algorithms</a></li><li><a class="el" href="giltutorial.html#ColorConversionSec">Color Conversion</a></li><li><a class="el" href="giltutorial.html#ImagesSec">Image</a></li><li><a class="el" href="giltutorial.html#VirtualViewSec">Virtual Image Views</a></li><li><a class="el" href="giltutorial.html#DynamicImageSec">Run-Time Specified Images and Image Views</a></li><li><a class="el" href="giltutorial.html#ConclusionSec">Conclusion</a></li></ul>
</li><li><a class="el" href="giltutorial.html#AppendixSec">Appendix</a><ul>
<li><a class="el" href="giltutorial.html#AppendixConventionSec">Naming convention for GIL concrete types</a></li></ul>
</li></ul>
<h2><a class="anchor" name="InstallSec">
Installation</a></h2>
The latest version of GIL can be downloaded from GIL's web page, at <a href="http://stlab.adobe.com/gil.">http://stlab.adobe.com/gil.</a> GIL is approved for integration into Boost and in the future will be installed simply by installing Boost from <a href="http://www.boost.org.">http://www.boost.org.</a> GIL consists of header files only and does not require any libraries to link against. It does not require Boost to be built. Including <code><a class="el" href="gil__all_8hpp.html" title="Includes all GIL files for convenience.">boost/gil/gil_all.hpp</a></code> will be sufficient for most projects.<h2><a class="anchor" name="ExampleSec">
Example - Computing the Image Gradient</a></h2>
This tutorial will walk through an example of using GIL to compute the image gradients. We will start with some very simple and non-generic code and make it more generic as we go along. Let us start with a horizontal gradient and use the simplest possible approximation to a gradient - central difference. The gradient at pixel x can be approximated with the half-difference of its two neighboring pixels: D[x] = (I[x-1] - I[x+1]) / 2<p>
For simplicity, we will also ignore the boundary cases - the pixels along the edges of the image for which one of the neighbors is not defined. The focus of this document is how to use GIL, not how to create a good gradient generation algorithm.<h3><a class="anchor" name="InterfaceSec">
Interface and Glue Code</a></h3>
Let us first start with 8-bit unsigned grayscale image as the input and 8-bit signed grayscale image as the output. Here is how the interface to our algorithm looks like:<p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="gil__all_8hpp.html" title="Includes all GIL files for convenience.">boost/gil/gil_all.hpp</a>&gt;</span>
<span class="keyword">using namespace </span>boost::gil;
<span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
assert(src.dimensions() == dst.dimensions());
... <span class="comment">// compute the gradient</span>
}
</pre></div><p>
<code>gray8c_view_t</code> is the type of the source image view - an 8-bit grayscale view, whose pixels are read-only (denoted by the <code>"c"</code>). The output is a grayscale view with a 8-bit signed (denoted by the <code>"s"</code>) integer channel type. See Appendix 1 for the complete convension GIL uses to name concrete types.<p>
GIL makes a distinction between an image and an image view. A GIL <em>image view</em>, is a shallow, lightweight view of a rectangular grid of pixels. It provides access to the pixels but does not own the pixels. Copy-constructing a view does not deep-copy the pixels. Image views do not propagate their constness to the pixels and should always be taken by a const reference. Whether a view is mutable or read-only (immutable) is a property of the view type.<p>
A GIL <em>image</em>, on the other hand, is a view with associated ownership. It is a container of pixels; its constructor/destructor allocates/deallocates the pixels, its copy-constructor performs deep-copy of the pixels and its operator== performs deep-compare of the pixels. Images also propagate their constness to their pixels - a constant reference to an image will not allow for modifying its pixels.<p>
Most GIL algorithms operate on image views; images are rarely needed. GIL's design is very similar to that of the STL. The STL equivalent of GIL's image is a container, like <code>std::vector</code>, whereas GIL's image view corresponds to STL's range, which is often represented with a pair of iterators. STL algorithms operate on ranges, just like GIL algorithms operate on image views.<p>
GIL's image views can be constructed from raw data - the dimensions, the number of bytes per row and the pixels, which for chunky views are represented with one pointer. Here is how to provide the glue between your code and GIL:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> ComputeXGradientGray8(<span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span>* src_pixels, ptrdiff_t src_row_bytes, <span class="keywordtype">int</span> w, <span class="keywordtype">int</span> h,
<span class="keywordtype">signed</span> <span class="keywordtype">char</span>* dst_pixels, ptrdiff_t dst_row_bytes) {
gray8c_view_t src = <a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w, h, (<span class="keyword">const</span> gray8_pixel_t*)src_pixels,src_row_bytes);
gray8s_view_t dst = <a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w, h, ( gray8s_pixel_t*)dst_pixels,dst_row_bytes);
x_gradient(src,dst);
}
</pre></div><p>
This glue code is very fast and views are lightweight - in the above example the views have a size of 16 bytes. They consist of a pointer to the top left pixel and three integers - the width, height, and number of bytes per row.<h3><a class="anchor" name="FirstImplementationSec">
First Implementation</a></h3>
Focusing on simplicity at the expense of speed, we can compute the horizontal gradient like this:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=0; y&lt;src.height(); ++y)
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=1; x&lt;src.width()-1; ++x)
dst(x,y) = (src(x-1,y) - src(x+1,y)) / 2;
}
</pre></div><p>
We use image view's <code>operator(x,y)</code> to get a reference to the pixel at a given location and we set it to the half-difference of its left and right neighbors. operator() returns a reference to a grayscale pixel. A grayscale pixel is convertible to its channel type (<code>unsigned char</code> for <code>src</code>) and it can be copy-constructed from a channel. (This is only true for grayscale pixels). While the above code is easy to read, it is not very fast, because the binary <code>operator()</code> computes the location of the pixel in a 2D grid, which involves addition and multiplication. Here is a faster version of the above:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=0; y&lt;src.height(); ++y) {
gray8c_view_t::x_iterator src_it = src.row_begin(y);
gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=1; x&lt;src.width()-1; ++x)
dst_it[x] = (src_it[x-1] - src_it[x+1]) / 2;
}
}
</pre></div><p>
We use pixel iterators initialized at the beginning of each row. GIL's iterators are Random Access Traversal iterators. If you are not familiar with random access iterators, think of them as if they were pointers. In fact, in the above example the two iterator types are raw C pointers and their <code>operator</code>[] is a fast pointer indexing operator.<p>
The code to compute gradient in the vertical direction is very similar:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> y_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=0; x&lt;src.width(); ++x) {
gray8c_view_t::y_iterator src_it = src.col_begin(x);
gray8s_view_t::y_iterator dst_it = dst.col_begin(x);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=1; y&lt;src.height()-1; ++y)
dst_it[y] = (src_it[y-1] - src_it[y+1])/2;
}
}
</pre></div><p>
Instead of looping over the rows, we loop over each column and create a <code>y_iterator</code>, an iterator moving vertically. In this case a simple pointer cannot be used because the distance between two adjacent pixels equals the number of bytes in each row of the image. GIL uses here a special step iterator class whose size is 8 bytes - it contains a raw C pointer and a step. Its <code>operator</code>[] multiplies the index by its step.<p>
The above version of <code>y_gradient</code>, however, is much slower (easily an order of magnitude slower) than <code>x_gradient</code> because of the memory access pattern; traversing an image vertically results in lots of cache misses. A much more efficient and cache-friendly version will iterate over the columns in the inner loop:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> y_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=1; y&lt;src.height()-1; ++y) {
gray8c_view_t::x_iterator src1_it = src.row_begin(y-1);
gray8c_view_t::x_iterator src2_it = src.row_begin(y+1);
gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=0; x&lt;src.width(); ++x) {
*dst_it = ((*src1_it) - (*src2_it))/2;
++dst_it;
++src1_it;
++src2_it;
}
}
}
</pre></div><p>
This sample code also shows an alternative way of using pixel iterators - instead of <code>operator</code>[] one could use increments and dereferences.<h3><a class="anchor" name="LocatorsSec">
Using Locators</a></h3>
Unfortunately this cache-friendly version requires the extra hassle of maintaining two separate iterators in the source view. For every pixel, we want to access its neighbors above and below it. Such relative access can be done with GIL locators:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> y_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
gray8c_view_t::xy_locator src_loc = src.xy_at(0,1);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=1; y&lt;src.height()-1; ++y) {
gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=0; x&lt;src.width(); ++x) {
(*dst_it) = (src_loc(0,-1) - src_loc(0,1)) / 2;
++dst_it;
++src_loc.x(); <span class="comment">// each dimension can be advanced separately</span>
}
src_loc+=point2&lt;std::ptrdiff_t&gt;(-src.width(),1); <span class="comment">// carriage return</span>
}
}
</pre></div><p>
The first line creates a locator pointing to the first pixel of the second row of the source view. A GIL pixel locator is very similar to an iterator, except that it can move both horizontally and vertically. <code>src_loc.x()</code> and <code>src_loc.y()</code> return references to a horizontal and a vertical iterator respectively, which can be used to move the locator along the desired dimension, as shown above. Additionally, the locator can be advanced in both dimensions simultaneously using its <code>operator+=</code> and <code>operator-=</code>. Similar to image views, locators provide binary <code>operator()</code> which returns a reference to a pixel with a relative offset to the current locator position. For example, <code>src_loc(0,1)</code> returns a reference to the neighbor below the current pixel. Locators are very lightweight objects - in the above example the locator has a size of 8 bytes - it consists of a raw pointer to the current pixel and an int indicating the number of bytes from one row to the next (which is the step when moving vertically). The call to <code>++src_loc</code>.x() corresponds to a single C pointer increment. However, the example above performs more computations than necessary. The code src_loc(0,1) has to compute the offset of the pixel in two dimensions, which is slow. Notice though that the offset of the two neighbors is the same, regardless of the pixel location. To improve the performance, GIL can cache and reuse this offset:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> y_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
gray8c_view_t::xy_locator src_loc = src.xy_at(0,1);
gray8c_view_t::xy_locator::cached_location_t above = src_loc.cache_location(0,-1);
gray8c_view_t::xy_locator::cached_location_t below = src_loc.cache_location(0, 1);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=1; y&lt;src.height()-1; ++y) {
gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=0; x&lt;src.width(); ++x) {
(*dst_it) = (src_loc[above] - src_loc[below])/2;
++dst_it;
++src_loc.x();
}
src_loc+=point2&lt;std::ptrdiff_t&gt;(-src.width(),1);
}
}
</pre></div><p>
In this example <code>"src_loc[above]"</code> corresponds to a fast pointer indexing operation and the code is efficient.<h3><a class="anchor" name="GenericVersionSec">
Creating a Generic Version of GIL Algorithms</a></h3>
Let us make our <code>x_gradient</code> more generic. It should work with any image views, as long as they have the same number of channels. The gradient operation is to be computed for each channel independently. Here is how the new interface looks like:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
gil_function_requires&lt;ImageViewConcept&lt;SrcView&gt; &gt;();
gil_function_requires&lt;MutableImageViewConcept&lt;DstView&gt; &gt;();
gil_function_requires&lt;ColorSpacesCompatibleConcept&lt;
<span class="keyword">typename</span> color_space_type&lt;SrcView&gt;::type,
<span class="keyword">typename</span> color_space_type&lt;DstView&gt;::type&gt; &gt;();
... <span class="comment">// compute the gradient</span>
}
</pre></div><p>
The new algorithm now takes the types of the input and output image views as template parameters. That allows using both built-in GIL image views, as well as any user-defined image view classes. The first three lines are optional; they use <code>boost::concept_check</code> to ensure that the two arguments are valid GIL image views, that the second one is mutable and that their color spaces are compatible (i.e. have the same set of channels).<p>
GIL does not require using its own built-in constructs. You are free to use your own channels, color spaces, iterators, locators, views and images. However, to work with the rest of GIL they have to satisfy a set of requirements; in other words, they have to <em>model</em> the corresponding GIL <em>concept</em>. GIL's concepts are defined in the user guide.<p>
One of the biggest drawbacks of using templates and generic programming in C++ is that compile errors can be very difficult to comprehend. This is a side-effect of the lack of early type checking - a generic argument may not satisfy the requirements of a function, but the incompatibility may be triggered deep into a nested call, in code unfamiliar and hardly related to the problem. GIL uses <code>boost::concept_check</code> to mitigate this problem. The above three lines of code check whether the template parameters are valid models of their corresponding concepts. If a model is incorrect, the compile error will be inside <code>gil_function_requires</code>, which is much closer to the problem and easier to track. Furthermore, such checks get compiled out and have zero performance overhead. The disadvantage of using concept checks is the sometimes severe impact they have on compile time. This is why GIL performs concept checks only in debug mode, and only if <code>BOOST_GIL_USE_CONCEPT_CHECK</code> is defined (off by default).<p>
The body of the generic function is very similar to that of the concrete one. The biggest difference is that we need to loop over the channels of the pixel and compute the gradient for each channel:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=0; y&lt;src.height(); ++y) {
<span class="keyword">typename</span> SrcView::x_iterator src_it = src.row_begin(y);
<span class="keyword">typename</span> DstView::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=1; x&lt;src.width()-1; ++x)
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> c=0; c&lt;num_channels&lt;SrcView&gt;::value; ++c)
dst_it[x][c] = (src_it[x-1][c]- src_it[x+1][c])/2;
}
}
</pre></div><p>
Having an explicit loop for each channel could be a performance problem. GIL allows us to abstract out such per-channel operations:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> Out&gt;
<span class="keyword">struct </span>halfdiff_cast_channels {
<span class="keyword">template</span> &lt;<span class="keyword">typename</span> T&gt; Out operator()(<span class="keyword">const</span> T&amp; in1, <span class="keyword">const</span> T&amp; in2)<span class="keyword"> const </span>{
<span class="keywordflow">return</span> Out((in1-in2)/2);
}
};
<span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
<span class="keyword">typedef</span> <span class="keyword">typename</span> channel_type&lt;DstView&gt;::type dst_channel_t;
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=0; y&lt;src.height(); ++y) {
<span class="keyword">typename</span> SrcView::x_iterator src_it = src.row_begin(y);
<span class="keyword">typename</span> DstView::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=1; x&lt;src.width()-1; ++x)
static_transform(src_it[x-1], src_it[x+1], dst_it[x],
halfdiff_cast_channels&lt;dst_channel_t&gt;());
}
}
</pre></div><p>
<code>static_transform</code> is an example of a channel-level GIL algorithm. Other such algorithms are <code>static_generate</code>, <code>static_fill</code> and <code>static_for_each</code>. They are the channel-level equivalents of STL's <code>generate</code>, <code>transform</code>, <code>fill</code> and <code>for_each</code> respectively. GIL channel algorithms use static recursion to unroll the loops; they never loop over the channels explicitly. Note that sometimes modern compilers (at least Visual Studio 8) already unroll channel-level loops, such as the one above. However, another advantage of using GIL's channel-level algorithms is that they pair the channels semantically, not based on their order in memory. For example, the above example will properly match an RGB source with a BGR destination.<p>
Here is how we can use our generic version with images of different types:<p>
<div class="fragment"><pre class="fragment"><span class="comment">// Calling with 16-bit grayscale data</span>
<span class="keywordtype">void</span> XGradientGray16_Gray32(<span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">short</span>* src_pixels, ptrdiff_t src_row_bytes, <span class="keywordtype">int</span> w, <span class="keywordtype">int</span> h,
<span class="keywordtype">signed</span> <span class="keywordtype">int</span>* dst_pixels, ptrdiff_t dst_row_bytes) {
gray16c_view_t src=<a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w,h,(<span class="keyword">const</span> gray16_pixel_t*)src_pixels,src_row_bytes);
gray32s_view_t dst=<a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w,h,( gray32s_pixel_t*)dst_pixels,dst_row_bytes);
x_gradient(src,dst);
}
<span class="comment">// Calling with 8-bit RGB data into 16-bit BGR</span>
<span class="keywordtype">void</span> XGradientRGB8_BGR16(<span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span>* src_pixels, ptrdiff_t src_row_bytes, <span class="keywordtype">int</span> w, <span class="keywordtype">int</span> h,
<span class="keywordtype">signed</span> <span class="keywordtype">short</span>* dst_pixels, ptrdiff_t dst_row_bytes) {
rgb8c_view_t src = <a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w,h,(<span class="keyword">const</span> rgb8_pixel_t*)src_pixels,src_row_bytes);
rgb16s_view_t dst = <a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w,h,( rgb16s_pixel_t*)dst_pixels,dst_row_bytes);
x_gradient(src,dst);
}
<span class="comment">// Either or both the source and the destination could be planar - the gradient code does not change</span>
<span class="keywordtype">void</span> XGradientPlanarRGB8_RGB32(
<span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">short</span>* src_r, <span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">short</span>* src_g, <span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">short</span>* src_b,
ptrdiff_t src_row_bytes, <span class="keywordtype">int</span> w, <span class="keywordtype">int</span> h,
<span class="keywordtype">signed</span> <span class="keywordtype">int</span>* dst_pixels, ptrdiff_t dst_row_bytes) {
rgb16c_planar_view_t src=<a class="code" href="g_i_l_0140.html#g294f43780e7b88f43b91fdd6346cb51b" title="from raw RGB planar data">planar_rgb_view</a> (w,h, src_r,src_g,src_b, src_row_bytes);
rgb32s_view_t dst=<a class="code" href="g_i_l_0140.html#g258d615c33c66b17c85b018297164df1" title="Constructing image views from raw interleaved pixel data.">interleaved_view</a>(w,h,(rgb32s_pixel_t*)dst_pixels,dst_row_bytes);
x_gradient(src,dst);
}
</pre></div><p>
As these examples illustrate, both the source and the destination can be interleaved or planar, of any channel depth (assuming the destination channel is assignable to the source), and of any compatible color spaces.<p>
GIL 2.1 can also natively represent images whose channels are not byte-aligned, such as 6-bit RGB222 image or a 1-bit Gray1 image. GIL algorithms apply to these images natively. See the design guide or sample files for more on using such images.<h3><a class="anchor" name="ImageViewTransformationSec">
Image View Transformations</a></h3>
One way to compute the y-gradient is to rotate the image by 90 degrees, compute the x-gradient and rotate the result back. Here is how to do this in GIL:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> y_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
x_gradient(rotated90ccw_view(src), rotated90ccw_view(dst));
}
</pre></div><p>
<code>rotated90ccw_view</code> takes an image view and returns an image view representing 90-degrees counter-clockwise rotation of its input. It is an example of a GIL view transformation function. GIL provides a variety of transformation functions that can perform any axis-aligned rotation, transpose the view, flip it vertically or horizontally, extract a rectangular subimage, perform color conversion, subsample view, etc. The view transformation functions are fast and shallow - they don't copy the pixels, they just change the "coordinate system" of accessing the pixels. <code>rotated90cw_view</code>, for example, returns a view whose horizontal iterators are the vertical iterators of the original view. The above code to compute <code>y_gradient</code> is slow because of the memory access pattern; using <code>rotated90cw_view</code> does not make it any slower.<p>
Another example: suppose we want to compute the gradient of the N-th channel of a color image. Here is how to do that:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> nth_channel_x_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keywordtype">int</span> n, <span class="keyword">const</span> DstView&amp; dst) {
x_gradient(nth_channel_view(src, n), dst);
}
</pre></div><p>
<code>nth_channel_view</code> is a view transformation function that takes any view and returns a single-channel (grayscale) view of its N-th channel. For interleaved RGB view, for example, the returned view is a step view - a view whose horizontal iterator skips over two channels when incremented. If applied on a planar RGB view, the returned type is a simple grayscale view whose horizontal iterator is a C pointer. Image view transformation functions can be piped together. For example, to compute the y gradient of the second channel of the even pixels in the view, use:<p>
<div class="fragment"><pre class="fragment">y_gradient(subsampled_view(nth_channel_view(src, 1), 2,2), dst);
</pre></div><p>
GIL can sometimes simplify piped views. For example, two nested subsampled views (views that skip over pixels in X and in Y) can be represented as a single subsampled view whose step is the product of the steps of the two views.<h3><a class="anchor" name="OneDIteratorsSec">
1D pixel iterators</a></h3>
Let's go back to <code>x_gradient</code> one more time. Many image view algorithms apply the same operation for each pixel and GIL provides an abstraction to handle them. However, our algorithm has an unusual access pattern, as it skips the first and the last column. It would be nice and instructional to see how we can rewrite it in canonical form. The way to do that in GIL is to write a version that works for every pixel, but apply it only on the subimage that excludes the first and last column:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> x_gradient_unguarded(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> y=0; y&lt;src.height(); ++y) {
gray8c_view_t::x_iterator src_it = src.row_begin(y);
gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> x=0; x&lt;src.width(); ++x)
dst_it[x] = (src_it[x-1] - src_it[x+1]) / 2;
}
}
<span class="keywordtype">void</span> x_gradient(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
assert(src.width()&gt;=2);
x_gradient_unguarded(subimage_view(src, 1, 0, src.width()-2, src.height()),
subimage_view(dst, 1, 0, src.width()-2, src.height()));
}
</pre></div><p>
<code>subimage_view</code> is another example of a GIL view transformation function. It takes a source view and a rectangular region (in this case, defined as x_min,y_min,width,height) and returns a view operating on that region of the source view. The above implementation has no measurable performance degradation from the version that operates on the original views.<p>
Now that <code>x_gradient_unguarded</code> operates on every pixel, we can rewrite it more compactly:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> x_gradient_unguarded(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
gray8c_view_t::iterator src_it = src.begin();
<span class="keywordflow">for</span> (gray8s_view_t::iterator dst_it = dst.begin(); dst_it!=dst.end(); ++dst_it, ++src_it)
*dst_it = (src_it.x()[-1] - src_it.x()[1]) / 2;
}
</pre></div><p>
GIL image views provide <code>begin()</code> and <code>end()</code> methods that return one dimensional pixel iterators which iterate over each pixel in the view, left to right and top to bottom. They do a proper "carriage return" - they skip any unused bytes at the end of a row. As such, they are slightly suboptimal, because they need to keep track of their current position with respect to the end of the row. Their increment operator performs one extra check (are we at the end of the row?), a check that is avoided if two nested loops are used instead. These iterators have a method <code>x()</code> which returns the more lightweight horizontal iterator that we used previously. Horizontal iterators have no notion of the end of rows. In this case, the horizontal iterators are raw C pointers. In our example, we must use the horizontal iterators to access the two neighbors properly, since they could reside outside the image view.<h3><a class="anchor" name="STLEquivalentsSec">
STL Equivalent Algorithms</a></h3>
GIL provides STL equivalents of many algorithms. For example, <code>std::transform</code> is an STL algorithm that sets each element in a destination range the result of a generic function taking the corresponding element of the source range. In our example, we want to assign to each destination pixel the value of the half-difference of the horizontal neighbors of the corresponding source pixel. If we abstract that operation in a function object, we can use GIL's <code>transform_pixel_positions</code> to do that:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">struct </span>half_x_difference {
<span class="keywordtype">int</span> operator()(<span class="keyword">const</span> gray8c_loc_t&amp; src_loc)<span class="keyword"> const </span>{
<span class="keywordflow">return</span> (src_loc.x()[-1] - src_loc.x()[1]) / 2;
}
};
<span class="keywordtype">void</span> x_gradient_unguarded(<span class="keyword">const</span> gray8c_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
<a class="code" href="g_i_l_0153.html#gc74f3114086b954dfd1735a918f68389" title="Like transform_pixels but passes to the function object pixel locators instead of...">transform_pixel_positions</a>(src, dst, half_x_difference());
}
</pre></div><p>
GIL provides the algorithms <code>for_each_pixel</code> and <code>transform_pixels</code> which are image view equivalents of STL's <code>std::for_each</code> and <code>std::transform</code>. It also provides <code>for_each_pixel_position</code> and <code>transform_pixel_positions</code>, which instead of references to pixels, pass to the generic function pixel locators. This allows for more powerful functions that can use the pixel neighbors through the passed locators. GIL algorithms iterate through the pixels using the more efficient two nested loops (as opposed to the single loop using 1-D iterators)<h3><a class="anchor" name="ColorConversionSec">
Color Conversion</a></h3>
Instead of computing the gradient of each color plane of an image, we often want to compute the gradient of the luminosity. In other words, we want to convert the color image to grayscale and compute the gradient of the result. Here how to compute the luminosity gradient of a 32-bit float RGB image:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> x_gradient_rgb_luminosity(<span class="keyword">const</span> rgb32fc_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
x_gradient(color_converted_view&lt;gray8_pixel_t&gt;(src), dst);
}
</pre></div><p>
<code>color_converted_view</code> is a GIL view transformation function that takes any image view and returns a view in a target color space and channel depth (specified as template parameters). In our example, it constructs an 8-bit integer grayscale view over 32-bit float RGB pixels. Like all other view transformation functions, <code>color_converted_view</code> is very fast and shallow. It doesn't copy the data or perform any color conversion. Instead it returns a view that performs color conversion every time its pixels are accessed.<p>
In the generic version of this algorithm we might like to convert the color space to grayscale, but keep the channel depth the same. We do that by constructing the type of a GIL grayscale pixel with the same channel as the source, and color convert to that pixel type:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_luminosity_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
<span class="keyword">typedef</span> pixel&lt;typename channel_type&lt;SrcView&gt;::type, gray_layout_t&gt; gray_pixel_t;
x_gradient(color_converted_view&lt;gray_pixel_t&gt;(src), dst);
}
</pre></div><p>
When the destination color space and channel type happens to be the same as the source one, color conversion is unnecessary. GIL detects this case and avoids calling the color conversion code at all - i.e. <code>color_converted_view</code> returns back the source view unchanged.<h3><a class="anchor" name="ImagesSec">
Image</a></h3>
The above example has a performance problem - <code>x_gradient</code> dereferences most source pixels twice, which will cause the above code to perform color conversion twice. Sometimes it may be more efficient to copy the color converted image into a temporary buffer and use it to compute the gradient - that way color conversion is invoked once per pixel. Using our non-generic version we can do it like this:<p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> x_luminosity_gradient(<span class="keyword">const</span> rgb32fc_view_t&amp; src, <span class="keyword">const</span> gray8s_view_t&amp; dst) {
gray8_image_t ccv_image(src.dimensions());
<a class="code" href="g_i_l_0145.html#g16f18749152217a2b84733c330a2b415" title="std::copy for image views">copy_pixels</a>(color_converted_view&lt;gray8_pixel_t&gt;(src), <a class="code" href="g_i_l_0135.html#gad0335b7d343667d626556681486f198" title="Returns the non-constant-pixel view of an image.">view</a>(ccv_image));
x_gradient(<a class="code" href="g_i_l_0135.html#ged731349e60a30a3a241fd1809729996" title="Returns the constant-pixel view of an image.">const_view</a>(ccv_image), dst);
}
</pre></div><p>
First we construct an 8-bit grayscale image with the same dimensions as our source. Then we copy a color-converted view of the source into the temporary image. Finally we use a read-only view of the temporary image in our <code>x_gradient</code> algorithm. As the example shows, GIL provides global functions <code>view</code> and <code>const_view</code> that take an image and return a mutable or an immutable view of its pixels.<p>
Creating a generic version of the above is a bit trickier:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_luminosity_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
<span class="keyword">typedef</span> <span class="keyword">typename</span> channel_type&lt;DstView&gt;::type d_channel_t;
<span class="keyword">typedef</span> <span class="keyword">typename</span> channel_convert_to_unsigned&lt;d_channel_t&gt;::type channel_t;
<span class="keyword">typedef</span> pixel&lt;channel_t, gray_layout_t&gt; gray_pixel_t;
<span class="keyword">typedef</span> image&lt;gray_pixel_t, false&gt; gray_image_t;
gray_image_t ccv_image(src.dimensions());
<a class="code" href="g_i_l_0145.html#g16f18749152217a2b84733c330a2b415" title="std::copy for image views">copy_pixels</a>(color_converted_view&lt;gray_pixel_t&gt;(src), <a class="code" href="g_i_l_0135.html#gad0335b7d343667d626556681486f198" title="Returns the non-constant-pixel view of an image.">view</a>(ccv_image));
x_gradient(<a class="code" href="g_i_l_0135.html#ged731349e60a30a3a241fd1809729996" title="Returns the constant-pixel view of an image.">const_view</a>(ccv_image), dst);
}
</pre></div><p>
First we use the <code>channel_type</code> metafunction to get the channel type of the destination view. A metafunction is a function operating on types. In GIL metafunctions are structs which take their parameters as template parameters and return their result in a nested typedef called <code>type</code>. In this case, <code>channel_type</code> is a unary metafunction which in this example is called with the type of an image view and returns the type of the channel associated with that image view.<p>
GIL constructs that have an associated pixel type, such as pixels, pixel iterators, locators, views and images, all model <code>PixelBasedConcept</code>, which means that they provide a set of metafunctions to query the pixel properties, such as <code>channel_type</code>, <code>color_space_type</code>, <code>channel_mapping_type</code>, and <code>num_channels</code>.<p>
After we get the channel type of the destination view, we use another metafunction to remove its sign (if it is a signed integral type) and then use it to generate the type of a grayscale pixel. From the pixel type we create the image type. GIL's image class is templated over the pixel type and a boolean indicating whether the image should be planar or interleaved. Single-channel (grayscale) images in GIL must always be interleaved. There are multiple ways of constructing types in GIL. Instead of instantiating the classes directly we could have used type factory metafunctions. The following code is equivalent:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_luminosity_gradient(<span class="keyword">const</span> SrcView&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
<span class="keyword">typedef</span> <span class="keyword">typename</span> channel_type&lt;DstView&gt;::type d_channel_t;
<span class="keyword">typedef</span> <span class="keyword">typename</span> channel_convert_to_unsigned&lt;d_channel_t&gt;::type channel_t;
<span class="keyword">typedef</span> <span class="keyword">typename</span> image_type&lt;channel_t, gray_layout_t&gt;::type gray_image_t;
<span class="keyword">typedef</span> <span class="keyword">typename</span> gray_image_t::value_type gray_pixel_t;
gray_image_t ccv_image(src.dimensions());
copy_and_convert_pixels(src, <a class="code" href="g_i_l_0135.html#gad0335b7d343667d626556681486f198" title="Returns the non-constant-pixel view of an image.">view</a>(ccv_image));
x_gradient(<a class="code" href="g_i_l_0135.html#ged731349e60a30a3a241fd1809729996" title="Returns the constant-pixel view of an image.">const_view</a>(ccv_image), dst);
}
</pre></div><p>
GIL provides a set of metafunctions that generate GIL types - <code>image_type</code> is one such meta-function that constructs the type of an image from a given channel type, color layout, and planar/interleaved option (the default is interleaved). There are also similar meta-functions to construct the types of pixel references, iterators, locators and image views. GIL also has metafunctions <code>derived_pixel_reference_type</code>, <code>derived_iterator_type</code>, <code>derived_view_type</code> and <code>derived_image_type</code> that construct the type of a GIL construct from a given source one by changing one or more properties of the type and keeping the rest.<p>
From the image type we can use the nested typedef <code>value_type</code> to obtain the type of a pixel. GIL images, image views and locators have nested typedefs <code>value_type</code> and <code>reference</code> to obtain the type of the pixel and a reference to the pixel. If you have a pixel iterator, you can get these types from its <code>iterator_traits</code>. Note also the algorithm <code>copy_and_convert_pixels</code>, which is an abbreviated version of <code>copy_pixels</code> with a color converted source view.<h3><a class="anchor" name="VirtualViewSec">
Virtual Image Views</a></h3>
So far we have been dealing with images that have pixels stored in memory. GIL allows you to create an image view of an arbitrary image, including a synthetic function. To demonstrate this, let us create a view of the Mandelbrot set. First, we need to create a function object that computes the value of the Mandelbrot set at a given location (x,y) in the image: <div class="fragment"><pre class="fragment"><span class="comment">// models PixelDereferenceAdaptorConcept</span>
<span class="keyword">struct </span>mandelbrot_fn {
<span class="keyword">typedef</span> point2&lt;ptrdiff_t&gt; point_t;
<span class="keyword">typedef</span> mandelbrot_fn const_t;
<span class="keyword">typedef</span> gray8_pixel_t value_type;
<span class="keyword">typedef</span> value_type reference;
<span class="keyword">typedef</span> value_type const_reference;
<span class="keyword">typedef</span> point_t argument_type;
<span class="keyword">typedef</span> reference result_type;
BOOST_STATIC_CONSTANT(<span class="keywordtype">bool</span>, is_mutable=<span class="keyword">false</span>);
mandelbrot_fn() {}
mandelbrot_fn(<span class="keyword">const</span> point_t&amp; sz) : _img_size(sz) {}
result_type operator()(<span class="keyword">const</span> point_t&amp; p)<span class="keyword"> const </span>{
<span class="comment">// normalize the coords to (-2..1, -1.5..1.5)</span>
<span class="keywordtype">double</span> t=get_num_iter(point2&lt;double&gt;(p.x/(<span class="keywordtype">double</span>)_img_size.x*3-2, p.y/(<span class="keywordtype">double</span>)_img_size.y*3-1.5f));
<span class="keywordflow">return</span> value_type((bits8)(pow(t,0.2)*255)); <span class="comment">// raise to power suitable for viewing</span>
}
<span class="keyword">private</span>:
point_t _img_size;
<span class="keywordtype">double</span> get_num_iter(<span class="keyword">const</span> point2&lt;double&gt;&amp; p)<span class="keyword"> const </span>{
point2&lt;double&gt; Z(0,0);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> i=0; i&lt;100; ++i) { <span class="comment">// 100 iterations</span>
Z = point2&lt;double&gt;(Z.x*Z.x - Z.y*Z.y + p.x, 2*Z.x*Z.y + p.y);
<span class="keywordflow">if</span> (Z.x*Z.x + Z.y*Z.y &gt; 4)
<span class="keywordflow">return</span> i/(double)100;
}
<span class="keywordflow">return</span> 0;
}
};
</pre></div><p>
We can now use GIL's <code>virtual_2d_locator</code> with this function object to construct a Mandelbrot view of size 200x200 pixels: <div class="fragment"><pre class="fragment"><span class="keyword">typedef</span> mandelbrot_fn::point_t point_t;
<span class="keyword">typedef</span> virtual_2d_locator&lt;mandelbrot_fn,false&gt; locator_t;
<span class="keyword">typedef</span> image_view&lt;locator_t&gt; my_virt_view_t;
point_t dims(200,200);
<span class="comment">// Construct a Mandelbrot view with a locator, taking top-left corner (0,0) and step (1,1)</span>
my_virt_view_t mandel(dims, locator_t(point_t(0,0), point_t(1,1), mandelbrot_fn(dims)));
</pre></div><p>
We can treat the synthetic view just like a real one. For example, let's invoke our <code>x_gradient</code> algorithm to compute the gradient of the 90-degree rotated view of the Mandelbrot set and save the original and the result:<p>
<div class="fragment"><pre class="fragment">gray8s_image_t img(dims);
x_gradient(rotated90cw_view(mandel), <a class="code" href="g_i_l_0135.html#gad0335b7d343667d626556681486f198" title="Returns the non-constant-pixel view of an image.">view</a>(img));
<span class="comment">// Save the Mandelbrot set and its 90-degree rotated gradient (jpeg cannot save signed char; must convert to unsigned char)</span>
<a class="code" href="g_i_l_0169.html#g3a185bccf9e6716693003db876b25dde" title="Saves the currently instantiated view to a jpeg file specified by the given jpeg...">jpeg_write_view</a>(<span class="stringliteral">"mandel.jpg"</span>,mandel);
<a class="code" href="g_i_l_0169.html#g3a185bccf9e6716693003db876b25dde" title="Saves the currently instantiated view to a jpeg file specified by the given jpeg...">jpeg_write_view</a>(<span class="stringliteral">"mandel_grad.jpg"</span>,color_converted_view&lt;gray8_pixel_t&gt;(<a class="code" href="g_i_l_0135.html#ged731349e60a30a3a241fd1809729996" title="Returns the constant-pixel view of an image.">const_view</a>(img)));
</pre></div><p>
Here is what the two files look like:<p>
<div align="center">
<img src="mandel.jpg" alt="mandel.jpg">
</div>
<h3><a class="anchor" name="DynamicImageSec">
Run-Time Specified Images and Image Views</a></h3>
So far we have created a generic function that computes the image gradient of a templated image view. Sometimes, however, the properties of an image view, such as its color space and channel depth, may not be available at compile time. GIL's <code>dynamic_image</code> extension allows for working with GIL constructs that are specified at run time, also called <em>variants</em>. GIL provides models of a run-time instantiated image, <code>any_image</code>, and a run-time instantiated image view, <code>any_image_view</code>. The mechanisms are in place to create other variants, such as <code>any_pixel</code>, <code>any_pixel_iterator</code>, etc. Most of GIL's algorithms and all of the view transformation functions also work with run-time instantiated image views and binary algorithms, such as <code>copy_pixels</code> can have either or both arguments be variants.<p>
Lets make our <code>x_luminosity_gradient</code> algorithm take a variant image view. For simplicity, let's assume that only the source view can be a variant. (As an example of using multiple variants, see GIL's image view algorithm overloads taking multiple variants.)<p>
First, we need to make a function object that contains the templated destination view and has an application operator taking a templated source view:<p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="g_i_l_0083.html" title="Includes all of the GIL dynamic image extension files, for convenience.">boost/gil/extension/dynamic_image/dynamic_image_all.hpp</a>&gt;</span>
<span class="keyword">template</span> &lt;<span class="keyword">typename</span> DstView&gt;
<span class="keyword">struct </span>x_gradient_obj {
<span class="keyword">typedef</span> <span class="keywordtype">void</span> result_type; <span class="comment">// required typedef</span>
<span class="keyword">const</span> DstView&amp; _dst;
x_gradient_obj(<span class="keyword">const</span> DstView&amp; dst) : _dst(dst) {}
<span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcView&gt;
<span class="keywordtype">void</span> operator()(<span class="keyword">const</span> SrcView&amp; src)<span class="keyword"> const </span>{ x_luminosity_gradient(src, _dst); }
};
</pre></div><p>
The second step is to provide an overload of <code>x_luminosity_gradient</code> that takes image view variant and calls GIL's <code>apply_operation</code> passing it the function object:<p>
<div class="fragment"><pre class="fragment"><span class="keyword">template</span> &lt;<span class="keyword">typename</span> SrcViews, <span class="keyword">typename</span> DstView&gt;
<span class="keywordtype">void</span> x_luminosity_gradient(<span class="keyword">const</span> any_image_view&lt;SrcViews&gt;&amp; src, <span class="keyword">const</span> DstView&amp; dst) {
<a class="code" href="group___variant.html#g3c8fd0f3dc2495060bf062428dccc505" title="Invokes a generic mutable operation (represented as a unary function object) on a...">apply_operation</a>(src, x_gradient_obj&lt;DstView&gt;(dst));
}
</pre></div><p>
<code>any_image_view&lt;SrcViews&gt;</code> is the image view variant. It is templated over <code>SrcViews</code>, an enumeration of all possible view types the variant can take. <code>src</code> contains inside an index of the currently instantiated type, as well as a block of memory containing the instance. <code>apply_operation</code> goes through a switch statement over the index, each case of which casts the memory to the correct view type and invokes the function object with it. Invoking an algorithm on a variant has the overhead of one switch statement. Algorithms that perform an operation for each pixel in an image view have practically no performance degradation when used with a variant.<p>
Here is how we can construct a variant and invoke the algorithm:<p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;boost/mpl/vector.hpp&gt;</span>
<span class="preprocessor">#include &lt;<a class="code" href="g_i_l_0232.html" title="Support for reading and writing JPEG files Requires libjpeg.">boost/gil/extension/io/jpeg_dynamic_io.hpp</a>&gt;</span>
<span class="keyword">typedef</span> mpl::vector&lt;gray8_image_t, gray16_image_t, rgb8_image_t, rgb16_image_t&gt; my_img_types;
any_image&lt;my_img_types&gt; runtime_image;
<a class="code" href="g_i_l_0169.html#ga8d0be11619e190cef13ab79d7169398" title="reads a JPEG image into a run-time instantiated image Opens the given JPEG file name...">jpeg_read_image</a>(<span class="stringliteral">"input.jpg"</span>, runtime_image);
gray8s_image_t gradient(runtime_image.dimensions());
x_luminosity_gradient(<a class="code" href="g_i_l_0135.html#ged731349e60a30a3a241fd1809729996" title="Returns the constant-pixel view of an image.">const_view</a>(runtime_image), <a class="code" href="g_i_l_0135.html#gad0335b7d343667d626556681486f198" title="Returns the non-constant-pixel view of an image.">view</a>(gradient));
<a class="code" href="g_i_l_0169.html#g3a185bccf9e6716693003db876b25dde" title="Saves the currently instantiated view to a jpeg file specified by the given jpeg...">jpeg_write_view</a>(<span class="stringliteral">"x_gradient.jpg"</span>, color_converted_view&lt;gray8_pixel_t&gt;(<a class="code" href="g_i_l_0135.html#ged731349e60a30a3a241fd1809729996" title="Returns the constant-pixel view of an image.">const_view</a>(gradient)));
</pre></div><p>
In this example, we create an image variant that could be 8-bit or 16-bit RGB or grayscale image. We then use GIL's I/O extension to load the image from file in its native color space and channel depth. If none of the allowed image types matches the image on disk, an exception will be thrown. We then construct a 8 bit signed (i.e. <code>char</code>) image to store the gradient and invoke <code>x_gradient</code> on it. Finally we save the result into another file. We save the view converted to 8-bit unsigned, because JPEG I/O does not support signed char.<p>
Note how free functions and methods such as <code>jpeg_read_image</code>, <code>dimensions</code>, <code>view</code> and <code>const_view</code> work on both templated and variant types. For templated images <code>view(img)</code> returns a templated view, whereas for image variants it returns a view variant. For example, the return type of <code>view(runtime_image)</code> is <code>any_image_view&lt;Views&gt;</code> where <code>Views</code> enumerates four views corresponding to the four image types. <code>const_view(runtime_image)</code> returns a <code>any_image_view</code> of the four read-only view types, etc.<p>
A warning about using variants: instantiating an algorithm with a variant effectively instantiates it with every possible type the variant can take. For binary algorithms, the algorithm is instantiated with every possible combination of the two input types! This can take a toll on both the compile time and the executable size.<h2><a class="anchor" name="ConclusionSec">
Conclusion</a></h2>
This tutorial provides a glimpse at the challenges associated with writing generic and efficient image processing algorithms in GIL. We have taken a simple algorithm and shown how to make it work with image representations that vary in bit depth, color space, ordering of the channels, and planar/interleaved structure. We have demonstrated that the algorithm can work with fully abstracted virtual images, and even images whose type is specified at run time. The associated video presentation also demonstrates that even for complex scenarios the generated assembly is comparable to that of a C version of the algorithm, hand-written for the specific image types.<p>
Yet, even for such a simple algorithm, we are far from making a fully generic and optimized code. In particular, the presented algorithms work on homogeneous images, i.e. images whose pixels have channels that are all of the same type. There are examples of images, such as a packed 565 RGB format, which contain channels of different types. While GIL provides concepts and algorithms operating on heterogeneous pixels, we leave the task of extending x_gradient as an exercise for the reader. Second, after computing the value of the gradient we are simply casting it to the destination channel type. This may not always be the desired operation. For example, if the source channel is a float with range [0..1] and the destination is unsigned char, casting the half-difference to unsigned char will result in either 0 or 1. Instead, what we might want to do is scale the result into the range of the destination channel. GIL's channel-level algorithms might be useful in such cases. For example, <code>channel_convert</code> converts between channels by linearly scaling the source channel value into the range of the destination channel.<p>
There is a lot to be done in improving the performance as well. Channel-level operations, such as the half-difference, could be abstracted out into atomic channel-level algorithms and performance overloads could be provided for concrete channel types. Processor-specific operations could be used, for example, to perform the operation over an entire row of pixels simultaneously, or the data could be prefetched. All of these optimizations can be realized as performance specializations of the generic algorithm. Finally, compilers, while getting better over time, are still failing to fully optimize generic code in some cases, such as failing to inline some functions or put some variables into registers. If performance is an issue, it might be worth trying your code with different compilers.<h2><a class="anchor" name="AppendixSec">
Appendix</a></h2>
<h3><a class="anchor" name="AppendixConventionSec">
Naming convention for GIL concrete types</a></h3>
Concrete (non-generic) GIL types follow this naming convention:<p>
<em>ColorSpace</em> + <em>BitDepth</em> + [<code>f</code> | <code>s</code>]+ [<code>c</code>] + [<code>_planar</code>] + [<code>_step</code>] + <em>ClassType</em> + <code>_t</code> <p>
Where <em>ColorSpace</em> also indicates the ordering of components. Examples are <code>rgb</code>, <code>bgr</code>, <code>cmyk</code>, <code>rgba</code>. <em>BitDepth</em> indicates the bit depth of the color channel. Examples are <code>8</code>,<code>16</code>,<code>32</code>. By default the type of channel is unsigned integral; using <code>s</code> indicates signed integral and <code>f</code> - a floating point type, which is always signed. <code>c</code> indicates object operating over immutable pixels. <code>_planar</code> indicates planar organization (as opposed to interleaved). <code>_step</code> indicates special image views, locators and iterators which traverse the data in non-trivial way (for example, backwards or every other pixel). <em>ClassType</em> is <code>_image</code> (image), <code>_view</code> (image view), <code>_loc</code> (pixel 2D locator) <code>_ptr</code> (pixel iterator), <code>_ref</code> (pixel reference), <code>_pixel</code> (pixel value).<p>
<div class="fragment"><pre class="fragment">bgr8_image_t a; <span class="comment">// 8-bit interleaved BGR image</span>
cmyk16_pixel_t; b; <span class="comment">// 16-bit CMYK pixel value;</span>
cmyk16c_planar_ref_t c(b); <span class="comment">// const reference to a 16-bit planar CMYK pixel x.</span>
rgb32f_planar_step_ptr_t d; <span class="comment">// step pointer to a 32-bit planar RGB pixel.</span>
</pre></div><p>
<div id="footerrow"></div><div id="footer" title="footer: links to copyright and other legal information"></div><p>
<div id="footer" title="footer: links to copyright and other legal information"><a href="licenses.html" class="el">Copyright &copy; 2005 Adobe Systems Incorporated</a><ul id="list1">
<li id="terms">
<a href="http://www.adobe.com/misc/copyright.html" title="Terms of Use">Terms of Use</a></li>
<li>
<a href="http://www.adobe.com/misc/privacy.html" title="Privacy Policy">Privacy Policy</a></li>
<li>
<a href="http://access.adobe.com">Accessibility</a></li>
<li>
<a href="http://www.adobe.com/aboutadobe/antipiracy/main.html" title="Avoid software piracy">Avoid software piracy</a></li>
<li id="tms">
<a href="http://www.adobe.com/misc/agreement.html" title="Permissions and trademarks">Permissions and trademarks</a></li>
<li>
<a href="http://www.adobe.com/products/eulas/main.html" title="Product License Agreements">Product License Agreements</a></li>
</ul>
</div> </div>
<hr size="1"><address style="text-align: right;"><small>Generated on Sat May 2 13:50:16 2009 for Generic Image Library by&nbsp;
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address>
</body>
</html>