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.

GlobalHistogramBinarizer.cs 9.0 kB

10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 Binarizer implementation uses the old ZXing global histogram approach. It is suitable
  19. /// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
  20. /// algorithm. However, because it picks a global black point, it cannot handle difficult shadows
  21. /// and gradients.
  22. ///
  23. /// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
  24. ///
  25. /// <author>dswitkin@google.com (Daniel Switkin)</author>
  26. /// <author>Sean Owen</author>
  27. /// </summary>
  28. public class GlobalHistogramBinarizer : Binarizer
  29. {
  30. private const int LUMINANCE_BITS = 5;
  31. private const int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
  32. private const int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
  33. private static readonly byte[] EMPTY = new byte[0];
  34. private byte[] luminances;
  35. private readonly int[] buckets;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="GlobalHistogramBinarizer"/> class.
  38. /// </summary>
  39. /// <param name="source">The source.</param>
  40. public GlobalHistogramBinarizer(LuminanceSource source)
  41. : base(source)
  42. {
  43. luminances = EMPTY;
  44. buckets = new int[LUMINANCE_BUCKETS];
  45. }
  46. /// <summary>
  47. /// Applies simple sharpening to the row data to improve performance of the 1D Readers.
  48. /// </summary>
  49. /// <param name="y"></param>
  50. /// <param name="row"></param>
  51. /// <returns></returns>
  52. public override BitArray getBlackRow(int y, BitArray row)
  53. {
  54. LuminanceSource source = LuminanceSource;
  55. int width = source.Width;
  56. if (row == null || row.Size < width)
  57. {
  58. row = new BitArray(width);
  59. }
  60. else
  61. {
  62. row.clear();
  63. }
  64. initArrays(width);
  65. byte[] localLuminances = source.getRow(y, luminances);
  66. int[] localBuckets = buckets;
  67. for (int x = 0; x < width; x++)
  68. {
  69. int pixel = localLuminances[x] & 0xff;
  70. localBuckets[pixel >> LUMINANCE_SHIFT]++;
  71. }
  72. int blackPoint;
  73. if (!estimateBlackPoint(localBuckets, out blackPoint))
  74. return null;
  75. int left = localLuminances[0] & 0xff;
  76. int center = localLuminances[1] & 0xff;
  77. for (int x = 1; x < width - 1; x++)
  78. {
  79. int right = localLuminances[x + 1] & 0xff;
  80. // A simple -1 4 -1 box filter with a weight of 2.
  81. int luminance = ((center << 2) - left - right) >> 1;
  82. row[x] = (luminance < blackPoint);
  83. left = center;
  84. center = right;
  85. }
  86. return row;
  87. }
  88. /// <summary>
  89. /// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
  90. /// </summary>
  91. override public BitMatrix BlackMatrix
  92. {
  93. get
  94. {
  95. LuminanceSource source = LuminanceSource;
  96. byte[] localLuminances;
  97. int width = source.Width;
  98. int height = source.Height;
  99. BitMatrix matrix = new BitMatrix(width, height);
  100. // Quickly calculates the histogram by sampling four rows from the image. This proved to be
  101. // more robust on the blackbox tests than sampling a diagonal as we used to do.
  102. initArrays(width);
  103. int[] localBuckets = buckets;
  104. for (int y = 1; y < 5; y++)
  105. {
  106. int row = height * y / 5;
  107. localLuminances = source.getRow(row, luminances);
  108. int right = (width << 2) / 5;
  109. for (int x = width / 5; x < right; x++)
  110. {
  111. int pixel = localLuminances[x] & 0xff;
  112. localBuckets[pixel >> LUMINANCE_SHIFT]++;
  113. }
  114. }
  115. int blackPoint;
  116. if (!estimateBlackPoint(localBuckets, out blackPoint))
  117. return null;
  118. // We delay reading the entire image luminance until the black point estimation succeeds.
  119. // Although we end up reading four rows twice, it is consistent with our motto of
  120. // "fail quickly" which is necessary for continuous scanning.
  121. localLuminances = source.Matrix;
  122. for (int y = 0; y < height; y++)
  123. {
  124. int offset = y * width;
  125. for (int x = 0; x < width; x++)
  126. {
  127. int pixel = localLuminances[offset + x] & 0xff;
  128. matrix[x, y] = (pixel < blackPoint);
  129. }
  130. }
  131. return matrix;
  132. }
  133. }
  134. /// <summary>
  135. /// Creates a new object with the same type as this Binarizer implementation, but with pristine
  136. /// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache
  137. /// of 1 bit data. See Effective Java for why we can't use Java's clone() method.
  138. /// </summary>
  139. /// <param name="source">The LuminanceSource this Binarizer will operate on.</param>
  140. /// <returns>
  141. /// A new concrete Binarizer implementation object.
  142. /// </returns>
  143. public override Binarizer createBinarizer(LuminanceSource source)
  144. {
  145. return new GlobalHistogramBinarizer(source);
  146. }
  147. private void initArrays(int luminanceSize)
  148. {
  149. if (luminances.Length < luminanceSize)
  150. {
  151. luminances = new byte[luminanceSize];
  152. }
  153. for (int x = 0; x < LUMINANCE_BUCKETS; x++)
  154. {
  155. buckets[x] = 0;
  156. }
  157. }
  158. private static bool estimateBlackPoint(int[] buckets, out int blackPoint)
  159. {
  160. blackPoint = 0;
  161. // Find the tallest peak in the histogram.
  162. int numBuckets = buckets.Length;
  163. int maxBucketCount = 0;
  164. int firstPeak = 0;
  165. int firstPeakSize = 0;
  166. for (int x = 0; x < numBuckets; x++)
  167. {
  168. if (buckets[x] > firstPeakSize)
  169. {
  170. firstPeak = x;
  171. firstPeakSize = buckets[x];
  172. }
  173. if (buckets[x] > maxBucketCount)
  174. {
  175. maxBucketCount = buckets[x];
  176. }
  177. }
  178. // Find the second-tallest peak which is somewhat far from the tallest peak.
  179. int secondPeak = 0;
  180. int secondPeakScore = 0;
  181. for (int x = 0; x < numBuckets; x++)
  182. {
  183. int distanceToBiggest = x - firstPeak;
  184. // Encourage more distant second peaks by multiplying by square of distance.
  185. int score = buckets[x] * distanceToBiggest * distanceToBiggest;
  186. if (score > secondPeakScore)
  187. {
  188. secondPeak = x;
  189. secondPeakScore = score;
  190. }
  191. }
  192. // Make sure firstPeak corresponds to the black peak.
  193. if (firstPeak > secondPeak)
  194. {
  195. int temp = firstPeak;
  196. firstPeak = secondPeak;
  197. secondPeak = temp;
  198. }
  199. // If there is too little contrast in the image to pick a meaningful black point, throw rather
  200. // than waste time trying to decode the image, and risk false positives.
  201. // TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the
  202. // two peaks, to determine the contrast.
  203. if (secondPeak - firstPeak <= numBuckets >> 4)
  204. {
  205. return false;
  206. }
  207. // Find a valley between them that is low and closer to the white peak.
  208. int bestValley = secondPeak - 1;
  209. int bestValleyScore = -1;
  210. for (int x = secondPeak - 1; x > firstPeak; x--)
  211. {
  212. int fromFirst = x - firstPeak;
  213. int score = fromFirst*fromFirst*(secondPeak - x)*(maxBucketCount - buckets[x]);
  214. if (score > bestValleyScore)
  215. {
  216. bestValley = x;
  217. bestValleyScore = score;
  218. }
  219. }
  220. blackPoint = bestValley << LUMINANCE_SHIFT;
  221. return true;
  222. }
  223. }
  224. }