FinderPattern.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Class FinderPattern
  4. *
  5. * @created 17.01.2021
  6. * @author ZXing Authors
  7. * @author Smiley <smiley@chillerlan.net>
  8. * @copyright 2021 Smiley
  9. * @license Apache-2.0
  10. */
  11. declare(strict_types=1);
  12. namespace chillerlan\QRCode\Detector;
  13. use function sqrt;
  14. /**
  15. * Encapsulates a finder pattern, which are the three square patterns found in
  16. * the corners of QR Codes. It also encapsulates a count of similar finder patterns,
  17. * as a convenience to the finder's bookkeeping.
  18. *
  19. * @author Sean Owen
  20. */
  21. final class FinderPattern extends ResultPoint{
  22. private int $count;
  23. public function __construct(float $posX, float $posY, float $estimatedModuleSize, int|null $count = null){
  24. parent::__construct($posX, $posY, $estimatedModuleSize);
  25. $this->count = ($count ?? 1);
  26. }
  27. public function getCount():int{
  28. return $this->count;
  29. }
  30. /**
  31. * @param \chillerlan\QRCode\Detector\FinderPattern $b second pattern
  32. *
  33. * @return float distance between two points
  34. */
  35. public function getDistance(FinderPattern $b):float{
  36. return self::distance($this->x, $this->y, $b->x, $b->y);
  37. }
  38. /**
  39. * Get square of distance between a and b.
  40. */
  41. public function getSquaredDistance(FinderPattern $b):float{
  42. return self::squaredDistance($this->x, $this->y, $b->x, $b->y);
  43. }
  44. /**
  45. * Combines this object's current estimate of a finder pattern position and module size
  46. * with a new estimate. It returns a new FinderPattern containing a weighted average
  47. * based on count.
  48. */
  49. public function combineEstimate(float $i, float $j, float $newModuleSize):static{
  50. $combinedCount = ($this->count + 1);
  51. return new self(
  52. ($this->count * $this->x + $j) / $combinedCount,
  53. ($this->count * $this->y + $i) / $combinedCount,
  54. ($this->count * $this->estimatedModuleSize + $newModuleSize) / $combinedCount,
  55. $combinedCount,
  56. );
  57. }
  58. private static function squaredDistance(float $aX, float $aY, float $bX, float $bY):float{
  59. $xDiff = ($aX - $bX);
  60. $yDiff = ($aY - $bY);
  61. return ($xDiff * $xDiff + $yDiff * $yDiff);
  62. }
  63. public static function distance(float $aX, float $aY, float $bX, float $bY):float{
  64. return sqrt(self::squaredDistance($aX, $aY, $bX, $bY));
  65. }
  66. }