Detector.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. /**
  3. * Class Detector
  4. *
  5. * @created 17.01.2021
  6. * @author ZXing Authors
  7. * @author Smiley <smiley@chillerlan.net>
  8. * @copyright 2021 Smiley
  9. * @license Apache-2.0
  10. */
  11. declare(strict_types=1);
  12. namespace chillerlan\QRCode\Detector;
  13. use chillerlan\QRCode\Common\{LuminanceSourceInterface, Version};
  14. use chillerlan\QRCode\Decoder\{Binarizer, BitMatrix};
  15. use function abs, intdiv, is_nan, max, min, round;
  16. use const NAN;
  17. /**
  18. * Encapsulates logic that can detect a QR Code in an image, even if the QR Code
  19. * is rotated or skewed, or partially obscured.
  20. *
  21. * @author Sean Owen
  22. */
  23. final class Detector{
  24. private BitMatrix $matrix;
  25. /**
  26. * Detector constructor.
  27. */
  28. public function __construct(LuminanceSourceInterface $source){
  29. $this->matrix = (new Binarizer($source))->getBlackMatrix();
  30. }
  31. /**
  32. * Detects a QR Code in an image.
  33. */
  34. public function detect():BitMatrix{
  35. [$bottomLeft, $topLeft, $topRight] = (new FinderPatternFinder($this->matrix))->find();
  36. $moduleSize = $this->calculateModuleSize($topLeft, $topRight, $bottomLeft);
  37. $dimension = $this->computeDimension($topLeft, $topRight, $bottomLeft, $moduleSize);
  38. $provisionalVersion = new Version(intdiv(($dimension - 17), 4));
  39. $alignmentPattern = null;
  40. // Anything above version 1 has an alignment pattern
  41. if(!empty($provisionalVersion->getAlignmentPattern())){
  42. // Guess where a "bottom right" finder pattern would have been
  43. $bottomRightX = ($topRight->getX() - $topLeft->getX() + $bottomLeft->getX());
  44. $bottomRightY = ($topRight->getY() - $topLeft->getY() + $bottomLeft->getY());
  45. // Estimate that alignment pattern is closer by 3 modules
  46. // from "bottom right" to known top left location
  47. $correctionToTopLeft = (1.0 - 3.0 / (float)($provisionalVersion->getDimension() - 7));
  48. $estAlignmentX = (int)($topLeft->getX() + $correctionToTopLeft * ($bottomRightX - $topLeft->getX()));
  49. $estAlignmentY = (int)($topLeft->getY() + $correctionToTopLeft * ($bottomRightY - $topLeft->getY()));
  50. // Kind of arbitrary -- expand search radius before giving up
  51. for($i = 4; $i <= 16; $i <<= 1){//??????????
  52. $alignmentPattern = $this->findAlignmentInRegion($moduleSize, $estAlignmentX, $estAlignmentY, (float)$i);
  53. if($alignmentPattern !== null){
  54. break;
  55. }
  56. }
  57. // If we didn't find alignment pattern... well try anyway without it
  58. }
  59. $transform = $this->createTransform($topLeft, $topRight, $bottomLeft, $dimension, $alignmentPattern);
  60. return (new GridSampler)->sampleGrid($this->matrix, $dimension, $transform);
  61. }
  62. /**
  63. * Computes an average estimated module size based on estimated derived from the positions
  64. * of the three finder patterns.
  65. *
  66. * @throws \chillerlan\QRCode\Detector\QRCodeDetectorException
  67. */
  68. private function calculateModuleSize(FinderPattern $topLeft, FinderPattern $topRight, FinderPattern $bottomLeft):float{
  69. // Take the average
  70. $moduleSize = ((
  71. $this->calculateModuleSizeOneWay($topLeft, $topRight) +
  72. $this->calculateModuleSizeOneWay($topLeft, $bottomLeft)
  73. ) / 2.0);
  74. if($moduleSize < 1.0){
  75. throw new QRCodeDetectorException('module size < 1.0');
  76. }
  77. return $moduleSize;
  78. }
  79. /**
  80. * Estimates module size based on two finder patterns -- it uses
  81. * #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int) to figure the
  82. * width of each, measuring along the axis between their centers.
  83. */
  84. private function calculateModuleSizeOneWay(FinderPattern $a, FinderPattern $b):float{
  85. $moduleSizeEst1 = $this->sizeOfBlackWhiteBlackRunBothWays($a->getX(), $a->getY(), $b->getX(), $b->getY());
  86. $moduleSizeEst2 = $this->sizeOfBlackWhiteBlackRunBothWays($b->getX(), $b->getY(), $a->getX(), $a->getY());
  87. if(is_nan($moduleSizeEst1)){
  88. return ($moduleSizeEst2 / 7.0);
  89. }
  90. if(is_nan($moduleSizeEst2)){
  91. return ($moduleSizeEst1 / 7.0);
  92. }
  93. // Average them, and divide by 7 since we've counted the width of 3 black modules,
  94. // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
  95. return (($moduleSizeEst1 + $moduleSizeEst2) / 14.0);
  96. }
  97. /**
  98. * See #sizeOfBlackWhiteBlackRun(int, int, int, int); computes the total width of
  99. * a finder pattern by looking for a black-white-black run from the center in the direction
  100. * of another po$(another finder pattern center), and in the opposite direction too.
  101. *
  102. * @noinspection DuplicatedCode
  103. */
  104. private function sizeOfBlackWhiteBlackRunBothWays(float $fromX, float $fromY, float $toX, float $toY):float{
  105. $result = $this->sizeOfBlackWhiteBlackRun((int)$fromX, (int)$fromY, (int)$toX, (int)$toY);
  106. $dimension = $this->matrix->getSize();
  107. // Now count other way -- don't run off image though of course
  108. $scale = 1.0;
  109. $otherToX = ($fromX - ($toX - $fromX));
  110. if($otherToX < 0){
  111. $scale = ($fromX / ($fromX - $otherToX));
  112. $otherToX = 0;
  113. }
  114. elseif($otherToX >= $dimension){
  115. $scale = (($dimension - 1 - $fromX) / ($otherToX - $fromX));
  116. $otherToX = ($dimension - 1);
  117. }
  118. $otherToY = (int)($fromY - ($toY - $fromY) * $scale);
  119. $scale = 1.0;
  120. if($otherToY < 0){
  121. $scale = ($fromY / ($fromY - $otherToY));
  122. $otherToY = 0;
  123. }
  124. elseif($otherToY >= $dimension){
  125. $scale = (($dimension - 1 - $fromY) / ($otherToY - $fromY));
  126. $otherToY = ($dimension - 1);
  127. }
  128. $otherToX = (int)($fromX + ($otherToX - $fromX) * $scale);
  129. $result += $this->sizeOfBlackWhiteBlackRun((int)$fromX, (int)$fromY, $otherToX, $otherToY);
  130. // Middle pixel is double-counted this way; subtract 1
  131. return ($result - 1.0);
  132. }
  133. /**
  134. * This method traces a line from a po$in the image, in the direction towards another point.
  135. * It begins in a black region, and keeps going until it finds white, then black, then white again.
  136. * It reports the distance from the start to this point.
  137. *
  138. * This is used when figuring out how wide a finder pattern is, when the finder pattern
  139. * may be skewed or rotated.
  140. */
  141. private function sizeOfBlackWhiteBlackRun(int $fromX, int $fromY, int $toX, int $toY):float{
  142. // Mild variant of Bresenham's algorithm;
  143. // @see https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
  144. $steep = abs($toY - $fromY) > abs($toX - $fromX);
  145. if($steep){
  146. $temp = $fromX;
  147. $fromX = $fromY;
  148. $fromY = $temp;
  149. $temp = $toX;
  150. $toX = $toY;
  151. $toY = $temp;
  152. }
  153. $dx = abs($toX - $fromX);
  154. $dy = abs($toY - $fromY);
  155. $error = (-$dx / 2);
  156. $xstep = (($fromX < $toX) ? 1 : -1);
  157. $ystep = (($fromY < $toY) ? 1 : -1);
  158. // In black pixels, looking for white, first or second time.
  159. $state = 0;
  160. // Loop up until x == toX, but not beyond
  161. $xLimit = ($toX + $xstep);
  162. for($x = $fromX, $y = $fromY; $x !== $xLimit; $x += $xstep){
  163. $realX = ($steep) ? $y : $x;
  164. $realY = ($steep) ? $x : $y;
  165. // Does current pixel mean we have moved white to black or vice versa?
  166. // Scanning black in state 0,2 and white in state 1, so if we find the wrong
  167. // color, advance to next state or end if we are in state 2 already
  168. if(($state === 1) === $this->matrix->check($realX, $realY)){
  169. if($state === 2){
  170. return FinderPattern::distance($x, $y, $fromX, $fromY);
  171. }
  172. $state++;
  173. }
  174. $error += $dy;
  175. if($error > 0){
  176. if($y === $toY){
  177. break;
  178. }
  179. $y += $ystep;
  180. $error -= $dx;
  181. }
  182. }
  183. // Found black-white-black; give the benefit of the doubt that the next pixel outside the image
  184. // is "white" so this last po$at (toX+xStep,toY) is the right ending. This is really a
  185. // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
  186. if($state === 2){
  187. return FinderPattern::distance(($toX + $xstep), $toY, $fromX, $fromY);
  188. }
  189. // else we didn't find even black-white-black; no estimate is really possible
  190. return NAN;
  191. }
  192. /**
  193. * Computes the dimension (number of modules on a size) of the QR Code based on the position
  194. * of the finder patterns and estimated module size.
  195. *
  196. * @throws \chillerlan\QRCode\Detector\QRCodeDetectorException
  197. */
  198. private function computeDimension(FinderPattern $nw, FinderPattern $ne, FinderPattern $sw, float $size):int{
  199. $tltrCentersDimension = (int)round($nw->getDistance($ne) / $size);
  200. $tlblCentersDimension = (int)round($nw->getDistance($sw) / $size);
  201. $dimension = (int)((($tltrCentersDimension + $tlblCentersDimension) / 2) + 7);
  202. switch($dimension % 4){
  203. case 0:
  204. $dimension++;
  205. break;
  206. // 1? do nothing
  207. case 2:
  208. $dimension--;
  209. break;
  210. case 3:
  211. throw new QRCodeDetectorException('estimated dimension: '.$dimension);
  212. }
  213. if(($dimension % 4) !== 1){
  214. throw new QRCodeDetectorException('dimension mod 4 is not 1');
  215. }
  216. return $dimension;
  217. }
  218. /**
  219. * Attempts to locate an alignment pattern in a limited region of the image, which is
  220. * guessed to contain it.
  221. *
  222. * @param float $overallEstModuleSize estimated module size so far
  223. * @param int $estAlignmentX x coordinate of center of area probably containing alignment pattern
  224. * @param int $estAlignmentY y coordinate of above
  225. * @param float $allowanceFactor number of pixels in all directions to search from the center
  226. *
  227. * @return \chillerlan\QRCode\Detector\AlignmentPattern|null if found, or null otherwise
  228. */
  229. private function findAlignmentInRegion(
  230. float $overallEstModuleSize,
  231. int $estAlignmentX,
  232. int $estAlignmentY,
  233. float $allowanceFactor,
  234. ):AlignmentPattern|null{
  235. // Look for an alignment pattern (3 modules in size) around where it should be
  236. $dimension = $this->matrix->getSize();
  237. $allowance = (int)($allowanceFactor * $overallEstModuleSize);
  238. $alignmentAreaLeftX = max(0, ($estAlignmentX - $allowance));
  239. $alignmentAreaRightX = min(($dimension - 1), ($estAlignmentX + $allowance));
  240. if(($alignmentAreaRightX - $alignmentAreaLeftX) < ($overallEstModuleSize * 3)){
  241. return null;
  242. }
  243. $alignmentAreaTopY = max(0, ($estAlignmentY - $allowance));
  244. $alignmentAreaBottomY = min(($dimension - 1), ($estAlignmentY + $allowance));
  245. if(($alignmentAreaBottomY - $alignmentAreaTopY) < ($overallEstModuleSize * 3)){
  246. return null;
  247. }
  248. return (new AlignmentPatternFinder($this->matrix, $overallEstModuleSize))->find(
  249. $alignmentAreaLeftX,
  250. $alignmentAreaTopY,
  251. ($alignmentAreaRightX - $alignmentAreaLeftX),
  252. ($alignmentAreaBottomY - $alignmentAreaTopY),
  253. );
  254. }
  255. private function createTransform(
  256. FinderPattern $nw,
  257. FinderPattern $ne,
  258. FinderPattern $sw,
  259. int $size,
  260. AlignmentPattern|null $ap = null,
  261. ):PerspectiveTransform{
  262. $dimMinusThree = ($size - 3.5);
  263. if($ap instanceof AlignmentPattern){
  264. $bottomRightX = $ap->getX();
  265. $bottomRightY = $ap->getY();
  266. $sourceBottomRightX = ($dimMinusThree - 3.0);
  267. $sourceBottomRightY = $sourceBottomRightX;
  268. }
  269. else{
  270. // Don't have an alignment pattern, just make up the bottom-right point
  271. $bottomRightX = ($ne->getX() - $nw->getX() + $sw->getX());
  272. $bottomRightY = ($ne->getY() - $nw->getY() + $sw->getY());
  273. $sourceBottomRightX = $dimMinusThree;
  274. $sourceBottomRightY = $dimMinusThree;
  275. }
  276. return (new PerspectiveTransform)->quadrilateralToQuadrilateral(
  277. 3.5,
  278. 3.5,
  279. $dimMinusThree,
  280. 3.5,
  281. $sourceBottomRightX,
  282. $sourceBottomRightY,
  283. 3.5,
  284. $dimMinusThree,
  285. $nw->getX(),
  286. $nw->getY(),
  287. $ne->getX(),
  288. $ne->getY(),
  289. $bottomRightX,
  290. $bottomRightY,
  291. $sw->getX(),
  292. $sw->getY(),
  293. );
  294. }
  295. }