You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

HybridBinarizer.cs 12 kB

10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright 2009 ZXing authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. namespace ZXing.Common
  17. {
  18. /// <summary> This class implements a local thresholding algorithm, which while slower than the
  19. /// GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
  20. /// high frequency images of barcodes with black data on white backgrounds. For this application,
  21. /// it does a much better job than a global blackpoint with severe shadows and gradients.
  22. /// However it tends to produce artifacts on lower frequency images and is therefore not
  23. /// a good general purpose binarizer for uses outside ZXing.
  24. ///
  25. /// This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
  26. /// and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
  27. /// inherently local, and only fails for horizontal gradients. We can revisit that problem later,
  28. /// but for now it was not a win to use local blocks for 1D.
  29. ///
  30. /// This Binarizer is the default for the unit tests and the recommended class for library users.
  31. ///
  32. /// </summary>
  33. /// <author> dswitkin@google.com (Daniel Switkin)
  34. /// </author>
  35. /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
  36. /// </author>
  37. public sealed class HybridBinarizer : GlobalHistogramBinarizer
  38. {
  39. override public BitMatrix BlackMatrix
  40. {
  41. get
  42. {
  43. binarizeEntireImage();
  44. return matrix;
  45. }
  46. }
  47. // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
  48. // So this is the smallest dimension in each axis we can accept.
  49. private const int BLOCK_SIZE_POWER = 3;
  50. private const int BLOCK_SIZE = 1 << BLOCK_SIZE_POWER; // ...0100...00
  51. private const int BLOCK_SIZE_MASK = BLOCK_SIZE - 1; // ...0011...11
  52. private const int MINIMUM_DIMENSION = 40;
  53. private const int MIN_DYNAMIC_RANGE = 24;
  54. private BitMatrix matrix = null;
  55. public HybridBinarizer(LuminanceSource source)
  56. : base(source)
  57. {
  58. }
  59. public override Binarizer createBinarizer(LuminanceSource source)
  60. {
  61. return new HybridBinarizer(source);
  62. }
  63. /// <summary>
  64. /// Calculates the final BitMatrix once for all requests. This could be called once from the
  65. /// constructor instead, but there are some advantages to doing it lazily, such as making
  66. /// profiling easier, and not doing heavy lifting when callers don't expect it.
  67. /// </summary>
  68. private void binarizeEntireImage()
  69. {
  70. if (matrix == null)
  71. {
  72. LuminanceSource source = LuminanceSource;
  73. int width = source.Width;
  74. int height = source.Height;
  75. if (width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION)
  76. {
  77. byte[] luminances = source.Matrix;
  78. int subWidth = width >> BLOCK_SIZE_POWER;
  79. if ((width & BLOCK_SIZE_MASK) != 0)
  80. {
  81. subWidth++;
  82. }
  83. int subHeight = height >> BLOCK_SIZE_POWER;
  84. if ((height & BLOCK_SIZE_MASK) != 0)
  85. {
  86. subHeight++;
  87. }
  88. int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height);
  89. var newMatrix = new BitMatrix(width, height);
  90. calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix);
  91. matrix = newMatrix;
  92. }
  93. else
  94. {
  95. // If the image is too small, fall back to the global histogram approach.
  96. matrix = base.BlackMatrix;
  97. }
  98. }
  99. }
  100. /// <summary>
  101. /// For each 8x8 block in the image, calculate the average black point using a 5x5 grid
  102. /// of the blocks around it. Also handles the corner cases (fractional blocks are computed based
  103. /// on the last 8 pixels in the row/column which are also used in the previous block).
  104. /// </summary>
  105. /// <param name="luminances">The luminances.</param>
  106. /// <param name="subWidth">Width of the sub.</param>
  107. /// <param name="subHeight">Height of the sub.</param>
  108. /// <param name="width">The width.</param>
  109. /// <param name="height">The height.</param>
  110. /// <param name="blackPoints">The black points.</param>
  111. /// <param name="matrix">The matrix.</param>
  112. private static void calculateThresholdForBlock(byte[] luminances, int subWidth, int subHeight, int width, int height, int[][] blackPoints, BitMatrix matrix)
  113. {
  114. for (int y = 0; y < subHeight; y++)
  115. {
  116. int yoffset = y << BLOCK_SIZE_POWER;
  117. int maxYOffset = height - BLOCK_SIZE;
  118. if (yoffset > maxYOffset)
  119. {
  120. yoffset = maxYOffset;
  121. }
  122. for (int x = 0; x < subWidth; x++)
  123. {
  124. int xoffset = x << BLOCK_SIZE_POWER;
  125. int maxXOffset = width - BLOCK_SIZE;
  126. if (xoffset > maxXOffset)
  127. {
  128. xoffset = maxXOffset;
  129. }
  130. int left = cap(x, 2, subWidth - 3);
  131. int top = cap(y, 2, subHeight - 3);
  132. int sum = 0;
  133. for (int z = -2; z <= 2; z++)
  134. {
  135. int[] blackRow = blackPoints[top + z];
  136. sum += blackRow[left - 2];
  137. sum += blackRow[left - 1];
  138. sum += blackRow[left];
  139. sum += blackRow[left + 1];
  140. sum += blackRow[left + 2];
  141. }
  142. int average = sum / 25;
  143. thresholdBlock(luminances, xoffset, yoffset, average, width, matrix);
  144. }
  145. }
  146. }
  147. private static int cap(int value, int min, int max)
  148. {
  149. return value < min ? min : value > max ? max : value;
  150. }
  151. /// <summary>
  152. /// Applies a single threshold to an 8x8 block of pixels.
  153. /// </summary>
  154. /// <param name="luminances">The luminances.</param>
  155. /// <param name="xoffset">The xoffset.</param>
  156. /// <param name="yoffset">The yoffset.</param>
  157. /// <param name="threshold">The threshold.</param>
  158. /// <param name="stride">The stride.</param>
  159. /// <param name="matrix">The matrix.</param>
  160. private static void thresholdBlock(byte[] luminances, int xoffset, int yoffset, int threshold, int stride, BitMatrix matrix)
  161. {
  162. int offset = (yoffset * stride) + xoffset;
  163. for (int y = 0; y < BLOCK_SIZE; y++, offset += stride)
  164. {
  165. for (int x = 0; x < BLOCK_SIZE; x++)
  166. {
  167. int pixel = luminances[offset + x] & 0xff;
  168. // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
  169. matrix[xoffset + x, yoffset + y] = (pixel <= threshold);
  170. }
  171. }
  172. }
  173. /// <summary>
  174. /// Calculates a single black point for each 8x8 block of pixels and saves it away.
  175. /// See the following thread for a discussion of this algorithm:
  176. /// http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
  177. /// </summary>
  178. /// <param name="luminances">The luminances.</param>
  179. /// <param name="subWidth">Width of the sub.</param>
  180. /// <param name="subHeight">Height of the sub.</param>
  181. /// <param name="width">The width.</param>
  182. /// <param name="height">The height.</param>
  183. /// <returns></returns>
  184. private static int[][] calculateBlackPoints(byte[] luminances, int subWidth, int subHeight, int width, int height)
  185. {
  186. int[][] blackPoints = new int[subHeight][];
  187. for (int i = 0; i < subHeight; i++)
  188. {
  189. blackPoints[i] = new int[subWidth];
  190. }
  191. for (int y = 0; y < subHeight; y++)
  192. {
  193. int yoffset = y << BLOCK_SIZE_POWER;
  194. int maxYOffset = height - BLOCK_SIZE;
  195. if (yoffset > maxYOffset)
  196. {
  197. yoffset = maxYOffset;
  198. }
  199. for (int x = 0; x < subWidth; x++)
  200. {
  201. int xoffset = x << BLOCK_SIZE_POWER;
  202. int maxXOffset = width - BLOCK_SIZE;
  203. if (xoffset > maxXOffset)
  204. {
  205. xoffset = maxXOffset;
  206. }
  207. int sum = 0;
  208. int min = 0xFF;
  209. int max = 0;
  210. for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width)
  211. {
  212. for (int xx = 0; xx < BLOCK_SIZE; xx++)
  213. {
  214. int pixel = luminances[offset + xx] & 0xFF;
  215. // still looking for good contrast
  216. sum += pixel;
  217. if (pixel < min)
  218. {
  219. min = pixel;
  220. }
  221. if (pixel > max)
  222. {
  223. max = pixel;
  224. }
  225. }
  226. // short-circuit min/max tests once dynamic range is met
  227. if (max - min > MIN_DYNAMIC_RANGE)
  228. {
  229. // finish the rest of the rows quickly
  230. for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width)
  231. {
  232. for (int xx = 0; xx < BLOCK_SIZE; xx++)
  233. {
  234. sum += luminances[offset + xx] & 0xFF;
  235. }
  236. }
  237. }
  238. }
  239. // The default estimate is the average of the values in the block.
  240. int average = sum >> (BLOCK_SIZE_POWER * 2);
  241. if (max - min <= MIN_DYNAMIC_RANGE)
  242. {
  243. // If variation within the block is low, assume this is a block with only light or only
  244. // dark pixels. In that case we do not want to use the average, as it would divide this
  245. // low contrast area into black and white pixels, essentially creating data out of noise.
  246. //
  247. // The default assumption is that the block is light/background. Since no estimate for
  248. // the level of dark pixels exists locally, use half the min for the block.
  249. average = min >> 1;
  250. if (y > 0 && x > 0)
  251. {
  252. // Correct the "white background" assumption for blocks that have neighbors by comparing
  253. // the pixels in this block to the previously calculated black points. This is based on
  254. // the fact that dark barcode symbology is always surrounded by some amount of light
  255. // background for which reasonable black point estimates were made. The bp estimated at
  256. // the boundaries is used for the interior.
  257. // The (min < bp) is arbitrary but works better than other heuristics that were tried.
  258. int averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) +
  259. blackPoints[y - 1][x - 1]) >> 2;
  260. if (min < averageNeighborBlackPoint)
  261. {
  262. average = averageNeighborBlackPoint;
  263. }
  264. }
  265. }
  266. blackPoints[y][x] = average;
  267. }
  268. }
  269. return blackPoints;
  270. }
  271. }
  272. }