HybridBinarizer.php 9.0 KB

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