AlignmentPatternFinder.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. /*
  3. * Copyright 2007 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\Qrcode\Detector;
  18. use Zxing\NotFoundException;
  19. use Zxing\ResultPointCallback;
  20. use Zxing\Common\BitMatrix;
  21. /**
  22. * <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
  23. * patterns but are smaller and appear at regular intervals throughout the image.</p>
  24. *
  25. * <p>At the moment this only looks for the bottom-right alignment pattern.</p>
  26. *
  27. * <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
  28. * pasted and stripped down here for maximum performance but does unfortunately duplicate
  29. * some code.</p>
  30. *
  31. * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
  32. *
  33. * @author Sean Owen
  34. */
  35. final class AlignmentPatternFinder
  36. {
  37. private $image;
  38. private $possibleCenters;
  39. private $startX;
  40. private $startY;
  41. private $width;
  42. private $height;
  43. private $moduleSize;
  44. private $crossCheckStateCount;
  45. private $resultPointCallback;
  46. /**
  47. * <p>Creates a finder that will look in a portion of the whole image.</p>
  48. *
  49. * @param image image to search
  50. * @param startX left column from which to start searching
  51. * @param startY top row from which to start searching
  52. * @param width width of region to search
  53. * @param height height of region to search
  54. * @param moduleSize estimated module size so far
  55. */
  56. public function __construct($image,
  57. $startX,
  58. $startY,
  59. $width,
  60. $height,
  61. $moduleSize,
  62. $resultPointCallback)
  63. {
  64. $this->image = $image;
  65. $this->possibleCenters = [];
  66. $this->startX = $startX;
  67. $this->startY = $startY;
  68. $this->width = $width;
  69. $this->height = $height;
  70. $this->moduleSize = $moduleSize;
  71. $this->crossCheckStateCount = [];
  72. $this->resultPointCallback = $resultPointCallback;
  73. }
  74. /**
  75. * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
  76. * it's pretty performance-critical and so is written to be fast foremost.</p>
  77. *
  78. * @return {@link AlignmentPattern} if found
  79. * @throws NotFoundException if not found
  80. */
  81. public function find()
  82. {
  83. $startX = $this->startX;
  84. $height = $this->height;
  85. $maxJ = $startX + $this->width;
  86. $middleI = $this->startY + ($height / 2);
  87. // We are looking for black/white/black modules in 1:1:1 ratio;
  88. // this tracks the number of black/white/black modules seen so far
  89. $stateCount = [];
  90. for ($iGen = 0; $iGen < $height; $iGen++) {
  91. // Search from middle outwards
  92. $i = $middleI + (($iGen & 0x01) == 0 ? ($iGen + 1) / 2 : -(($iGen + 1) / 2));
  93. $i = (int)($i);
  94. $stateCount[0] = 0;
  95. $stateCount[1] = 0;
  96. $stateCount[2] = 0;
  97. $j = $startX;
  98. // Burn off leading white pixels before anything else; if we start in the middle of
  99. // a white run, it doesn't make sense to count its length, since we don't know if the
  100. // white run continued to the left of the start point
  101. while ($j < $maxJ && !$this->image->get($j, $i)) {
  102. $j++;
  103. }
  104. $currentState = 0;
  105. while ($j < $maxJ) {
  106. if ($this->image->get($j, $i)) {
  107. // Black pixel
  108. if ($currentState == 1) { // Counting black pixels
  109. $stateCount[$currentState]++;
  110. } else { // Counting white pixels
  111. if ($currentState == 2) { // A winner?
  112. if ($this->foundPatternCross($stateCount)) { // Yes
  113. $confirmed = $this->handlePossibleCenter($stateCount, $i, $j);
  114. if ($confirmed != null) {
  115. return $confirmed;
  116. }
  117. }
  118. $stateCount[0] = $stateCount[2];
  119. $stateCount[1] = 1;
  120. $stateCount[2] = 0;
  121. $currentState = 1;
  122. } else {
  123. $stateCount[++$currentState]++;
  124. }
  125. }
  126. } else { // White pixel
  127. if ($currentState == 1) { // Counting black pixels
  128. $currentState++;
  129. }
  130. $stateCount[$currentState]++;
  131. }
  132. $j++;
  133. }
  134. if ($this->foundPatternCross($stateCount)) {
  135. $confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ);
  136. if ($confirmed != null) {
  137. return $confirmed;
  138. }
  139. }
  140. }
  141. // Hmm, nothing we saw was observed and confirmed twice. If we had
  142. // any guess at all, return it.
  143. if (count($this->possibleCenters)) {
  144. return $this->possibleCenters[0];
  145. }
  146. throw NotFoundException::getNotFoundInstance();
  147. }
  148. /**
  149. * @param stateCount count of black/white/black pixels just read
  150. *
  151. * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios
  152. * used by alignment patterns to be considered a match
  153. */
  154. private function foundPatternCross($stateCount)
  155. {
  156. $moduleSize = $this->moduleSize;
  157. $maxVariance = $moduleSize / 2.0;
  158. for ($i = 0; $i < 3; $i++) {
  159. if (abs($moduleSize - $stateCount[$i]) >= $maxVariance) {
  160. return false;
  161. }
  162. }
  163. return true;
  164. }
  165. /**
  166. * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
  167. * cross check with a vertical scan, and if successful, will see if this pattern had been
  168. * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
  169. * found the alignment pattern.</p>
  170. *
  171. * @param stateCount reading state module counts from horizontal scan
  172. * @param i row where alignment pattern may be found
  173. * @param j end of possible alignment pattern in row
  174. *
  175. * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not
  176. */
  177. private function handlePossibleCenter($stateCount, $i, $j)
  178. {
  179. $stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2];
  180. $centerJ = $this->centerFromEnd($stateCount, $j);
  181. $centerI = $this->crossCheckVertical($i, (int)$centerJ, 2 * $stateCount[1], $stateCountTotal);
  182. if (!is_nan($centerI)) {
  183. $estimatedModuleSize = (float)($stateCount[0] + $stateCount[1] + $stateCount[2]) / 3.0;
  184. foreach ($this->possibleCenters as $center) {
  185. // Look for about the same center and module size:
  186. if ($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)) {
  187. return $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
  188. }
  189. }
  190. // Hadn't found this before; save it
  191. $point = new AlignmentPattern($centerJ, $centerI, $estimatedModuleSize);
  192. $this->possibleCenters[] = $point;
  193. if ($this->resultPointCallback != null) {
  194. $this->resultPointCallback->foundPossibleResultPoint($point);
  195. }
  196. }
  197. return null;
  198. }
  199. /**
  200. * Given a count of black/white/black pixels just seen and an end position,
  201. * figures the location of the center of this black/white/black run.
  202. */
  203. private static function centerFromEnd($stateCount, $end)
  204. {
  205. return (float)($end - $stateCount[2]) - $stateCount[1] / 2.0;
  206. }
  207. /**
  208. * <p>After a horizontal scan finds a potential alignment pattern, this method
  209. * "cross-checks" by scanning down vertically through the center of the possible
  210. * alignment pattern to see if the same proportion is detected.</p>
  211. *
  212. * @param startI row where an alignment pattern was detected
  213. * @param centerJ center of the section that appears to cross an alignment pattern
  214. * @param maxCount maximum reasonable number of modules that should be
  215. * observed in any reading state, based on the results of the horizontal scan
  216. *
  217. * @return vertical center of alignment pattern, or {@link Float#NaN} if not found
  218. */
  219. private function crossCheckVertical($startI, $centerJ, $maxCount,
  220. $originalStateCountTotal)
  221. {
  222. $image = $this->image;
  223. $maxI = $image->getHeight();
  224. $stateCount = $this->crossCheckStateCount;
  225. $stateCount[0] = 0;
  226. $stateCount[1] = 0;
  227. $stateCount[2] = 0;
  228. // Start counting up from center
  229. $i = $startI;
  230. while ($i >= 0 && $image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
  231. $stateCount[1]++;
  232. $i--;
  233. }
  234. // If already too many modules in this state or ran off the edge:
  235. if ($i < 0 || $stateCount[1] > $maxCount) {
  236. return NAN;
  237. }
  238. while ($i >= 0 && !$image->get($centerJ, $i) && $stateCount[0] <= $maxCount) {
  239. $stateCount[0]++;
  240. $i--;
  241. }
  242. if ($stateCount[0] > $maxCount) {
  243. return NAN;
  244. }
  245. // Now also count down from center
  246. $i = $startI + 1;
  247. while ($i < $maxI && $image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
  248. $stateCount[1]++;
  249. $i++;
  250. }
  251. if ($i == $maxI || $stateCount[1] > $maxCount) {
  252. return NAN;
  253. }
  254. while ($i < $maxI && !$image->get($centerJ, $i) && $stateCount[2] <= $maxCount) {
  255. $stateCount[2]++;
  256. $i++;
  257. }
  258. if ($stateCount[2] > $maxCount) {
  259. return NAN;
  260. }
  261. $stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2];
  262. if (5 * abs($stateCountTotal - $originalStateCountTotal) >= 2 * $originalStateCountTotal) {
  263. return NAN;
  264. }
  265. return $this->foundPatternCross($stateCount) ? $this->centerFromEnd($stateCount, $i) : NAN;
  266. }
  267. }