AlignmentPatternFinder.php 8.7 KB

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