FinderPatternFinder.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. <?php
  2. /**
  3. * Class FinderPatternFinder
  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. namespace chillerlan\QRCode\Detector;
  12. use chillerlan\QRCode\Decoder\BitMatrix;
  13. use function abs, count, intdiv, usort;
  14. use const PHP_FLOAT_MAX;
  15. /**
  16. * This class attempts to find finder patterns in a QR Code. Finder patterns are the square
  17. * markers at three corners of a QR Code.
  18. *
  19. * This class is thread-safe but not reentrant. Each thread must allocate its own object.
  20. *
  21. * @author Sean Owen
  22. */
  23. final class FinderPatternFinder{
  24. private const MIN_SKIP = 2;
  25. private const MAX_MODULES = 177; // 1 pixel/module times 3 modules/center
  26. private const CENTER_QUORUM = 2; // support up to version 10 for mobile clients
  27. private BitMatrix $matrix;
  28. /** @var \chillerlan\QRCode\Detector\FinderPattern[] */
  29. private array $possibleCenters;
  30. private bool $hasSkipped = false;
  31. /**
  32. * Creates a finder that will search the image for three finder patterns.
  33. *
  34. * @param BitMatrix $matrix image to search
  35. */
  36. public function __construct(BitMatrix $matrix){
  37. $this->matrix = $matrix;
  38. $this->possibleCenters = [];
  39. }
  40. /**
  41. * @return \chillerlan\QRCode\Detector\FinderPattern[]
  42. */
  43. public function find():array{
  44. $dimension = $this->matrix->getSize();
  45. // We are looking for black/white/black/white/black modules in
  46. // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
  47. // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
  48. // image, and then account for the center being 3 modules in size. This gives the smallest
  49. // number of pixels the center could be, so skip this often.
  50. $iSkip = intdiv((3 * $dimension), (4 * self::MAX_MODULES));
  51. if($iSkip < self::MIN_SKIP){
  52. $iSkip = self::MIN_SKIP;
  53. }
  54. $done = false;
  55. for($i = ($iSkip - 1); ($i < $dimension) && !$done; $i += $iSkip){
  56. // Get a row of black/white values
  57. $stateCount = $this->getCrossCheckStateCount();
  58. $currentState = 0;
  59. for($j = 0; $j < $dimension; $j++){
  60. // Black pixel
  61. if($this->matrix->check($j, $i)){
  62. // Counting white pixels
  63. if(($currentState & 1) === 1){
  64. $currentState++;
  65. }
  66. $stateCount[$currentState]++;
  67. }
  68. // White pixel
  69. else{
  70. // Counting black pixels
  71. if(($currentState & 1) === 0){
  72. // A winner?
  73. if($currentState === 4){
  74. // Yes
  75. if($this->foundPatternCross($stateCount)){
  76. $confirmed = $this->handlePossibleCenter($stateCount, $i, $j);
  77. if($confirmed){
  78. // Start examining every other line. Checking each line turned out to be too
  79. // expensive and didn't improve performance.
  80. $iSkip = 3;
  81. if($this->hasSkipped){
  82. $done = $this->haveMultiplyConfirmedCenters();
  83. }
  84. else{
  85. $rowSkip = $this->findRowSkip();
  86. if($rowSkip > $stateCount[2]){
  87. // Skip rows between row of lower confirmed center
  88. // and top of presumed third confirmed center
  89. // but back up a bit to get a full chance of detecting
  90. // it, entire width of center of finder pattern
  91. // Skip by rowSkip, but back off by $stateCount[2] (size of last center
  92. // of pattern we saw) to be conservative, and also back off by iSkip which
  93. // is about to be re-added
  94. $i += ($rowSkip - $stateCount[2] - $iSkip);
  95. $j = ($dimension - 1);
  96. }
  97. }
  98. }
  99. else{
  100. $stateCount = $this->doShiftCounts2($stateCount);
  101. $currentState = 3;
  102. continue;
  103. }
  104. // Clear state to start looking again
  105. $currentState = 0;
  106. $stateCount = $this->getCrossCheckStateCount();
  107. }
  108. // No, shift counts back by two
  109. else{
  110. $stateCount = $this->doShiftCounts2($stateCount);
  111. $currentState = 3;
  112. }
  113. }
  114. else{
  115. $stateCount[++$currentState]++;
  116. }
  117. }
  118. // Counting white pixels
  119. else{
  120. $stateCount[$currentState]++;
  121. }
  122. }
  123. }
  124. if($this->foundPatternCross($stateCount)){
  125. $confirmed = $this->handlePossibleCenter($stateCount, $i, $dimension);
  126. if($confirmed){
  127. $iSkip = $stateCount[0];
  128. if($this->hasSkipped){
  129. // Found a third one
  130. $done = $this->haveMultiplyConfirmedCenters();
  131. }
  132. }
  133. }
  134. }
  135. return $this->orderBestPatterns($this->selectBestPatterns());
  136. }
  137. /**
  138. * @return int[]
  139. */
  140. private function getCrossCheckStateCount():array{
  141. return [0, 0, 0, 0, 0];
  142. }
  143. /**
  144. * @param int[] $stateCount
  145. *
  146. * @return int[]
  147. */
  148. private function doShiftCounts2(array $stateCount):array{
  149. $stateCount[0] = $stateCount[2];
  150. $stateCount[1] = $stateCount[3];
  151. $stateCount[2] = $stateCount[4];
  152. $stateCount[3] = 1;
  153. $stateCount[4] = 0;
  154. return $stateCount;
  155. }
  156. /**
  157. * Given a count of black/white/black/white/black pixels just seen and an end position,
  158. * figures the location of the center of this run.
  159. *
  160. * @param int[] $stateCount
  161. */
  162. private function centerFromEnd(array $stateCount, int $end):float{
  163. return (float)(($end - $stateCount[4] - $stateCount[3]) - $stateCount[2] / 2);
  164. }
  165. /**
  166. * @param int[] $stateCount
  167. */
  168. private function foundPatternCross(array $stateCount):bool{
  169. // Allow less than 50% variance from 1-1-3-1-1 proportions
  170. return $this->foundPatternVariance($stateCount, 2.0);
  171. }
  172. /**
  173. * @param int[] $stateCount
  174. */
  175. private function foundPatternDiagonal(array $stateCount):bool{
  176. // Allow less than 75% variance from 1-1-3-1-1 proportions
  177. return $this->foundPatternVariance($stateCount, 1.333);
  178. }
  179. /**
  180. * @param int[] $stateCount count of black/white/black/white/black pixels just read
  181. *
  182. * @return bool true if the proportions of the counts is close enough to the 1/1/3/1/1 ratios
  183. * used by finder patterns to be considered a match
  184. */
  185. private function foundPatternVariance(array $stateCount, float $variance):bool{
  186. $totalModuleSize = 0;
  187. for($i = 0; $i < 5; $i++){
  188. $count = $stateCount[$i];
  189. if($count === 0){
  190. return false;
  191. }
  192. $totalModuleSize += $count;
  193. }
  194. if($totalModuleSize < 7){
  195. return false;
  196. }
  197. $moduleSize = ($totalModuleSize / 7.0);
  198. $maxVariance = ($moduleSize / $variance);
  199. return
  200. abs($moduleSize - $stateCount[0]) < $maxVariance
  201. && abs($moduleSize - $stateCount[1]) < $maxVariance
  202. && abs(3.0 * $moduleSize - $stateCount[2]) < (3 * $maxVariance)
  203. && abs($moduleSize - $stateCount[3]) < $maxVariance
  204. && abs($moduleSize - $stateCount[4]) < $maxVariance;
  205. }
  206. /**
  207. * After a vertical and horizontal scan finds a potential finder pattern, this method
  208. * "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
  209. * finder pattern to see if the same proportion is detected.
  210. *
  211. * @param int $centerI row where a finder pattern was detected
  212. * @param int $centerJ center of the section that appears to cross a finder pattern
  213. *
  214. * @return bool true if proportions are withing expected limits
  215. */
  216. private function crossCheckDiagonal(int $centerI, int $centerJ):bool{
  217. $stateCount = $this->getCrossCheckStateCount();
  218. // Start counting up, left from center finding black center mass
  219. $i = 0;
  220. while($centerI >= $i && $centerJ >= $i && $this->matrix->check(($centerJ - $i), ($centerI - $i))){
  221. $stateCount[2]++;
  222. $i++;
  223. }
  224. if($stateCount[2] === 0){
  225. return false;
  226. }
  227. // Continue up, left finding white space
  228. while($centerI >= $i && $centerJ >= $i && !$this->matrix->check(($centerJ - $i), ($centerI - $i))){
  229. $stateCount[1]++;
  230. $i++;
  231. }
  232. if($stateCount[1] === 0){
  233. return false;
  234. }
  235. // Continue up, left finding black border
  236. while($centerI >= $i && $centerJ >= $i && $this->matrix->check(($centerJ - $i), ($centerI - $i))){
  237. $stateCount[0]++;
  238. $i++;
  239. }
  240. if($stateCount[0] === 0){
  241. return false;
  242. }
  243. $dimension = $this->matrix->getSize();
  244. // Now also count down, right from center
  245. $i = 1;
  246. while(($centerI + $i) < $dimension && ($centerJ + $i) < $dimension && $this->matrix->check(($centerJ + $i), ($centerI + $i))){
  247. $stateCount[2]++;
  248. $i++;
  249. }
  250. while(($centerI + $i) < $dimension && ($centerJ + $i) < $dimension && !$this->matrix->check(($centerJ + $i), ($centerI + $i))){
  251. $stateCount[3]++;
  252. $i++;
  253. }
  254. if($stateCount[3] === 0){
  255. return false;
  256. }
  257. while(($centerI + $i) < $dimension && ($centerJ + $i) < $dimension && $this->matrix->check(($centerJ + $i), ($centerI + $i))){
  258. $stateCount[4]++;
  259. $i++;
  260. }
  261. if($stateCount[4] === 0){
  262. return false;
  263. }
  264. return $this->foundPatternDiagonal($stateCount);
  265. }
  266. /**
  267. * After a horizontal scan finds a potential finder pattern, this method
  268. * "cross-checks" by scanning down vertically through the center of the possible
  269. * finder pattern to see if the same proportion is detected.
  270. *
  271. * @param int $startI row where a finder pattern was detected
  272. * @param int $centerJ center of the section that appears to cross a finder pattern
  273. * @param int $maxCount maximum reasonable number of modules that should be
  274. * observed in any reading state, based on the results of the horizontal scan
  275. * @param int $originalStateCountTotal
  276. *
  277. * @return float|null vertical center of finder pattern, or null if not found
  278. * @noinspection DuplicatedCode
  279. */
  280. private function crossCheckVertical(int $startI, int $centerJ, int $maxCount, int $originalStateCountTotal):float|null{
  281. $maxI = $this->matrix->getSize();
  282. $stateCount = $this->getCrossCheckStateCount();
  283. // Start counting up from center
  284. $i = $startI;
  285. while($i >= 0 && $this->matrix->check($centerJ, $i)){
  286. $stateCount[2]++;
  287. $i--;
  288. }
  289. if($i < 0){
  290. return null;
  291. }
  292. while($i >= 0 && !$this->matrix->check($centerJ, $i) && $stateCount[1] <= $maxCount){
  293. $stateCount[1]++;
  294. $i--;
  295. }
  296. // If already too many modules in this state or ran off the edge:
  297. if($i < 0 || $stateCount[1] > $maxCount){
  298. return null;
  299. }
  300. while($i >= 0 && $this->matrix->check($centerJ, $i) && $stateCount[0] <= $maxCount){
  301. $stateCount[0]++;
  302. $i--;
  303. }
  304. if($stateCount[0] > $maxCount){
  305. return null;
  306. }
  307. // Now also count down from center
  308. $i = ($startI + 1);
  309. while($i < $maxI && $this->matrix->check($centerJ, $i)){
  310. $stateCount[2]++;
  311. $i++;
  312. }
  313. if($i === $maxI){
  314. return null;
  315. }
  316. while($i < $maxI && !$this->matrix->check($centerJ, $i) && $stateCount[3] < $maxCount){
  317. $stateCount[3]++;
  318. $i++;
  319. }
  320. if($i === $maxI || $stateCount[3] >= $maxCount){
  321. return null;
  322. }
  323. while($i < $maxI && $this->matrix->check($centerJ, $i) && $stateCount[4] < $maxCount){
  324. $stateCount[4]++;
  325. $i++;
  326. }
  327. if($stateCount[4] >= $maxCount){
  328. return null;
  329. }
  330. // If we found a finder-pattern-like section, but its size is more than 40% different from
  331. // the original, assume it's a false positive
  332. $stateCountTotal = ($stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] + $stateCount[4]);
  333. if((5 * abs($stateCountTotal - $originalStateCountTotal)) >= (2 * $originalStateCountTotal)){
  334. return null;
  335. }
  336. if(!$this->foundPatternCross($stateCount)){
  337. return null;
  338. }
  339. return $this->centerFromEnd($stateCount, $i);
  340. }
  341. /**
  342. * Like #crossCheckVertical(int, int, int, int), and in fact is basically identical,
  343. * except it reads horizontally instead of vertically. This is used to cross-cross
  344. * check a vertical cross-check and locate the real center of the alignment pattern.
  345. * @noinspection DuplicatedCode
  346. */
  347. private function crossCheckHorizontal(int $startJ, int $centerI, int $maxCount, int $originalStateCountTotal):float|null{
  348. $maxJ = $this->matrix->getSize();
  349. $stateCount = $this->getCrossCheckStateCount();
  350. $j = $startJ;
  351. while($j >= 0 && $this->matrix->check($j, $centerI)){
  352. $stateCount[2]++;
  353. $j--;
  354. }
  355. if($j < 0){
  356. return null;
  357. }
  358. while($j >= 0 && !$this->matrix->check($j, $centerI) && $stateCount[1] <= $maxCount){
  359. $stateCount[1]++;
  360. $j--;
  361. }
  362. if($j < 0 || $stateCount[1] > $maxCount){
  363. return null;
  364. }
  365. while($j >= 0 && $this->matrix->check($j, $centerI) && $stateCount[0] <= $maxCount){
  366. $stateCount[0]++;
  367. $j--;
  368. }
  369. if($stateCount[0] > $maxCount){
  370. return null;
  371. }
  372. $j = ($startJ + 1);
  373. while($j < $maxJ && $this->matrix->check($j, $centerI)){
  374. $stateCount[2]++;
  375. $j++;
  376. }
  377. if($j === $maxJ){
  378. return null;
  379. }
  380. while($j < $maxJ && !$this->matrix->check($j, $centerI) && $stateCount[3] < $maxCount){
  381. $stateCount[3]++;
  382. $j++;
  383. }
  384. if($j === $maxJ || $stateCount[3] >= $maxCount){
  385. return null;
  386. }
  387. while($j < $maxJ && $this->matrix->check($j, $centerI) && $stateCount[4] < $maxCount){
  388. $stateCount[4]++;
  389. $j++;
  390. }
  391. if($stateCount[4] >= $maxCount){
  392. return null;
  393. }
  394. // If we found a finder-pattern-like section, but its size is significantly different from
  395. // the original, assume it's a false positive
  396. $stateCountTotal = ($stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] + $stateCount[4]);
  397. if((5 * abs($stateCountTotal - $originalStateCountTotal)) >= $originalStateCountTotal){
  398. return null;
  399. }
  400. if(!$this->foundPatternCross($stateCount)){
  401. return null;
  402. }
  403. return $this->centerFromEnd($stateCount, $j);
  404. }
  405. /**
  406. * This is called when a horizontal scan finds a possible alignment pattern. It will
  407. * cross-check with a vertical scan, and if successful, will, ah, cross-cross-check
  408. * with another horizontal scan. This is needed primarily to locate the real horizontal
  409. * center of the pattern in cases of extreme skew.
  410. * And then we cross-cross-cross check with another diagonal scan.
  411. *
  412. * If that succeeds the finder pattern location is added to a list that tracks
  413. * the number of times each location has been nearly-matched as a finder pattern.
  414. * Each additional find is more evidence that the location is in fact a finder
  415. * pattern center
  416. *
  417. * @param int[] $stateCount reading state module counts from horizontal scan
  418. * @param int $i row where finder pattern may be found
  419. * @param int $j end of possible finder pattern in row
  420. *
  421. * @return bool if a finder pattern candidate was found this time
  422. */
  423. private function handlePossibleCenter(array $stateCount, int $i, int $j):bool{
  424. $stateCountTotal = ($stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] + $stateCount[4]);
  425. $centerJ = $this->centerFromEnd($stateCount, $j);
  426. $centerI = $this->crossCheckVertical($i, (int)$centerJ, $stateCount[2], $stateCountTotal);
  427. if($centerI !== null){
  428. // Re-cross check
  429. $centerJ = $this->crossCheckHorizontal((int)$centerJ, (int)$centerI, $stateCount[2], $stateCountTotal);
  430. if($centerJ !== null && ($this->crossCheckDiagonal((int)$centerI, (int)$centerJ))){
  431. $estimatedModuleSize = ($stateCountTotal / 7.0);
  432. $found = false;
  433. // cautious (was in for fool in which $this->possibleCenters is updated)
  434. $count = count($this->possibleCenters);
  435. for($index = 0; $index < $count; $index++){
  436. $center = $this->possibleCenters[$index];
  437. // Look for about the same center and module size:
  438. if($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)){
  439. $this->possibleCenters[$index] = $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
  440. $found = true;
  441. break;
  442. }
  443. }
  444. if(!$found){
  445. $point = new FinderPattern($centerJ, $centerI, $estimatedModuleSize);
  446. $this->possibleCenters[] = $point;
  447. }
  448. return true;
  449. }
  450. }
  451. return false;
  452. }
  453. /**
  454. * @return int number of rows we could safely skip during scanning, based on the first
  455. * two finder patterns that have been located. In some cases their position will
  456. * allow us to infer that the third pattern must lie below a certain point farther
  457. * down in the image.
  458. */
  459. private function findRowSkip():int{
  460. $max = count($this->possibleCenters);
  461. if($max <= 1){
  462. return 0;
  463. }
  464. $firstConfirmedCenter = null;
  465. foreach($this->possibleCenters as $center){
  466. if($center->getCount() >= self::CENTER_QUORUM){
  467. if($firstConfirmedCenter === null){
  468. $firstConfirmedCenter = $center;
  469. }
  470. else{
  471. // We have two confirmed centers
  472. // How far down can we skip before resuming looking for the next
  473. // pattern? In the worst case, only the difference between the
  474. // difference in the x / y coordinates of the two centers.
  475. // This is the case where you find top left last.
  476. $this->hasSkipped = true;
  477. return (int)((abs($firstConfirmedCenter->getX() - $center->getX()) -
  478. abs($firstConfirmedCenter->getY() - $center->getY())) / 2);
  479. }
  480. }
  481. }
  482. return 0;
  483. }
  484. /**
  485. * @return bool true if we have found at least 3 finder patterns that have been detected
  486. * at least #CENTER_QUORUM times each, and, the estimated module size of the
  487. * candidates is "pretty similar"
  488. */
  489. private function haveMultiplyConfirmedCenters():bool{
  490. $confirmedCount = 0;
  491. $totalModuleSize = 0.0;
  492. $max = count($this->possibleCenters);
  493. foreach($this->possibleCenters as $pattern){
  494. if($pattern->getCount() >= self::CENTER_QUORUM){
  495. $confirmedCount++;
  496. $totalModuleSize += $pattern->getEstimatedModuleSize();
  497. }
  498. }
  499. if($confirmedCount < 3){
  500. return false;
  501. }
  502. // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
  503. // and that we need to keep looking. We detect this by asking if the estimated module sizes
  504. // vary too much. We arbitrarily say that when the total deviation from average exceeds
  505. // 5% of the total module size estimates, it's too much.
  506. $average = ($totalModuleSize / (float)$max);
  507. $totalDeviation = 0.0;
  508. foreach($this->possibleCenters as $pattern){
  509. $totalDeviation += abs($pattern->getEstimatedModuleSize() - $average);
  510. }
  511. return $totalDeviation <= (0.05 * $totalModuleSize);
  512. }
  513. /**
  514. * @return \chillerlan\QRCode\Detector\FinderPattern[] the 3 best FinderPatterns from our list of candidates. The "best" are
  515. * those that have been detected at least #CENTER_QUORUM times, and whose module
  516. * size differs from the average among those patterns the least
  517. * @throws \chillerlan\QRCode\Detector\QRCodeDetectorException if 3 such finder patterns do not exist
  518. */
  519. private function selectBestPatterns():array{
  520. $startSize = count($this->possibleCenters);
  521. if($startSize < 3){
  522. throw new QRCodeDetectorException('could not find enough finder patterns');
  523. }
  524. usort(
  525. $this->possibleCenters,
  526. fn(FinderPattern $a, FinderPattern $b) => ($a->getEstimatedModuleSize() <=> $b->getEstimatedModuleSize())
  527. );
  528. $distortion = PHP_FLOAT_MAX;
  529. $bestPatterns = [];
  530. for($i = 0; $i < ($startSize - 2); $i++){
  531. $fpi = $this->possibleCenters[$i];
  532. $minModuleSize = $fpi->getEstimatedModuleSize();
  533. for($j = ($i + 1); $j < ($startSize - 1); $j++){
  534. $fpj = $this->possibleCenters[$j];
  535. $squares0 = $fpi->getSquaredDistance($fpj);
  536. for($k = ($j + 1); $k < $startSize; $k++){
  537. $fpk = $this->possibleCenters[$k];
  538. $maxModuleSize = $fpk->getEstimatedModuleSize();
  539. // module size is not similar
  540. if($maxModuleSize > ($minModuleSize * 1.4)){
  541. continue;
  542. }
  543. $a = $squares0;
  544. $b = $fpj->getSquaredDistance($fpk);
  545. $c = $fpi->getSquaredDistance($fpk);
  546. // sorts ascending - inlined
  547. if($a < $b){
  548. if($b > $c){
  549. if($a < $c){
  550. $temp = $b;
  551. $b = $c;
  552. $c = $temp;
  553. }
  554. else{
  555. $temp = $a;
  556. $a = $c;
  557. $c = $b;
  558. $b = $temp;
  559. }
  560. }
  561. }
  562. else{
  563. if($b < $c){
  564. if($a < $c){
  565. $temp = $a;
  566. $a = $b;
  567. $b = $temp;
  568. }
  569. else{
  570. $temp = $a;
  571. $a = $b;
  572. $b = $c;
  573. $c = $temp;
  574. }
  575. }
  576. else{
  577. $temp = $a;
  578. $a = $c;
  579. $c = $temp;
  580. }
  581. }
  582. // a^2 + b^2 = c^2 (Pythagorean theorem), and a = b (isosceles triangle).
  583. // Since any right triangle satisfies the formula c^2 - b^2 - a^2 = 0,
  584. // we need to check both two equal sides separately.
  585. // The value of |c^2 - 2 * b^2| + |c^2 - 2 * a^2| increases as dissimilarity
  586. // from isosceles right triangle.
  587. $d = (abs($c - 2 * $b) + abs($c - 2 * $a));
  588. if($d < $distortion){
  589. $distortion = $d;
  590. $bestPatterns = [$fpi, $fpj, $fpk];
  591. }
  592. }
  593. }
  594. }
  595. if($distortion === PHP_FLOAT_MAX){
  596. throw new QRCodeDetectorException('finder patterns may be too distorted');
  597. }
  598. return $bestPatterns;
  599. }
  600. /**
  601. * Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
  602. * and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
  603. *
  604. * @param \chillerlan\QRCode\Detector\FinderPattern[] $patterns array of three FinderPattern to order
  605. *
  606. * @return \chillerlan\QRCode\Detector\FinderPattern[]
  607. */
  608. private function orderBestPatterns(array $patterns):array{
  609. // Find distances between pattern centers
  610. $zeroOneDistance = $patterns[0]->getDistance($patterns[1]);
  611. $oneTwoDistance = $patterns[1]->getDistance($patterns[2]);
  612. $zeroTwoDistance = $patterns[0]->getDistance($patterns[2]);
  613. // Assume one closest to other two is B; A and C will just be guesses at first
  614. if($oneTwoDistance >= $zeroOneDistance && $oneTwoDistance >= $zeroTwoDistance){
  615. [$pointB, $pointA, $pointC] = $patterns;
  616. }
  617. elseif($zeroTwoDistance >= $oneTwoDistance && $zeroTwoDistance >= $zeroOneDistance){
  618. [$pointA, $pointB, $pointC] = $patterns;
  619. }
  620. else{
  621. [$pointA, $pointC, $pointB] = $patterns;
  622. }
  623. // Use cross product to figure out whether A and C are correct or flipped.
  624. // This asks whether BC x BA has a positive z component, which is the arrangement
  625. // we want for A, B, C. If it's negative, then we've got it flipped around and
  626. // should swap A and C.
  627. if($this->crossProductZ($pointA, $pointB, $pointC) < 0.0){
  628. $temp = $pointA;
  629. $pointA = $pointC;
  630. $pointC = $temp;
  631. }
  632. return [$pointA, $pointB, $pointC];
  633. }
  634. /**
  635. * Returns the z component of the cross product between vectors BC and BA.
  636. */
  637. private function crossProductZ(FinderPattern $pointA, FinderPattern $pointB, FinderPattern $pointC):float{
  638. $bX = $pointB->getX();
  639. $bY = $pointB->getY();
  640. return ((($pointC->getX() - $bX) * ($pointA->getY() - $bY)) - (($pointC->getY() - $bY) * ($pointA->getX() - $bX)));
  641. }
  642. }