ImageProcessing.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <!DOCTYPE html> <HTML lang=en> <HEAD> <STYLE>
  2. body { background-color: #EEFFEE; font-size: 1.0rem; font-family: Arial; max-width: 60rem;
  3. color: #000000; margin: 0px;
  4. padding-left: 0px; padding-right: 0px; padding-top: 0px; padding-bottom: 0px; }
  5. H1 { padding-left: 10px; padding-right: 0px; padding-top: 10px; padding-bottom: 10px; font-size: 1.4rem; }
  6. H2 { padding-left: 10px; padding-right: 0px; padding-top: 10px; padding-bottom: 0px; font-size: 1.2rem; }
  7. blockquote {
  8. tab-size: 3rem;
  9. color: #88FF88; background: #000000;
  10. font-size: 0.95rem; font-family: monospace;
  11. padding-left: 5px; padding-right: 5px;
  12. padding-top: 5px; padding-bottom: 5px;
  13. }
  14. P { padding-left: 20px; padding-right: 0px; padding-top: 0px; padding-bottom: 0px; }
  15. IMG { padding-left: 0px; padding-right: 0px; padding-top: 2px; padding-bottom: 0px;
  16. max-width: 100%; }
  17. A { display: inline; border-radius: 4px;
  18. font-size: 1.0rem; font-family: Arial; color: #000044; text-decoration: none;
  19. padding-left: 4px; padding-right: 4px; padding-top: 4px; padding-bottom: 4px; }
  20. A:hover { color: #FFFF00; background: #000044; }
  21. A:active { color: #FFFFFF; background: #444444; }
  22. </STYLE> </HEAD> <BODY>
  23. <IMG SRC="Images/Title.png" ALT="Images/Title.png">
  24. <P>
  25. <A href="Manual.html">Back to main page</A>
  26. </P><P>
  27. </P><H1> Image processing</H1><P>When creating your own image filter, you should begin by creating a reference implementation.
  28. This allow experimenting with different math formulas and effects without having to worry about optimization and crashes.
  29. </P><P>
  30. Then create a pixel loop where you have more control and can start to apply SIMD.
  31. </P><P>
  32. If the filters take a long time to execute, multi-threading might be useful depending on how it is implemented.
  33. With lower resolutions or trivial operations, SIMD is so fast that a single thread is complete before a second thread had the time to start.
  34. </P><P>
  35. See <B>Source/test/tests/ImageProcessingTest.cpp</B> for a an executable version of these example functions called from <B>Source/test.sh</B>.
  36. </P><P>
  37. See <B>Source/SDK/SpriteEngine/lightAPI.cpp</B> for a real use of multi-threading with threadedSplit.
  38. </P><P>
  39. </P><IMG SRC="Images/Border.png"><P>
  40. </P><P>
  41. </P><H2> Read pixel functions (slow but safe)</H2><P>
  42. </P><P>
  43. Both basic pixel loops and lambdas may find this way of reading pixel data useful for prototyping.
  44. </P><P>
  45. <B>Source/DFPSR/api/imageAPI.h</B> contains image_readPixel_border, which allow specifying a uniform color for out of bound reads.
  46. </P><P>
  47. <B>Source/DFPSR/api/imageAPI.h</B> contains image_readPixel_clamp, which reads the closest valid pixel.
  48. </P><P>
  49. <B>Source/DFPSR/api/imageAPI.h</B> contains image_readPixel_tile, which loops the image like a repeated tile to fill the space.
  50. </P><P>
  51. All these sampling methods will safely return zero if the image handle contains null.
  52. </P><P>
  53. </P><IMG SRC="Images/Border.png"><P>
  54. </P><P>
  55. </P><H2> Write pixel functions (slow but safe)</H2><P>
  56. </P><P>
  57. Only for prototyping with own pixel loops.
  58. </P><P>
  59. <B>Source/DFPSR/api/imageAPI.h</B> contains image_writePixel, which allow writing pixel data only when the given x, y coordinate is inside of an image that exists.
  60. </P><P>
  61. </P><IMG SRC="Images/Border.png"><P>
  62. </P><P>
  63. </P><H2> Map functions (slow but safe)</H2><P>
  64. </P><P>
  65. <B>Source/DFPSR/api/filterAPI.h</B> contains filter_mapRgbaU8, filter_mapU8, et cetera...
  66. </P><P>
  67. Useful for prototyping something that later will become an optimized in-place image filter.
  68. The map functions simply call your lambda function for each pixel in the image and gives the x, y coordinate as arguments.
  69. If you enter startX and startY offsets, these will be uniformly added to the x, y coordinates entering your function, which is useful for panorating a view or partial updates of blocks.
  70. Input images and other resources can be captured by the lambda.
  71. The returned result is automatically saturated to the resulting color type and written without any need for bound checks.
  72. </P><P>
  73. Adding two grayscale images using <B>filter_mapU8</B>:
  74. <PRE><BLOCKQUOTE>void addImages_map(ImageU8 targetImage, ImageU8 imageA, ImageU8 imageB) {
  75. // Call your lambda for each pixel in targetImage
  76. filter_mapU8(targetImage,
  77. [imageA, imageB](int x, int y) {
  78. int lumaA = image_readPixel_clamp(imageA, x, y);
  79. int lumaB = image_readPixel_clamp(imageB, x, y);
  80. return lumaA + lumaB;
  81. }
  82. );
  83. }
  84. </BLOCKQUOTE></PRE>
  85. </P><P>
  86. </P><IMG SRC="Images/Border.png"><P>
  87. </P><P>
  88. </P><H2> Generate functions (slow but safe)</H2><P>
  89. </P><P>
  90. <B>Source/DFPSR/api/filterAPI.h</B> also contains filter_generateRgbaU8, filter_generateU8, et cetera...
  91. </P><P>
  92. Useful for generating images when starting the application where executing once is not making a notable difference.
  93. Allocates a new image of the specified dimensions before evaluating the lambda function on each pixel.
  94. Same performance as allocating an image yourself and then calling the map function.
  95. </P><P>
  96. When taking inputs, try to allow unaligned images if you don't plan to use it for SIMD later.
  97. When returning a result that was just created and not a sub-image let it be aligned or even ordered to describe it as closely as possible.
  98. </P><P>
  99. Adding two grayscale images using <B>filter_generateU8</B>:
  100. <PRE><BLOCKQUOTE>AlignedImageU8 addImages_generate(ImageU8 imageA, ImageU8 imageB) {
  101. int width = image_getWidth(imageA);
  102. int height = image_getHeight(imageA);
  103. // Call your lambda for width times height pixels
  104. return filter_generateU8(width, height,
  105. [imageA, imageB](int x, int y) {
  106. int lumaA = image_readPixel_clamp(imageA, x, y);
  107. int lumaB = image_readPixel_clamp(imageB, x, y);
  108. return lumaA + lumaB;
  109. }
  110. );
  111. }
  112. </BLOCKQUOTE></PRE>
  113. </P><P>
  114. </P><IMG SRC="Images/Border.png"><P>
  115. </P><P>
  116. </P><H2> Loops with image_writePixel (slow but safe)</H2><P>When beginning to optimize, make your own pixel loop using x and y integers.
  117. </P><P>
  118. Because pixels on the same row are packed together in memory, you should try to read the pixels of different x coordinates before moving to the next row along y.
  119. Otherwise the memory will be read in an order that is hard to predict when reading memory into data cache.
  120. </P><P>
  121. Storing the dimensions before the loop prevents calling non-inlined functions inside the loop.
  122. Calling functions that can not be inlined inside of a loop would be very bad for performance by clearing the CPU's execution window with each call.
  123. </P><P>
  124. Writing the result using image_writePixel will automatically saturate to fit into 8 bits.
  125. </P><P>
  126. Adding two grayscale images using <B>image_writePixel</B>:
  127. <PRE><BLOCKQUOTE>void addImages_loop(ImageU8 targetImage, ImageU8 imageA, ImageU8 imageB) {
  128. int width = image_getWidth(targetImage);
  129. int height = image_getHeight(targetImage);
  130. // Loop over all x, y coordinates yourself
  131. for (int y = 0; y &lt; height; y++) {
  132. for (int x = 0; x &lt; width; x++) {
  133. int lumaA = image_readPixel_clamp(imageA, x, y);
  134. int lumaB = image_readPixel_clamp(imageB, x, y);
  135. image_writePixel(targetImage, x, y, lumaA + lumaB);
  136. }
  137. }
  138. }
  139. </BLOCKQUOTE></PRE>
  140. </P><P>
  141. </P><IMG SRC="Images/Border.png"><P>
  142. </P><P>
  143. </P><H2> Loops with safe pointers (fast in release and safe in debug)</H2><P>
  144. </P><P>
  145. Use safe pointers instead of raw pointers when you need better error messages with tighter memory bounds in debug mode, but can not afford any performance penalty in release mode.
  146. </P><P>
  147. Safe pointers may only be used within the lifetime of the resource, because the safe pointer does not affect any reference counting for the allocation.
  148. </P><P>
  149. Saturation of the result can be done using an atomic if statement containing a basic assignment, which will be optimized into a conditional move instruction taking a single cycle on most CPU architectures.
  150. Because we are adding two unsigned images, we do not have to clamp any negative values to zero and only need to clamp values larger than the largest unsigned 8-bit integer (255).
  151. </P><P>
  152. Adding two grayscale images using <B>SafePointer<uint8_t></B>:
  153. <PRE><BLOCKQUOTE>void addImages_pointer(ImageU8 targetImage, ImageU8 imageA, ImageU8 imageB) {
  154. int width = image_getWidth(targetImage);
  155. int height = image_getHeight(targetImage);
  156. SafePointer&lt;uint8_t&gt; targetRow = image_getSafePointer(targetImage);
  157. SafePointer&lt;uint8_t&gt; rowA = image_getSafePointer(imageA);
  158. SafePointer&lt;uint8_t&gt; rowB = image_getSafePointer(imageB);
  159. int targetStride = image_getStride(targetImage);
  160. int strideA = image_getStride(imageA);
  161. int strideB = image_getStride(imageB);
  162. for (int y = 0; y &lt; height; y++) {
  163. SafePointer&lt;uint8_t&gt; targetPixel = targetRow;
  164. SafePointer&lt;uint8_t&gt; pixelA = rowA;
  165. SafePointer&lt;uint8_t&gt; pixelB = rowB;
  166. for (int x = 0; x &lt; width; x++) {
  167. // Read both source pixels and add them
  168. int result = *pixelA + *pixelB;
  169. // Clamp overflow
  170. if (result &gt; 255) result = 255;
  171. // Can skip underflow check
  172. //if (result &lt; 0) result = 0;
  173. // Write the result
  174. *targetPixel = result;
  175. // Move pixel pointers to the next pixel
  176. targetPixel += 1;
  177. pixelA += 1;
  178. pixelB += 1;
  179. }
  180. // Move row pointers to the next row
  181. targetRow.increaseBytes(targetStride);
  182. rowA.increaseBytes(strideA);
  183. rowB.increaseBytes(strideB);
  184. }
  185. }
  186. </BLOCKQUOTE></PRE>
  187. </P><P>
  188. </P><IMG SRC="Images/Border.png"><P>
  189. </P><P>
  190. </P><H2> Loops with SIMD vectorization (very fast in release and safe in debug)</H2><P>
  191. </P><P>
  192. <B>Source/DFPSR/base/simd.h</B> contains F32x4, a SIMD vector storing 4 32-bit floats.
  193. </P><P>
  194. <B>Source/DFPSR/base/simd.h</B> contains I32x4, a SIMD vector storing 4 signed 32-bit integers.
  195. </P><P>
  196. <B>Source/DFPSR/base/simd.h</B> contains U32x4, a SIMD vector storing 4 unsigned 32-bit integers.
  197. </P><P>
  198. <B>Source/DFPSR/base/simd.h</B> contains U16x8, a SIMD vector storing 8 unsigned 16-bit integers.
  199. </P><P>
  200. <B>Source/DFPSR/base/simd.h</B> contains U8x16, a SIMD vector storing 16 unsigned 8-bit integers.
  201. </P><P>
  202. SIMD vectorization requires that the images are aligned.
  203. Ordered images such as OrderedImageRgbaU8 are also aligned.
  204. Sub-images from image_getSubImage are not aligned, because otherwise their construction would require runtime checks that might randomly fail and requesting an aligned image for SIMD will often also assume ownership of any padding bytes for writing over with garbage data.
  205. </P><P>
  206. When using readAligned or writeAligned in debug mode, you get both bound checks and alignment checks at runtime.
  207. So make sure that you enable debug mode when developing with the SIMD vectors.
  208. </P><P>
  209. You might want to check which SIMD functions are available before writing your algorithm, because some are only available for certain datatypes.
  210. </P><P>
  211. Iterate in multiples of 16 bytes over the pixel rows to stay aligned with the memory.
  212. When adding an integer to a pointer, the address offset is multiplied by the pointer's element size.
  213. This means that a pointers of uint32_t for a color pixel only needs to add 4 elements to the pointer to move 16 bytes, while pointers of uint16_t moves 8 elements and pointers of uint8_t moves 16 elements.
  214. </P><P>
  215. Adding two grayscale images using <B>SIMD vectorization</B>:
  216. <PRE><BLOCKQUOTE>void addImages_simd(AlignedImageU8 targetImage, AlignedImageU8 imageA, AlignedImageU8 imageB) {
  217. int width = image_getWidth(targetImage);
  218. int height = image_getHeight(targetImage);
  219. SafePointer&lt;uint8_t&gt; targetRow = image_getSafePointer(targetImage);
  220. SafePointer&lt;uint8_t&gt; rowA = image_getSafePointer(imageA);
  221. SafePointer&lt;uint8_t&gt; rowB = image_getSafePointer(imageB);
  222. int targetStride = image_getStride(targetImage);
  223. int strideA = image_getStride(imageA);
  224. int strideB = image_getStride(imageB);
  225. for (int y = 0; y &lt; height; y++) {
  226. SafePointer&lt;uint8_t&gt; targetPixel = targetRow;
  227. SafePointer&lt;uint8_t&gt; pixelA = rowA;
  228. SafePointer&lt;uint8_t&gt; pixelB = rowB;
  229. // Assuming that we have ownership of any padding pixels
  230. for (int x = 0; x &lt; width; x += 16) {
  231. // Read 16 source pixels at a time
  232. U8x16 a = U8x16::readAligned(pixelA, "addImages: reading pixelA");
  233. U8x16 b = U8x16::readAligned(pixelB, "addImages: reading pixelB");
  234. // Saturated operations replace conditional move
  235. U8x16 result = saturatedAddition(a, b);
  236. // Write the result 16 pixels at a time
  237. result.writeAligned(targetPixel, "addImages: writing result");
  238. // Move pixel pointers to the next pixel
  239. targetPixel += 16;
  240. pixelA += 16;
  241. pixelB += 16;
  242. }
  243. // Move row pointers to the next row
  244. targetRow.increaseBytes(targetStride);
  245. rowA.increaseBytes(strideA);
  246. rowB.increaseBytes(strideB);
  247. }
  248. }
  249. </BLOCKQUOTE></PRE>
  250. </P><P>
  251. </P><IMG SRC="Images/Border.png"><P>
  252. </P><P>
  253. </P><H2> Loops with the arbitrary X vector size (faster for heavy calculations)</H2><P>
  254. </P><P>
  255. <B>Source/DFPSR/base/simd.h</B> contains F32xX, a SIMD vector storing laneCountX_32Bit 32-bit floats.
  256. </P><P>
  257. <B>Source/DFPSR/base/simd.h</B> contains I32xX, a SIMD vector storing laneCountX_32Bit signed 32-bit integers.
  258. </P><P>
  259. <B>Source/DFPSR/base/simd.h</B> contains U32xX, a SIMD vector storing laneCountX_32Bit unsigned 32-bit integers.
  260. </P><P>
  261. <B>Source/DFPSR/base/simd.h</B> contains U16xX, a SIMD vector storing laneCountX_16Bit unsigned 16-bit integers.
  262. </P><P>
  263. <B>Source/DFPSR/base/simd.h</B> contains U8xX, a SIMD vector storing laneCountX_8Bit unsigned 8-bit integers.
  264. </P><P>
  265. Then you might want to take advantage of 256-bit SIMD vectors, but don't want to copy and paste code to use both U8x16 and U8x32.
  266. For functions working directly on values without reading nor writing, you can use templates to have multiple vector lengths supported at the same time.
  267. For a filter however, you only need to generate the code for the biggest available vector size, so we use U8xX and laneCountX_8Bit for processing 8-bit monochrome images using type aliases.
  268. When building with AVX2 (-mavx2 for g++), the X vector types (F32xX, I32xX, U32xX, U16xX, U8xX) change size from 128 bits to 256 bits and their lane counts (laneCountX_32Bit, laneCountX_16Bit, laneCountX_8Bit) also double.
  269. If you do not have AVX2 on your computer for testing this, you can force the X vector to be at least 256 bits by defining the macro EMULATE_256BIT_X_SIMD globally or in settings.h.
  270. The aligned image types and buffers allocated by the library are always aligned with DSR_MAXIMUM_ALIGNMENT from settings.h, so you can safely use the X and F vectors on any buffer or aligned image.
  271. </P><P>
  272. Replaced <B>U8x16</B> with <B>U8xX</B> and <B>16</B> with <B>laneCountX_8Bit</B> to work with any future SIMD vector length:
  273. <PRE><BLOCKQUOTE>void addImages_simd(AlignedImageU8 targetImage, AlignedImageU8 imageA, AlignedImageU8 imageB) {
  274. int width = image_getWidth(targetImage);
  275. int height = image_getHeight(targetImage);
  276. SafePointer&lt;uint8_t&gt; targetRow = image_getSafePointer(targetImage);
  277. SafePointer&lt;uint8_t&gt; rowA = image_getSafePointer(imageA);
  278. SafePointer&lt;uint8_t&gt; rowB = image_getSafePointer(imageB);
  279. int targetStride = image_getStride(targetImage);
  280. int strideA = image_getStride(imageA);
  281. int strideB = image_getStride(imageB);
  282. for (int y = 0; y &lt; height; y++) {
  283. SafePointer&lt;uint8_t&gt; targetPixel = targetRow;
  284. SafePointer&lt;uint8_t&gt; pixelA = rowA;
  285. SafePointer&lt;uint8_t&gt; pixelB = rowB;
  286. // Assuming that we have ownership of any padding pixels
  287. for (int x = 0; x &lt; width; x += laneCountX_8Bit) {
  288. // Read multiple source pixels at a time
  289. U8xX a = U8xX::readAligned(pixelA, "addImages: reading pixelA");
  290. U8xX b = U8xX::readAligned(pixelB, "addImages: reading pixelB");
  291. // Saturated operations replace conditional move
  292. U8xX result = saturatedAddition(a, b);
  293. // Write the result multiple pixels at a time
  294. result.writeAligned(targetPixel, "addImages: writing result");
  295. // Move pixel pointers to the next pixel
  296. targetPixel += laneCountX_8Bit;
  297. pixelA += laneCountX_8Bit;
  298. pixelB += laneCountX_8Bit;
  299. }
  300. // Move row pointers to the next row
  301. targetRow.increaseBytes(targetStride);
  302. rowA.increaseBytes(strideA);
  303. rowB.increaseBytes(strideB);
  304. }
  305. }
  306. </BLOCKQUOTE></PRE>
  307. </P><P>
  308. </P><IMG SRC="Images/Border.png"><P>
  309. </P>
  310. </BODY> </HTML>