FinderPatternFinder.php 28 KB

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