FinderPatternFinder.php 22 KB

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