FinderPatternFinder.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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\Common\BitMatrix;
  19. use Zxing\NotFoundException;
  20. use Zxing\ResultPoint;
  21. /**
  22. * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
  23. * markers at three corners of a QR Code.</p>
  24. *
  25. * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
  26. *
  27. * @author Sean Owen
  28. */
  29. class FinderPatternFinder
  30. {
  31. protected static int $MIN_SKIP = 3;
  32. protected static int $MAX_MODULES = 57; // 1 pixel/module times 3 modules/center
  33. private static int $CENTER_QUORUM = 2;
  34. private ?float $average = null;
  35. private array $possibleCenters = []; //private final List<FinderPattern> possibleCenters;
  36. private bool $hasSkipped = false;
  37. /**
  38. * @var mixed|int[]
  39. */
  40. private $crossCheckStateCount;
  41. /**
  42. * <p>Creates a finder that will search the image for three finder patterns.</p>
  43. *
  44. * @param BitMatrix $image image to search
  45. */
  46. public function __construct(private $image, private $resultPointCallback = null)
  47. {
  48. //new ArrayList<>();
  49. $this->crossCheckStateCount = fill_array(0, 5, 0);
  50. }
  51. final public function find($hints): \Zxing\Qrcode\Detector\FinderPatternInfo
  52. {/*final FinderPatternInfo find(Map<DecodeHintType,?> hints) throws NotFoundException {*/
  53. $tryHarder = $hints != null && $hints['TRY_HARDER'];
  54. $pureBarcode = $hints != null && $hints['PURE_BARCODE'];
  55. $maxI = $this->image->getHeight();
  56. $maxJ = $this->image->getWidth();
  57. // We are looking for black/white/black/white/black modules in
  58. // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
  59. // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
  60. // image, and then account for the center being 3 modules in size. This gives the smallest
  61. // number of pixels the center could be, so skip this often. When trying harder, look for all
  62. // QR versions regardless of how dense they are.
  63. $iSkip = (int)((3 * $maxI) / (4 * self::$MAX_MODULES));
  64. if ($iSkip < self::$MIN_SKIP || $tryHarder) {
  65. $iSkip = self::$MIN_SKIP;
  66. }
  67. $done = false;
  68. $stateCount = [];
  69. for ($i = $iSkip - 1; $i < $maxI && !$done; $i += $iSkip) {
  70. // Get a row of black/white values
  71. $stateCount[0] = 0;
  72. $stateCount[1] = 0;
  73. $stateCount[2] = 0;
  74. $stateCount[3] = 0;
  75. $stateCount[4] = 0;
  76. $currentState = 0;
  77. for ($j = 0; $j < $maxJ; $j++) {
  78. if ($this->image->get($j, $i)) {
  79. // Black pixel
  80. if (($currentState & 1) == 1) { // Counting white pixels
  81. $currentState++;
  82. }
  83. $stateCount[$currentState]++;
  84. } else { // White pixel
  85. if (($currentState & 1) == 0) { // Counting black pixels
  86. if ($currentState == 4) { // A winner?
  87. if (self::foundPatternCross($stateCount)) { // Yes
  88. $confirmed = $this->handlePossibleCenter($stateCount, $i, $j, $pureBarcode);
  89. if ($confirmed) {
  90. // Start examining every other line. Checking each line turned out to be too
  91. // expensive and didn't improve performance.
  92. $iSkip = 3;
  93. if ($this->hasSkipped) {
  94. $done = $this->haveMultiplyConfirmedCenters();
  95. } else {
  96. $rowSkip = $this->findRowSkip();
  97. if ($rowSkip > $stateCount[2]) {
  98. // Skip rows between row of lower confirmed center
  99. // and top of presumed third confirmed center
  100. // but back up a bit to get a full chance of detecting
  101. // it, entire width of center of finder pattern
  102. // Skip by rowSkip, but back off by $stateCount[2] (size of last center
  103. // of pattern we saw) to be conservative, and also back off by iSkip which
  104. // is about to be re-added
  105. $i += $rowSkip - $stateCount[2] - $iSkip;
  106. $j = $maxJ - 1;
  107. }
  108. }
  109. } else {
  110. $stateCount[0] = $stateCount[2];
  111. $stateCount[1] = $stateCount[3];
  112. $stateCount[2] = $stateCount[4];
  113. $stateCount[3] = 1;
  114. $stateCount[4] = 0;
  115. $currentState = 3;
  116. continue;
  117. }
  118. // Clear state to start looking again
  119. $currentState = 0;
  120. $stateCount[0] = 0;
  121. $stateCount[1] = 0;
  122. $stateCount[2] = 0;
  123. $stateCount[3] = 0;
  124. $stateCount[4] = 0;
  125. } else { // No, shift counts back by two
  126. $stateCount[0] = $stateCount[2];
  127. $stateCount[1] = $stateCount[3];
  128. $stateCount[2] = $stateCount[4];
  129. $stateCount[3] = 1;
  130. $stateCount[4] = 0;
  131. $currentState = 3;
  132. }
  133. } else {
  134. $stateCount[++$currentState]++;
  135. }
  136. } else { // Counting white pixels
  137. $stateCount[$currentState]++;
  138. }
  139. }
  140. }
  141. if (self::foundPatternCross($stateCount)) {
  142. $confirmed = $this->handlePossibleCenter($stateCount, $i, $maxJ, $pureBarcode);
  143. if ($confirmed) {
  144. $iSkip = $stateCount[0];
  145. if ($this->hasSkipped) {
  146. // Found a third one
  147. $done = $this->haveMultiplyConfirmedCenters();
  148. }
  149. }
  150. }
  151. }
  152. $patternInfo = $this->selectBestPatterns();
  153. $patternInfo = ResultPoint::orderBestPatterns($patternInfo);
  154. return new FinderPatternInfo($patternInfo);
  155. }
  156. /**
  157. * @param $stateCount ; count of black/white/black/white/black pixels just read
  158. *
  159. * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
  160. * used by finder patterns to be considered a match
  161. */
  162. protected static function foundPatternCross($stateCount)
  163. {
  164. $totalModuleSize = 0;
  165. for ($i = 0; $i < 5; $i++) {
  166. $count = $stateCount[$i];
  167. if ($count == 0) {
  168. return false;
  169. }
  170. $totalModuleSize += $count;
  171. }
  172. if ($totalModuleSize < 7) {
  173. return false;
  174. }
  175. $moduleSize = $totalModuleSize / 7.0;
  176. $maxVariance = $moduleSize / 2.0;
  177. // Allow less than 50% variance from 1-1-3-1-1 proportions
  178. return
  179. abs($moduleSize - $stateCount[0]) < $maxVariance &&
  180. abs($moduleSize - $stateCount[1]) < $maxVariance &&
  181. abs(3.0 * $moduleSize - $stateCount[2]) < 3 * $maxVariance &&
  182. abs($moduleSize - $stateCount[3]) < $maxVariance &&
  183. abs($moduleSize - $stateCount[4]) < $maxVariance;
  184. }
  185. /**
  186. * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
  187. * cross check with a vertical scan, and if successful, will, ah, cross-cross-check
  188. * with another horizontal scan. This is needed primarily to locate the real horizontal
  189. * center of the pattern in cases of extreme skew.
  190. * And then we cross-cross-cross check with another diagonal scan.</p>
  191. *
  192. * <p>If that succeeds the finder pattern location is added to a list that tracks
  193. * the number of times each location has been nearly-matched as a finder pattern.
  194. * Each additional find is more evidence that the location is in fact a finder
  195. * pattern center
  196. *
  197. * @param reading $stateCount state module counts from horizontal scan
  198. * @param row $i where finder pattern may be found
  199. * @param end $j of possible finder pattern in row
  200. * @param true $pureBarcode if in "pure barcode" mode
  201. *
  202. * @return true if a finder pattern candidate was found this time
  203. */
  204. final protected function handlePossibleCenter($stateCount, $i, $j, $pureBarcode)
  205. {
  206. $stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
  207. $stateCount[4];
  208. $centerJ = self::centerFromEnd($stateCount, $j);
  209. $centerI = $this->crossCheckVertical($i, (int)($centerJ), $stateCount[2], $stateCountTotal);
  210. if (!is_nan($centerI)) {
  211. // Re-cross check
  212. $centerJ = $this->crossCheckHorizontal((int)($centerJ), (int)($centerI), $stateCount[2], $stateCountTotal);
  213. if (!is_nan($centerJ) &&
  214. (!$pureBarcode || $this->crossCheckDiagonal((int)($centerI), (int)($centerJ), $stateCount[2], $stateCountTotal))
  215. ) {
  216. $estimatedModuleSize = (float)$stateCountTotal / 7.0;
  217. $found = false;
  218. for ($index = 0; $index < count($this->possibleCenters); $index++) {
  219. $center = $this->possibleCenters[$index];
  220. // Look for about the same center and module size:
  221. if ($center->aboutEquals($estimatedModuleSize, $centerI, $centerJ)) {
  222. $this->possibleCenters[$index] = $center->combineEstimate($centerI, $centerJ, $estimatedModuleSize);
  223. $found = true;
  224. break;
  225. }
  226. }
  227. if (!$found) {
  228. $point = new FinderPattern($centerJ, $centerI, $estimatedModuleSize);
  229. $this->possibleCenters[] = $point;
  230. if ($this->resultPointCallback != null) {
  231. $this->resultPointCallback->foundPossibleResultPoint($point);
  232. }
  233. }
  234. return true;
  235. }
  236. }
  237. return false;
  238. }
  239. /**
  240. * Given a count of black/white/black/white/black pixels just seen and an end position,
  241. * figures the location of the center of this run.
  242. */
  243. private static function centerFromEnd($stateCount, $end)
  244. {
  245. return (float)($end - $stateCount[4] - $stateCount[3]) - $stateCount[2] / 2.0;
  246. }
  247. /**
  248. * <p>After a horizontal scan finds a potential finder pattern, this method
  249. * "cross-checks" by scanning down vertically through the center of the possible
  250. * finder pattern to see if the same proportion is detected.</p>
  251. *
  252. * @param $startI ; row where a finder pattern was detected
  253. * @param $centerJ ; center of the section that appears to cross a finder pattern
  254. * @param $maxCount ; maximum reasonable number of modules that should be
  255. * observed in any reading state, based on the results of the horizontal scan
  256. *
  257. * @return float vertical center of finder pattern, or {@link Float#NaN} if not found
  258. */
  259. private function crossCheckVertical(
  260. $startI,
  261. $centerJ,
  262. $maxCount,
  263. $originalStateCountTotal
  264. )
  265. {
  266. $image = $this->image;
  267. $maxI = $image->getHeight();
  268. $stateCount = $this->getCrossCheckStateCount();
  269. // Start counting up from center
  270. $i = $startI;
  271. while ($i >= 0 && $image->get($centerJ, $i)) {
  272. $stateCount[2]++;
  273. $i--;
  274. }
  275. if ($i < 0) {
  276. return NAN;
  277. }
  278. while ($i >= 0 && !$image->get($centerJ, $i) && $stateCount[1] <= $maxCount) {
  279. $stateCount[1]++;
  280. $i--;
  281. }
  282. // If already too many modules in this state or ran off the edge:
  283. if ($i < 0 || $stateCount[1] > $maxCount) {
  284. return NAN;
  285. }
  286. while ($i >= 0 && $image->get($centerJ, $i) && $stateCount[0] <= $maxCount) {
  287. $stateCount[0]++;
  288. $i--;
  289. }
  290. if ($stateCount[0] > $maxCount) {
  291. return NAN;
  292. }
  293. // Now also count down from center
  294. $i = $startI + 1;
  295. while ($i < $maxI && $image->get($centerJ, $i)) {
  296. $stateCount[2]++;
  297. $i++;
  298. }
  299. if ($i == $maxI) {
  300. return NAN;
  301. }
  302. while ($i < $maxI && !$image->get($centerJ, $i) && $stateCount[3] < $maxCount) {
  303. $stateCount[3]++;
  304. $i++;
  305. }
  306. if ($i == $maxI || $stateCount[3] >= $maxCount) {
  307. return NAN;
  308. }
  309. while ($i < $maxI && $image->get($centerJ, $i) && $stateCount[4] < $maxCount) {
  310. $stateCount[4]++;
  311. $i++;
  312. }
  313. if ($stateCount[4] >= $maxCount) {
  314. return NAN;
  315. }
  316. // If we found a finder-pattern-like section, but its size is more than 40% different than
  317. // the original, assume it's a false positive
  318. $stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
  319. $stateCount[4];
  320. if (5 * abs($stateCountTotal - $originalStateCountTotal) >= 2 * $originalStateCountTotal) {
  321. return NAN;
  322. }
  323. return self::foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $i) : NAN;
  324. }
  325. private function getCrossCheckStateCount()
  326. {
  327. $this->crossCheckStateCount[0] = 0;
  328. $this->crossCheckStateCount[1] = 0;
  329. $this->crossCheckStateCount[2] = 0;
  330. $this->crossCheckStateCount[3] = 0;
  331. $this->crossCheckStateCount[4] = 0;
  332. return $this->crossCheckStateCount;
  333. }
  334. /**
  335. * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
  336. * except it reads horizontally instead of vertically. This is used to cross-cross
  337. * check a vertical cross check and locate the real center of the alignment pattern.</p>
  338. */
  339. private function crossCheckHorizontal(
  340. $startJ,
  341. $centerI,
  342. $maxCount,
  343. $originalStateCountTotal
  344. )
  345. {
  346. $image = $this->image;
  347. $maxJ = $this->image->getWidth();
  348. $stateCount = $this->getCrossCheckStateCount();
  349. $j = $startJ;
  350. while ($j >= 0 && $image->get($j, $centerI)) {
  351. $stateCount[2]++;
  352. $j--;
  353. }
  354. if ($j < 0) {
  355. return NAN;
  356. }
  357. while ($j >= 0 && !$image->get($j, $centerI) && $stateCount[1] <= $maxCount) {
  358. $stateCount[1]++;
  359. $j--;
  360. }
  361. if ($j < 0 || $stateCount[1] > $maxCount) {
  362. return NAN;
  363. }
  364. while ($j >= 0 && $image->get($j, $centerI) && $stateCount[0] <= $maxCount) {
  365. $stateCount[0]++;
  366. $j--;
  367. }
  368. if ($stateCount[0] > $maxCount) {
  369. return NAN;
  370. }
  371. $j = $startJ + 1;
  372. while ($j < $maxJ && $image->get($j, $centerI)) {
  373. $stateCount[2]++;
  374. $j++;
  375. }
  376. if ($j == $maxJ) {
  377. return NAN;
  378. }
  379. while ($j < $maxJ && !$image->get($j, $centerI) && $stateCount[3] < $maxCount) {
  380. $stateCount[3]++;
  381. $j++;
  382. }
  383. if ($j == $maxJ || $stateCount[3] >= $maxCount) {
  384. return NAN;
  385. }
  386. while ($j < $maxJ && $this->image->get($j, $centerI) && $stateCount[4] < $maxCount) {
  387. $stateCount[4]++;
  388. $j++;
  389. }
  390. if ($stateCount[4] >= $maxCount) {
  391. return NAN;
  392. }
  393. // If we found a finder-pattern-like section, but its size is significantly different than
  394. // the original, assume it's a false positive
  395. $stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] +
  396. $stateCount[4];
  397. if (5 * abs($stateCountTotal - $originalStateCountTotal) >= $originalStateCountTotal) {
  398. return NAN;
  399. }
  400. return static::foundPatternCross($stateCount) ? self::centerFromEnd($stateCount, $j) : NAN;
  401. }
  402. /**
  403. * After a vertical and horizontal scan finds a potential finder pattern, this method
  404. * "cross-cross-cross-checks" by scanning down diagonally through the center of the possible
  405. * finder pattern to see if the same proportion is detected.
  406. *
  407. * @param $startI ; row where a finder pattern was detected
  408. * @param $centerJ ; center of the section that appears to cross a finder pattern
  409. * @param $maxCount ; maximum reasonable number of modules that should be
  410. * observed in any reading state, based on the results of the horizontal scan
  411. * @param $originalStateCountTotal ; The original state count total.
  412. *
  413. * @return true if proportions are withing expected limits
  414. */
  415. private function crossCheckDiagonal($startI, $centerJ, $maxCount, $originalStateCountTotal)
  416. {
  417. $stateCount = $this->getCrossCheckStateCount();
  418. // Start counting up, left from center finding black center mass
  419. $i = 0;
  420. $startI = (int)($startI);
  421. $centerJ = (int)($centerJ);
  422. while ($startI >= $i && $centerJ >= $i && $this->image->get($centerJ - $i, $startI - $i)) {
  423. $stateCount[2]++;
  424. $i++;
  425. }
  426. if ($startI < $i || $centerJ < $i) {
  427. return false;
  428. }
  429. // Continue up, left finding white space
  430. while ($startI >= $i && $centerJ >= $i && !$this->image->get($centerJ - $i, $startI - $i) &&
  431. $stateCount[1] <= $maxCount) {
  432. $stateCount[1]++;
  433. $i++;
  434. }
  435. // If already too many modules in this state or ran off the edge:
  436. if ($startI < $i || $centerJ < $i || $stateCount[1] > $maxCount) {
  437. return false;
  438. }
  439. // Continue up, left finding black border
  440. while ($startI >= $i && $centerJ >= $i && $this->image->get($centerJ - $i, $startI - $i) &&
  441. $stateCount[0] <= $maxCount) {
  442. $stateCount[0]++;
  443. $i++;
  444. }
  445. if ($stateCount[0] > $maxCount) {
  446. return false;
  447. }
  448. $maxI = $this->image->getHeight();
  449. $maxJ = $this->image->getWidth();
  450. // Now also count down, right from center
  451. $i = 1;
  452. while ($startI + $i < $maxI && $centerJ + $i < $maxJ && $this->image->get($centerJ + $i, $startI + $i)) {
  453. $stateCount[2]++;
  454. $i++;
  455. }
  456. // Ran off the edge?
  457. if ($startI + $i >= $maxI || $centerJ + $i >= $maxJ) {
  458. return false;
  459. }
  460. while ($startI + $i < $maxI && $centerJ + $i < $maxJ && !$this->image->get($centerJ + $i, $startI + $i) &&
  461. $stateCount[3] < $maxCount) {
  462. $stateCount[3]++;
  463. $i++;
  464. }
  465. if ($startI + $i >= $maxI || $centerJ + $i >= $maxJ || $stateCount[3] >= $maxCount) {
  466. return false;
  467. }
  468. while ($startI + $i < $maxI && $centerJ + $i < $maxJ && $this->image->get($centerJ + $i, $startI + $i) &&
  469. $stateCount[4] < $maxCount) {
  470. $stateCount[4]++;
  471. $i++;
  472. }
  473. if ($stateCount[4] >= $maxCount) {
  474. return false;
  475. }
  476. // If we found a finder-pattern-like section, but its size is more than 100% different than
  477. // the original, assume it's a false positive
  478. $stateCountTotal = $stateCount[0] + $stateCount[1] + $stateCount[2] + $stateCount[3] + $stateCount[4];
  479. return
  480. abs($stateCountTotal - $originalStateCountTotal) < 2 * $originalStateCountTotal &&
  481. self::foundPatternCross($stateCount);
  482. }
  483. /**
  484. * @return true iff we have found at least 3 finder patterns that have been detected
  485. * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
  486. * candidates is "pretty similar"
  487. */
  488. private function haveMultiplyConfirmedCenters()
  489. {
  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 int number of rows we could safely skip during scanning, based on the first
  515. * two finder patterns that have been located. In some cases their position will
  516. * allow us to infer that the third pattern must lie below a certain point farther
  517. * down in the image.
  518. */
  519. private function findRowSkip()
  520. {
  521. $max = count($this->possibleCenters);
  522. if ($max <= 1) {
  523. return 0;
  524. }
  525. $firstConfirmedCenter = null;
  526. foreach ($this->possibleCenters as $center) {
  527. if ($center->getCount() >= self::$CENTER_QUORUM) {
  528. if ($firstConfirmedCenter == null) {
  529. $firstConfirmedCenter = $center;
  530. } else {
  531. // We have two confirmed centers
  532. // How far down can we skip before resuming looking for the next
  533. // pattern? In the worst case, only the difference between the
  534. // difference in the x / y coordinates of the two centers.
  535. // This is the case where you find top left last.
  536. $this->hasSkipped = true;
  537. return (int)((abs($firstConfirmedCenter->getX() - $center->getX()) -
  538. abs($firstConfirmedCenter->getY() - $center->getY())) / 2);
  539. }
  540. }
  541. }
  542. return 0;
  543. }
  544. /**
  545. * @return array the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
  546. * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
  547. * size differs from the average among those patterns the least
  548. * @throws NotFoundException if 3 such finder patterns do not exist
  549. */
  550. private function selectBestPatterns()
  551. {
  552. $startSize = count($this->possibleCenters);
  553. if ($startSize < 3) {
  554. // Couldn't find enough finder patterns
  555. throw new NotFoundException();
  556. }
  557. // Filter outlier possibilities whose module size is too different
  558. if ($startSize > 3) {
  559. // But we can only afford to do so if we have at least 4 possibilities to choose from
  560. $totalModuleSize = 0.0;
  561. $square = 0.0;
  562. foreach ($this->possibleCenters as $center) {
  563. $size = $center->getEstimatedModuleSize();
  564. $totalModuleSize += $size;
  565. $square += $size * $size;
  566. }
  567. $this->average = $totalModuleSize / (float)$startSize;
  568. $stdDev = (float)sqrt($square / $startSize - $this->average * $this->average);
  569. usort($this->possibleCenters, $this->FurthestFromAverageComparator(...));
  570. $limit = max(0.2 * $this->average, $stdDev);
  571. for ($i = 0; $i < count($this->possibleCenters) && count($this->possibleCenters) > 3; $i++) {
  572. $pattern = $this->possibleCenters[$i];
  573. if (abs($pattern->getEstimatedModuleSize() - $this->average) > $limit) {
  574. unset($this->possibleCenters[$i]);//возможно что ключи меняются в java при вызове .remove(i) ???
  575. $this->possibleCenters = array_values($this->possibleCenters);
  576. $i--;
  577. }
  578. }
  579. }
  580. if (count($this->possibleCenters) > 3) {
  581. // Throw away all but those first size candidate points we found.
  582. $totalModuleSize = 0.0;
  583. foreach ($this->possibleCenters as $possibleCenter) {
  584. $totalModuleSize += $possibleCenter->getEstimatedModuleSize();
  585. }
  586. $this->average = $totalModuleSize / (float)count($this->possibleCenters);
  587. usort($this->possibleCenters, $this->CenterComparator(...));
  588. array_slice($this->possibleCenters, 3, count($this->possibleCenters) - 3);
  589. }
  590. return [$this->possibleCenters[0], $this->possibleCenters[1], $this->possibleCenters[2]];
  591. }
  592. /**
  593. * <p>Orders by furthest from average</p>
  594. */
  595. public function FurthestFromAverageComparator($center1, $center2)
  596. {
  597. $dA = abs($center2->getEstimatedModuleSize() - $this->average);
  598. $dB = abs($center1->getEstimatedModuleSize() - $this->average);
  599. if ($dA < $dB) {
  600. return -1;
  601. } elseif ($dA == $dB) {
  602. return 0;
  603. } else {
  604. return 1;
  605. }
  606. }
  607. public function CenterComparator($center1, $center2)
  608. {
  609. if ($center2->getCount() == $center1->getCount()) {
  610. $dA = abs($center2->getEstimatedModuleSize() - $this->average);
  611. $dB = abs($center1->getEstimatedModuleSize() - $this->average);
  612. if ($dA < $dB) {
  613. return 1;
  614. } elseif ($dA == $dB) {
  615. return 0;
  616. } else {
  617. return -1;
  618. }
  619. } else {
  620. return $center2->getCount() - $center1->getCount();
  621. }
  622. }
  623. final protected function getImage()
  624. {
  625. return $this->image;
  626. }
  627. /**
  628. * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
  629. */
  630. //@Override
  631. final protected function getPossibleCenters()
  632. { //List<FinderPattern> getPossibleCenters()
  633. return $this->possibleCenters;
  634. }
  635. }