/Src/Dependencies/Boost/libs/gil/doc/doxygen/tutorial.dox

http://hadesmem.googlecode.com/ · text · 768 lines · 596 code · 172 blank · 0 comment · 0 complexity · f22e211acff11be737d8470ce9cc5bdf MD5 · raw file

  1. ////////////////////////////////////////////////////////////////////////////////////////
  2. /// \file
  3. /// \brief Doxygen documentation
  4. /// \author Lubomir Bourdev and Hailin Jin \n
  5. /// Adobe Systems Incorporated
  6. ///
  7. ///
  8. ////////////////////////////////////////////////////////////////////////////////////////
  9. /**
  10. \page GILTutorial Generic Image Library Tutorial
  11. \author Lubomir Bourdev (lbourdev@adobe.com) and Hailin Jin (hljin@adobe.com) \n
  12. Adobe Systems Incorporated
  13. \version 2.1
  14. \date September 15, 2007
  15. The Generic Image Library (GIL) is a C++ library that abstracts image representations from algorithms and allows writing code that can work on
  16. a variety of images with performance similar to hand-writing for a specific image type.
  17. <p>This document will give you a jump-start in using GIL. It does not discuss the underlying design
  18. 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
  19. at http://stlab.adobe.com/gil
  20. - \ref InstallSec
  21. - \ref ExampleSec
  22. - \ref InterfaceSec
  23. - \ref FirstImplementationSec
  24. - \ref LocatorsSec
  25. - \ref GenericVersionSec
  26. - \ref ImageViewTransformationSec
  27. - \ref OneDIteratorsSec
  28. - \ref STLEquivalentsSec
  29. - \ref ColorConversionSec
  30. - \ref ImagesSec
  31. - \ref VirtualViewSec
  32. - \ref DynamicImageSec
  33. - \ref ConclusionSec
  34. - \ref AppendixSec
  35. - \ref AppendixConventionSec
  36. \section InstallSec Installation
  37. The latest version of GIL can be downloaded from GIL's web page, at http://stlab.adobe.com/gil.
  38. GIL is approved for integration into Boost and in the future will be installed simply by installing Boost from http://www.boost.org.
  39. GIL consists of header files only and does not require any libraries to link against. It does not require Boost to be built.
  40. Including \p boost/gil/gil_all.hpp will be sufficient for most projects.
  41. \section ExampleSec Example - Computing the Image Gradient
  42. This tutorial will walk through an example of using GIL to compute the image gradients.
  43. We will start with some very simple and non-generic code and make it more generic as we go along.
  44. Let us start with a horizontal gradient and use the simplest possible approximation to a gradient - central difference.
  45. The gradient at pixel x can be approximated with the half-difference of its two neighboring pixels:
  46. D[x] = (I[x-1] - I[x+1]) / 2
  47. 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.
  48. The focus of this document is how to use GIL, not how to create a good gradient generation algorithm.
  49. \subsection InterfaceSec Interface and Glue Code
  50. Let us first start with 8-bit unsigned grayscale image as the input and 8-bit signed grayscale image as the output.
  51. Here is how the interface to our algorithm looks like:
  52. \code
  53. #include <boost/gil/gil_all.hpp>
  54. using namespace boost::gil;
  55. void x_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  56. assert(src.dimensions() == dst.dimensions());
  57. ... // compute the gradient
  58. }
  59. \endcode
  60. \p gray8c_view_t is the type of the source image view - an 8-bit grayscale view, whose pixels are read-only (denoted by the \p "c"). The output
  61. is a grayscale view with a 8-bit signed (denoted by the \p "s") integer channel type. See Appendix 1 for the complete convension GIL uses to name concrete types.
  62. 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
  63. 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
  64. always be taken by a const reference. Whether a view is mutable or read-only (immutable) is a property of the view type.
  65. A GIL \e image, 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
  66. 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
  67. allow for modifying its pixels.
  68. 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 \p std::vector, whereas
  69. 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.
  70. 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
  71. the glue between your code and GIL:
  72. \code
  73. void ComputeXGradientGray8(const unsigned char* src_pixels, ptrdiff_t src_row_bytes, int w, int h,
  74. signed char* dst_pixels, ptrdiff_t dst_row_bytes) {
  75. gray8c_view_t src = interleaved_view(w, h, (const gray8_pixel_t*)src_pixels,src_row_bytes);
  76. gray8s_view_t dst = interleaved_view(w, h, ( gray8s_pixel_t*)dst_pixels,dst_row_bytes);
  77. x_gradient(src,dst);
  78. }
  79. \endcode
  80. 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,
  81. and number of bytes per row.
  82. \subsection FirstImplementationSec First Implementation
  83. Focusing on simplicity at the expense of speed, we can compute the horizontal gradient like this:
  84. \code
  85. void x_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  86. for (int y=0; y<src.height(); ++y)
  87. for (int x=1; x<src.width()-1; ++x)
  88. dst(x,y) = (src(x-1,y) - src(x+1,y)) / 2;
  89. }
  90. \endcode
  91. We use image view's \p operator(x,y) 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.
  92. operator() returns a reference to a grayscale pixel. A grayscale pixel is convertible to its channel type (<tt>unsigned char</tt> for \p src) and it can be copy-constructed from a channel.
  93. (This is only true for grayscale pixels).
  94. While the above code is easy to read, it is not very fast, because the binary \p operator() computes the location of the pixel in a 2D grid, which involves addition and multiplication. Here is
  95. a faster version of the above:
  96. \code
  97. void x_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  98. for (int y=0; y<src.height(); ++y) {
  99. gray8c_view_t::x_iterator src_it = src.row_begin(y);
  100. gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
  101. for (int x=1; x<src.width()-1; ++x)
  102. dst_it[x] = (src_it[x-1] - src_it[x+1]) / 2;
  103. }
  104. }
  105. \endcode
  106. 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
  107. were pointers. In fact, in the above example the two iterator types are raw C pointers and their \p operator[] is a fast pointer indexing operator.
  108. The code to compute gradient in the vertical direction is very similar:
  109. \code
  110. void y_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  111. for (int x=0; x<src.width(); ++x) {
  112. gray8c_view_t::y_iterator src_it = src.col_begin(x);
  113. gray8s_view_t::y_iterator dst_it = dst.col_begin(x);
  114. for (int y=1; y<src.height()-1; ++y)
  115. dst_it[y] = (src_it[y-1] - src_it[y+1])/2;
  116. }
  117. }
  118. \endcode
  119. Instead of looping over the rows, we loop over each column and create a \p y_iterator, an iterator moving vertically. In this case a simple pointer cannot be used because the distance
  120. 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.
  121. Its \p operator[] multiplies the index by its step.
  122. The above version of \p y_gradient, however, is much slower (easily an order of magnitude slower) than \p x_gradient because of the memory access pattern; traversing an image vertically
  123. results in lots of cache misses. A much more efficient and cache-friendly version will iterate over the columns in the inner loop:
  124. \code
  125. void y_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  126. for (int y=1; y<src.height()-1; ++y) {
  127. gray8c_view_t::x_iterator src1_it = src.row_begin(y-1);
  128. gray8c_view_t::x_iterator src2_it = src.row_begin(y+1);
  129. gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
  130. for (int x=0; x<src.width(); ++x) {
  131. *dst_it = ((*src1_it) - (*src2_it))/2;
  132. ++dst_it;
  133. ++src1_it;
  134. ++src2_it;
  135. }
  136. }
  137. }
  138. \endcode
  139. This sample code also shows an alternative way of using pixel iterators - instead of \p operator[] one could use increments and dereferences.
  140. \subsection LocatorsSec Using Locators
  141. Unfortunately this cache-friendly version requires the extra hassle of maintaining two separate iterators in the source view. For every pixel,
  142. we want to access its neighbors above and below it. Such relative access can be done with GIL locators:
  143. \code
  144. void y_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  145. gray8c_view_t::xy_locator src_loc = src.xy_at(0,1);
  146. for (int y=1; y<src.height()-1; ++y) {
  147. gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
  148. for (int x=0; x<src.width(); ++x) {
  149. (*dst_it) = (src_loc(0,-1) - src_loc(0,1)) / 2;
  150. ++dst_it;
  151. ++src_loc.x(); // each dimension can be advanced separately
  152. }
  153. src_loc+=point2<std::ptrdiff_t>(-src.width(),1); // carriage return
  154. }
  155. }
  156. \endcode
  157. 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,
  158. except that it can move both horizontally and vertically. \p src_loc.x() and \p src_loc.y() return references to a horizontal and a vertical iterator
  159. 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
  160. simultaneously using its \p operator+= and \p operator-=. Similar to image views, locators provide binary \p operator() which returns a reference to a pixel
  161. with a relative offset to the current locator position. For example, \p src_loc(0,1) returns a reference to the neighbor below the current pixel.
  162. 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
  163. indicating the number of bytes from one row to the next (which is the step when moving vertically). The call to \p ++src_loc.x() corresponds to a single C pointer increment.
  164. 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.
  165. 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:
  166. \code
  167. void y_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  168. gray8c_view_t::xy_locator src_loc = src.xy_at(0,1);
  169. gray8c_view_t::xy_locator::cached_location_t above = src_loc.cache_location(0,-1);
  170. gray8c_view_t::xy_locator::cached_location_t below = src_loc.cache_location(0, 1);
  171. for (int y=1; y<src.height()-1; ++y) {
  172. gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
  173. for (int x=0; x<src.width(); ++x) {
  174. (*dst_it) = (src_loc[above] - src_loc[below])/2;
  175. ++dst_it;
  176. ++src_loc.x();
  177. }
  178. src_loc+=point2<std::ptrdiff_t>(-src.width(),1);
  179. }
  180. }
  181. \endcode
  182. In this example \p "src_loc[above]" corresponds to a fast pointer indexing operation and the code is efficient.
  183. \subsection GenericVersionSec Creating a Generic Version of GIL Algorithms
  184. Let us make our \p x_gradient more generic. It should work with any image views, as long as they have the same number of channels.
  185. The gradient operation is to be computed for each channel independently. Here is how the new interface looks like:
  186. \code
  187. template <typename SrcView, typename DstView>
  188. void x_gradient(const SrcView& src, const DstView& dst) {
  189. gil_function_requires<ImageViewConcept<SrcView> >();
  190. gil_function_requires<MutableImageViewConcept<DstView> >();
  191. gil_function_requires<ColorSpacesCompatibleConcept<
  192. typename color_space_type<SrcView>::type,
  193. typename color_space_type<DstView>::type> >();
  194. ... // compute the gradient
  195. }
  196. \endcode
  197. The new algorithm now takes the types of the input and output image views as template parameters.
  198. That allows using both built-in GIL image views, as well as any user-defined image view classes.
  199. The first three lines are optional; they use \p boost::concept_check to ensure that the two arguments
  200. 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).
  201. 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.
  202. However, to work with the rest of GIL they have to satisfy a set of requirements; in other words, they have to \e model the corresponding GIL \e concept.
  203. GIL's concepts are defined in the user guide.
  204. One of the biggest drawbacks of using
  205. templates and generic programming in C++ is that compile errors can be very difficult to comprehend.
  206. This is a side-effect of the lack of early type checking - a generic argument may not satisfy the requirements of a function,
  207. but the incompatibility may be triggered deep into a nested call, in code unfamiliar and hardly related to the problem.
  208. GIL uses \p boost::concept_check to mitigate this problem. The above three lines of code check whether the
  209. template parameters are valid models of their corresponding concepts.
  210. If a model is incorrect, the compile error will be inside \p gil_function_requires, which is much closer to the problem
  211. and easier to track. Furthermore, such checks get compiled out and have zero performance overhead. The disadvantage of using
  212. concept checks is the sometimes severe impact they have on compile time. This is why GIL performs concept checks only in
  213. debug mode, and only if \p BOOST_GIL_USE_CONCEPT_CHECK is defined (off by default).
  214. 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
  215. channels of the pixel and compute the gradient for each channel:
  216. \code
  217. template <typename SrcView, typename DstView>
  218. void x_gradient(const SrcView& src, const DstView& dst) {
  219. for (int y=0; y<src.height(); ++y) {
  220. typename SrcView::x_iterator src_it = src.row_begin(y);
  221. typename DstView::x_iterator dst_it = dst.row_begin(y);
  222. for (int x=1; x<src.width()-1; ++x)
  223. for (int c=0; c<num_channels<SrcView>::value; ++c)
  224. dst_it[x][c] = (src_it[x-1][c]- src_it[x+1][c])/2;
  225. }
  226. }
  227. \endcode
  228. Having an explicit loop for each channel could be a performance problem. GIL allows us to abstract out such per-channel operations:
  229. \code
  230. template <typename Out>
  231. struct halfdiff_cast_channels {
  232. template <typename T> Out operator()(const T& in1, const T& in2) const {
  233. return Out((in1-in2)/2);
  234. }
  235. };
  236. template <typename SrcView, typename DstView>
  237. void x_gradient(const SrcView& src, const DstView& dst) {
  238. typedef typename channel_type<DstView>::type dst_channel_t;
  239. for (int y=0; y<src.height(); ++y) {
  240. typename SrcView::x_iterator src_it = src.row_begin(y);
  241. typename DstView::x_iterator dst_it = dst.row_begin(y);
  242. for (int x=1; x<src.width()-1; ++x)
  243. static_transform(src_it[x-1], src_it[x+1], dst_it[x],
  244. halfdiff_cast_channels<dst_channel_t>());
  245. }
  246. }
  247. \endcode
  248. \p static_transform is an example of a channel-level GIL algorithm. Other such algorithms are \p static_generate, \p static_fill and \p static_for_each. They are the channel-level equivalents
  249. of STL's \p generate, \p transform, \p fill and \p for_each respectively. GIL channel algorithms use static recursion to unroll the loops; they never loop over the channels explicitly.
  250. 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
  251. 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
  252. with a BGR destination.
  253. Here is how we can use our generic version with images of different types:
  254. \code
  255. // Calling with 16-bit grayscale data
  256. void XGradientGray16_Gray32(const unsigned short* src_pixels, ptrdiff_t src_row_bytes, int w, int h,
  257. signed int* dst_pixels, ptrdiff_t dst_row_bytes) {
  258. gray16c_view_t src=interleaved_view(w,h,(const gray16_pixel_t*)src_pixels,src_row_bytes);
  259. gray32s_view_t dst=interleaved_view(w,h,( gray32s_pixel_t*)dst_pixels,dst_row_bytes);
  260. x_gradient(src,dst);
  261. }
  262. // Calling with 8-bit RGB data into 16-bit BGR
  263. void XGradientRGB8_BGR16(const unsigned char* src_pixels, ptrdiff_t src_row_bytes, int w, int h,
  264. signed short* dst_pixels, ptrdiff_t dst_row_bytes) {
  265. rgb8c_view_t src = interleaved_view(w,h,(const rgb8_pixel_t*)src_pixels,src_row_bytes);
  266. rgb16s_view_t dst = interleaved_view(w,h,( rgb16s_pixel_t*)dst_pixels,dst_row_bytes);
  267. x_gradient(src,dst);
  268. }
  269. // Either or both the source and the destination could be planar - the gradient code does not change
  270. void XGradientPlanarRGB8_RGB32(
  271. const unsigned short* src_r, const unsigned short* src_g, const unsigned short* src_b,
  272. ptrdiff_t src_row_bytes, int w, int h,
  273. signed int* dst_pixels, ptrdiff_t dst_row_bytes) {
  274. rgb16c_planar_view_t src=planar_rgb_view (w,h, src_r,src_g,src_b, src_row_bytes);
  275. rgb32s_view_t dst=interleaved_view(w,h,(rgb32s_pixel_t*)dst_pixels,dst_row_bytes);
  276. x_gradient(src,dst);
  277. }
  278. \endcode
  279. As these examples illustrate, both the source and the destination can be interleaved or planar, of any channel depth (assuming the destination channel is
  280. assignable to the source), and of any compatible color spaces.
  281. 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.
  282. GIL algorithms apply to these images natively. See the design guide or sample files for more on using such images.
  283. \subsection ImageViewTransformationSec Image View Transformations
  284. 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:
  285. \code
  286. template <typename SrcView, typename DstView>
  287. void y_gradient(const SrcView& src, const DstView& dst) {
  288. x_gradient(rotated90ccw_view(src), rotated90ccw_view(dst));
  289. }
  290. \endcode
  291. \p rotated90ccw_view 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
  292. a variety of transformation functions that can perform any axis-aligned rotation, transpose the view, flip it vertically or horizontally, extract a rectangular subimage,
  293. 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
  294. accessing the pixels. \p rotated90cw_view, for example, returns a view whose horizontal iterators are the vertical iterators of the original view. The above code to compute \p y_gradient
  295. is slow because of the memory access pattern; using \p rotated90cw_view does not make it any slower.
  296. Another example: suppose we want to compute the gradient of the N-th channel of a color image. Here is how to do that:
  297. \code
  298. template <typename SrcView, typename DstView>
  299. void nth_channel_x_gradient(const SrcView& src, int n, const DstView& dst) {
  300. x_gradient(nth_channel_view(src, n), dst);
  301. }
  302. \endcode
  303. \p nth_channel_view is a view transformation function that takes any view and returns a single-channel (grayscale) view of its N-th channel.
  304. For interleaved RGB view, for example, the returned view is a step view - a view whose horizontal iterator skips over two channels when incremented.
  305. If applied on a planar RGB view, the returned type is a simple grayscale view whose horizontal iterator is a C pointer.
  306. 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:
  307. \code
  308. y_gradient(subsampled_view(nth_channel_view(src, 1), 2,2), dst);
  309. \endcode
  310. 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
  311. is the product of the steps of the two views.
  312. \subsection OneDIteratorsSec 1D pixel iterators
  313. Let's go back to \p x_gradient one more time.
  314. 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
  315. 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
  316. apply it only on the subimage that excludes the first and last column:
  317. \code
  318. void x_gradient_unguarded(const gray8c_view_t& src, const gray8s_view_t& dst) {
  319. for (int y=0; y<src.height(); ++y) {
  320. gray8c_view_t::x_iterator src_it = src.row_begin(y);
  321. gray8s_view_t::x_iterator dst_it = dst.row_begin(y);
  322. for (int x=0; x<src.width(); ++x)
  323. dst_it[x] = (src_it[x-1] - src_it[x+1]) / 2;
  324. }
  325. }
  326. void x_gradient(const gray8c_view_t& src, const gray8s_view_t& dst) {
  327. assert(src.width()>=2);
  328. x_gradient_unguarded(subimage_view(src, 1, 0, src.width()-2, src.height()),
  329. subimage_view(dst, 1, 0, src.width()-2, src.height()));
  330. }
  331. \endcode
  332. \p subimage_view 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
  333. 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.
  334. Now that \p x_gradient_unguarded operates on every pixel, we can rewrite it more compactly:
  335. \code
  336. void x_gradient_unguarded(const gray8c_view_t& src, const gray8s_view_t& dst) {
  337. gray8c_view_t::iterator src_it = src.begin();
  338. for (gray8s_view_t::iterator dst_it = dst.begin(); dst_it!=dst.end(); ++dst_it, ++src_it)
  339. *dst_it = (src_it.x()[-1] - src_it.x()[1]) / 2;
  340. }
  341. \endcode
  342. GIL image views provide \p begin() and \p end() methods that return one dimensional pixel iterators which iterate over each pixel in the view,
  343. 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
  344. 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
  345. nested loops are used instead. These iterators have a method \p x() which returns the more lightweight horizontal iterator that we used previously. Horizontal iterators have no
  346. 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
  347. could reside outside the image view.
  348. \subsection STLEquivalentsSec STL Equivalent Algorithms
  349. GIL provides STL equivalents of many algorithms. For example, \p std::transform is an STL algorithm that sets each element in a destination range the result of a generic function taking the
  350. 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.
  351. If we abstract that operation in a function object, we can use GIL's \p transform_pixel_positions to do that:
  352. \code
  353. struct half_x_difference {
  354. int operator()(const gray8c_loc_t& src_loc) const {
  355. return (src_loc.x()[-1] - src_loc.x()[1]) / 2;
  356. }
  357. };
  358. void x_gradient_unguarded(const gray8c_view_t& src, const gray8s_view_t& dst) {
  359. transform_pixel_positions(src, dst, half_x_difference());
  360. }
  361. \endcode
  362. GIL provides the algorithms \p for_each_pixel and \p transform_pixels which are image view equivalents of STL's \p std::for_each and \p std::transform. It also provides
  363. \p for_each_pixel_position and \p transform_pixel_positions, which instead of references to pixels, pass to the generic function pixel locators. This allows for more powerful functions
  364. that can use the pixel neighbors through the passed locators.
  365. GIL algorithms iterate through the pixels using the more efficient two nested loops (as opposed to the single loop using 1-D iterators)
  366. \subsection ColorConversionSec Color Conversion
  367. 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
  368. 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:
  369. \code
  370. void x_gradient_rgb_luminosity(const rgb32fc_view_t& src, const gray8s_view_t& dst) {
  371. x_gradient(color_converted_view<gray8_pixel_t>(src), dst);
  372. }
  373. \endcode
  374. \p color_converted_view is a GIL view transformation function that takes any image view and returns a view in a target color space and channel depth (specified
  375. 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, \p color_converted_view is very
  376. 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.
  377. 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
  378. type of a GIL grayscale pixel with the same channel as the source, and color convert to that pixel type:
  379. \code
  380. template <typename SrcView, typename DstView>
  381. void x_luminosity_gradient(const SrcView& src, const DstView& dst) {
  382. typedef pixel<typename channel_type<SrcView>::type, gray_layout_t> gray_pixel_t;
  383. x_gradient(color_converted_view<gray_pixel_t>(src), dst);
  384. }
  385. \endcode
  386. 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
  387. code at all - i.e. \p color_converted_view returns back the source view unchanged.
  388. \subsection ImagesSec Image
  389. The above example has a performance problem - \p x_gradient dereferences most source pixels twice, which will cause the above code to perform color conversion twice.
  390. 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.
  391. Using our non-generic version we can do it like this:
  392. \code
  393. void x_luminosity_gradient(const rgb32fc_view_t& src, const gray8s_view_t& dst) {
  394. gray8_image_t ccv_image(src.dimensions());
  395. copy_pixels(color_converted_view<gray8_pixel_t>(src), view(ccv_image));
  396. x_gradient(const_view(ccv_image), dst);
  397. }
  398. \endcode
  399. 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.
  400. Finally we use a read-only view of the temporary image in our \p x_gradient algorithm. As the example shows, GIL provides global functions \p view and \p const_view
  401. that take an image and return a mutable or an immutable view of its pixels.
  402. Creating a generic version of the above is a bit trickier:
  403. \code
  404. template <typename SrcView, typename DstView>
  405. void x_luminosity_gradient(const SrcView& src, const DstView& dst) {
  406. typedef typename channel_type<DstView>::type d_channel_t;
  407. typedef typename channel_convert_to_unsigned<d_channel_t>::type channel_t;
  408. typedef pixel<channel_t, gray_layout_t> gray_pixel_t;
  409. typedef image<gray_pixel_t, false> gray_image_t;
  410. gray_image_t ccv_image(src.dimensions());
  411. copy_pixels(color_converted_view<gray_pixel_t>(src), view(ccv_image));
  412. x_gradient(const_view(ccv_image), dst);
  413. }
  414. \endcode
  415. First we use the \p channel_type metafunction to get the channel type of the destination view. A metafunction is a function operating on types. In GIL metafunctions
  416. are structs which take their parameters as template parameters and return their result in a nested typedef called \p type. In this case, \p channel_type is
  417. 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.
  418. GIL constructs that have an associated pixel type, such as pixels, pixel iterators, locators, views and images, all model \p PixelBasedConcept, which means
  419. that they provide a set of metafunctions to query the pixel properties, such as \p channel_type, \p color_space_type, \p channel_mapping_type, and \p num_channels.
  420. 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
  421. 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
  422. indicating whether the image should be planar or interleaved.
  423. Single-channel (grayscale) images in GIL must always be interleaved. There are multiple ways of constructing types in GIL. Instead of instantiating the classes
  424. directly we could have used type factory metafunctions. The following code is equivalent:
  425. \code
  426. template <typename SrcView, typename DstView>
  427. void x_luminosity_gradient(const SrcView& src, const DstView& dst) {
  428. typedef typename channel_type<DstView>::type d_channel_t;
  429. typedef typename channel_convert_to_unsigned<d_channel_t>::type channel_t;
  430. typedef typename image_type<channel_t, gray_layout_t>::type gray_image_t;
  431. typedef typename gray_image_t::value_type gray_pixel_t;
  432. gray_image_t ccv_image(src.dimensions());
  433. copy_and_convert_pixels(src, view(ccv_image));
  434. x_gradient(const_view(ccv_image), dst);
  435. }
  436. \endcode
  437. GIL provides a set of metafunctions that generate GIL types - \p image_type is one such meta-function that constructs the type of an image from
  438. a given channel type, color layout, and planar/interleaved option (the default is interleaved). There are also similar meta-functions to
  439. construct the types of pixel references, iterators, locators and image views. GIL also has metafunctions \p derived_pixel_reference_type, \p derived_iterator_type,
  440. \p derived_view_type and \p derived_image_type that construct the type of a GIL construct from a given source one by changing one or more properties of
  441. the type and keeping the rest.
  442. From the image type we can use the nested typedef \p value_type to obtain the type of a pixel. GIL images, image views and locators have nested typedefs
  443. \p value_type and \p reference 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
  444. \p iterator_traits. Note also the algorithm \p copy_and_convert_pixels, which is an abbreviated version of \p copy_pixels with a color converted source view.
  445. \subsection VirtualViewSec Virtual Image Views
  446. 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
  447. a synthetic function. To demonstrate this, let us create a view of the Mandelbrot set.
  448. 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:
  449. \code
  450. // models PixelDereferenceAdaptorConcept
  451. struct mandelbrot_fn {
  452. typedef point2<ptrdiff_t> point_t;
  453. typedef mandelbrot_fn const_t;
  454. typedef gray8_pixel_t value_type;
  455. typedef value_type reference;
  456. typedef value_type const_reference;
  457. typedef point_t argument_type;
  458. typedef reference result_type;
  459. BOOST_STATIC_CONSTANT(bool, is_mutable=false);
  460. mandelbrot_fn() {}
  461. mandelbrot_fn(const point_t& sz) : _img_size(sz) {}
  462. result_type operator()(const point_t& p) const {
  463. // normalize the coords to (-2..1, -1.5..1.5)
  464. double t=get_num_iter(point2<double>(p.x/(double)_img_size.x*3-2, p.y/(double)_img_size.y*3-1.5f));
  465. return value_type((bits8)(pow(t,0.2)*255)); // raise to power suitable for viewing
  466. }
  467. private:
  468. point_t _img_size;
  469. double get_num_iter(const point2<double>& p) const {
  470. point2<double> Z(0,0);
  471. for (int i=0; i<100; ++i) { // 100 iterations
  472. Z = point2<double>(Z.x*Z.x - Z.y*Z.y + p.x, 2*Z.x*Z.y + p.y);
  473. if (Z.x*Z.x + Z.y*Z.y > 4)
  474. return i/(double)100;
  475. }
  476. return 0;
  477. }
  478. };
  479. \endcode
  480. We can now use GIL's \p virtual_2d_locator with this function object to construct a Mandelbrot view of size 200x200 pixels:
  481. \code
  482. typedef mandelbrot_fn::point_t point_t;
  483. typedef virtual_2d_locator<mandelbrot_fn,false> locator_t;
  484. typedef image_view<locator_t> my_virt_view_t;
  485. point_t dims(200,200);
  486. // Construct a Mandelbrot view with a locator, taking top-left corner (0,0) and step (1,1)
  487. my_virt_view_t mandel(dims, locator_t(point_t(0,0), point_t(1,1), mandelbrot_fn(dims)));
  488. \endcode
  489. We can treat the synthetic view just like a real one. For example, let's invoke our \p x_gradient algorithm to compute
  490. the gradient of the 90-degree rotated view of the Mandelbrot set and save the original and the result:
  491. \code
  492. gray8s_image_t img(dims);
  493. x_gradient(rotated90cw_view(mandel), view(img));
  494. // Save the Mandelbrot set and its 90-degree rotated gradient (jpeg cannot save signed char; must convert to unsigned char)
  495. jpeg_write_view("mandel.jpg",mandel);
  496. jpeg_write_view("mandel_grad.jpg",color_converted_view<gray8_pixel_t>(const_view(img)));
  497. \endcode
  498. Here is what the two files look like:
  499. \image html mandel.jpg
  500. \subsection DynamicImageSec Run-Time Specified Images and Image Views
  501. So far we have created a generic function that computes the image gradient of a templated image view.
  502. Sometimes, however, the properties of an image view, such as its color space and channel depth, may not be available at compile time.
  503. GIL's \p dynamic_image extension allows for working with GIL constructs that are specified at run time, also called \e variants. GIL provides
  504. models of a run-time instantiated image, \p any_image, and a run-time instantiated image view, \p any_image_view. The mechanisms are in place to create
  505. other variants, such as \p any_pixel, \p any_pixel_iterator, etc.
  506. Most of GIL's algorithms and all of the view transformation functions also work with run-time instantiated image views and binary algorithms, such
  507. as \p copy_pixels can have either or both arguments be variants.
  508. Lets make our \p x_luminosity_gradient algorithm take a variant image view. For simplicity, let's assume that only the source view can be a variant.
  509. (As an example of using multiple variants, see GIL's image view algorithm overloads taking multiple variants.)
  510. First, we need to make a function object that contains the templated destination view and has an application operator taking a templated source view:
  511. \code
  512. #include <boost/gil/extension/dynamic_image/dynamic_image_all.hpp>
  513. template <typename DstView>
  514. struct x_gradient_obj {
  515. typedef void result_type; // required typedef
  516. const DstView& _dst;
  517. x_gradient_obj(const DstView& dst) : _dst(dst) {}
  518. template <typename SrcView>
  519. void operator()(const SrcView& src) const { x_luminosity_gradient(src, _dst); }
  520. };
  521. \endcode
  522. The second step is to provide an overload of \p x_luminosity_gradient that takes image view variant and calls GIL's \p apply_operation
  523. passing it the function object:
  524. \code
  525. template <typename SrcViews, typename DstView>
  526. void x_luminosity_gradient(const any_image_view<SrcViews>& src, const DstView& dst) {
  527. apply_operation(src, x_gradient_obj<DstView>(dst));
  528. }
  529. \endcode
  530. \p any_image_view<SrcViews> is the image view variant. It is templated over \p SrcViews, an enumeration of all possible view types the variant can take.
  531. \p src contains inside an index of the currently instantiated type, as well as a block of memory containing the instance.
  532. \p apply_operation goes through a switch statement over the index, each case of which casts the memory to the correct view type and invokes the
  533. function object with it. Invoking an algorithm on a variant has the overhead of one switch statement. Algorithms that perform an operation for
  534. each pixel in an image view have practically no performance degradation when used with a variant.
  535. Here is how we can construct a variant and invoke the algorithm:
  536. \code
  537. #include <boost/mpl/vector.hpp>
  538. #include <boost/gil/extension/io/jpeg_dynamic_io.hpp>
  539. typedef mpl::vector<gray8_image_t, gray16_image_t, rgb8_image_t, rgb16_image_t> my_img_types;
  540. any_image<my_img_types> runtime_image;
  541. jpeg_read_image("input.jpg", runtime_image);
  542. gray8s_image_t gradient(runtime_image.dimensions());
  543. x_luminosity_gradient(const_view(runtime_image), view(gradient));
  544. jpeg_write_view("x_gradient.jpg", color_converted_view<gray8_pixel_t>(const_view(gradient)));
  545. \endcode
  546. 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
  547. 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.
  548. We then construct a 8 bit signed (i.e. \p char) image to store the gradient and invoke \p x_gradient on it. Finally we save the result into another file.
  549. We save the view converted to 8-bit unsigned, because JPEG I/O does not support signed char.
  550. Note how free functions and methods such as \p jpeg_read_image, \p dimensions, \p view and \p const_view work on both templated and variant types.
  551. For templated images \p view(img) returns a templated view, whereas for image variants it returns a view variant.
  552. For example, the return type of \p view(runtime_image) is \p any_image_view<Views> where \p Views enumerates four views corresponding to the four image types.
  553. \p const_view(runtime_image) returns a \p any_image_view of the four read-only view types, etc.
  554. A warning about using variants: instantiating an algorithm with a variant effectively instantiates it with every possible type the variant can take.
  555. 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
  556. and the executable size.
  557. \section ConclusionSec Conclusion
  558. This tutorial provides a glimpse at the challenges associated with writing generic and efficient image processing algorithms in GIL.
  559. 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
  560. channels, and planar/interleaved structure. We have demonstrated that the algorithm can work with fully abstracted virtual images, and even images
  561. whose type is specified at run time. The associated video presentation also demonstrates that even for complex scenarios the generated assembly
  562. is comparable to that of a C version of the algorithm, hand-written for the specific image types.
  563. 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
  564. 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
  565. channels of different types. While GIL provides concepts and algorithms operating on heterogeneous pixels, we leave the task of extending x_gradient as an
  566. exercise for the reader.
  567. 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
  568. 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
  569. 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
  570. in such cases. For example, \p channel_convert converts between channels by linearly scaling the source channel value into the range of the destination channel.
  571. 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
  572. channel-level algorithms and performance overloads could be provided for concrete channel types. Processor-specific operations could be used, for example,
  573. 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
  574. specializations of the generic algorithm. Finally, compilers, while getting better over time, are still failing to fully optimize generic code in some cases, such
  575. 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.
  576. \section AppendixSec Appendix
  577. \subsection AppendixConventionSec Naming convention for GIL concrete types
  578. Concrete (non-generic) GIL types follow this naming convention:
  579. <p>
  580. \e ColorSpace + \e BitDepth + [\p f | \p s]+ [\p c] + [\p _planar] + [\p _step] + \e ClassType + \p _t
  581. <p>
  582. Where \e ColorSpace also indicates the ordering of components. Examples are \p rgb, \p bgr, \p cmyk, \p rgba.
  583. \e BitDepth indicates the bit depth of the color channel. Examples are \p 8,\p 16,\p 32. By default the type of channel is unsigned integral; using \p s indicates
  584. signed integral and \p f - a floating point type, which is always signed. \p c indicates object operating over immutable pixels. \p _planar indicates planar organization
  585. (as opposed to interleaved). \p _step indicates special image views,
  586. locators and iterators which traverse the data in non-trivial way (for example, backwards or every other pixel).
  587. \e ClassType is \p _image (image), \p _view (image view), \p _loc (pixel 2D locator) \p _ptr (pixel iterator), \p _ref (pixel reference),
  588. \p _pixel (pixel value).
  589. \code
  590. bgr8_image_t a; // 8-bit interleaved BGR image
  591. cmyk16_pixel_t; b; // 16-bit CMYK pixel value;
  592. cmyk16c_planar_ref_t c(b); // const reference to a 16-bit planar CMYK pixel x.
  593. rgb32f_planar_step_ptr_t d; // step pointer to a 32-bit planar RGB pixel.
  594. \endcode
  595. <div id="footerrow"><!--give footer 25px of white above--></div><div id="footer" title="footer: links to copyright and other legal information"><p><a href="licenses.html" class="el">Copyright &copy; 2005 Adobe Systems Incorporated</a></p><ul id="list1"><!-- due to a rendering error in IE, these links should all be on one line without returns --><li id="terms"><a title="Terms of Use" href="http://www.adobe.com/misc/copyright.html">Terms of Use</a></li><li><a title="Privacy Policy" href="http://www.adobe.com/misc/privacy.html">Privacy Policy</a></li><li><a href="http://access.adobe.com">Accessibility</a></li><li><a title="Avoid software piracy" href="http://www.adobe.com/aboutadobe/antipiracy/main.html">Avoid software piracy</a></li><li id="tms"><a title="Permissions and trademarks" href="http://www.adobe.com/misc/agreement.html">Permissions and trademarks</a></li><li><a title="Product License Agreements" href="http://www.adobe.com/products/eulas/main.html">Product License Agreements</a></li></ul></div>
  596. */