| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class Detector |
| 4 |
* |
| 5 |
* @created 17.01.2021 |
| 6 |
* @author ZXing Authors |
| 7 |
* @author Smiley <[email protected]> |
| 8 |
* @copyright 2021 Smiley |
| 9 |
* @license Apache-2.0 |
| 10 |
*/ |
| 11 |
declare(strict_types=1); |
| 12 |
|
| 13 |
namespace chillerlan\QRCode\Detector; |
| 14 |
|
| 15 |
use chillerlan\QRCode\Common\{LuminanceSourceInterface, Version}; |
| 16 |
use chillerlan\QRCode\Decoder\{Binarizer, BitMatrix}; |
| 17 |
use function abs, intdiv, is_nan, max, min, round; |
| 18 |
use const NAN; |
| 19 |
|
| 20 |
/** |
| 21 |
* Encapsulates logic that can detect a QR Code in an image, even if the QR Code |
| 22 |
* is rotated or skewed, or partially obscured. |
| 23 |
* |
| 24 |
* @author Sean Owen |
| 25 |
*/ |
| 26 |
final class Detector{ |
| 27 |
|
| 28 |
private BitMatrix $matrix; |
| 29 |
/** @var \chillerlan\QRCode\Detector\FinderPattern[] */ |
| 30 |
private array $finderPatterns = []; |
| 31 |
|
| 32 |
/** |
| 33 |
* Detector constructor. |
| 34 |
*/ |
| 35 |
public function __construct(LuminanceSourceInterface $source){ |
| 36 |
$this->matrix = (new Binarizer($source))->getBlackMatrix(); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* @return \chillerlan\QRCode\Detector\FinderPattern[] |
| 41 |
* |
| 42 |
* @deprecated 6.0.1 This method will be removed. In v7, use the property "Detector::$finderPatterns" instead. |
| 43 |
*/ |
| 44 |
public function getFinderPatterns():array{ |
| 45 |
return $this->finderPatterns; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Detects a QR Code in an image. |
| 50 |
*/ |
| 51 |
public function detect():BitMatrix{ |
| 52 |
$this->finderPatterns = (new FinderPatternFinder($this->matrix))->find(); |
| 53 |
|
| 54 |
[$bottomLeft, $topLeft, $topRight] = $this->finderPatterns; |
| 55 |
|
| 56 |
$moduleSize = $this->calculateModuleSize($topLeft, $topRight, $bottomLeft); |
| 57 |
$dimension = $this->computeDimension($topLeft, $topRight, $bottomLeft, $moduleSize); |
| 58 |
$provisionalVersion = new Version(intdiv(($dimension - 17), 4)); |
| 59 |
$alignmentPattern = null; |
| 60 |
|
| 61 |
// Anything above version 1 has an alignment pattern |
| 62 |
if($provisionalVersion->getAlignmentPattern() !== []){ |
| 63 |
// Guess where a "bottom right" finder pattern would have been |
| 64 |
$bottomRightX = ($topRight->getX() - $topLeft->getX() + $bottomLeft->getX()); |
| 65 |
$bottomRightY = ($topRight->getY() - $topLeft->getY() + $bottomLeft->getY()); |
| 66 |
|
| 67 |
// Estimate that alignment pattern is closer by 3 modules |
| 68 |
// from "bottom right" to known top left location |
| 69 |
$correctionToTopLeft = (1.0 - 3.0 / (float)($provisionalVersion->getDimension() - 7)); |
| 70 |
$estAlignmentX = (int)($topLeft->getX() + $correctionToTopLeft * ($bottomRightX - $topLeft->getX())); |
| 71 |
$estAlignmentY = (int)($topLeft->getY() + $correctionToTopLeft * ($bottomRightY - $topLeft->getY())); |
| 72 |
|
| 73 |
// Kind of arbitrary -- expand search radius before giving up |
| 74 |
for($i = 4; $i <= 16; $i <<= 1){//?????????? |
| 75 |
$alignmentPattern = $this->findAlignmentInRegion($moduleSize, $estAlignmentX, $estAlignmentY, (float)$i); |
| 76 |
|
| 77 |
if($alignmentPattern !== null){ |
| 78 |
break; |
| 79 |
} |
| 80 |
} |
| 81 |
// If we didn't find alignment pattern... well try anyway without it |
| 82 |
} |
| 83 |
|
| 84 |
$transform = $this->createTransform($topLeft, $topRight, $bottomLeft, $dimension, $alignmentPattern); |
| 85 |
|
| 86 |
return (new GridSampler)->sampleGrid($this->matrix, $dimension, $transform); |
| 87 |
} |
| 88 |
|
| 89 |
/** |
| 90 |
* Computes an average estimated module size based on estimated derived from the positions |
| 91 |
* of the three finder patterns. |
| 92 |
* |
| 93 |
* @throws \chillerlan\QRCode\Detector\QRCodeDetectorException |
| 94 |
*/ |
| 95 |
private function calculateModuleSize(FinderPattern $topLeft, FinderPattern $topRight, FinderPattern $bottomLeft):float{ |
| 96 |
// Take the average |
| 97 |
$moduleSize = (( |
| 98 |
$this->calculateModuleSizeOneWay($topLeft, $topRight) + |
| 99 |
$this->calculateModuleSizeOneWay($topLeft, $bottomLeft) |
| 100 |
) / 2.0); |
| 101 |
|
| 102 |
if($moduleSize < 1.0){ |
| 103 |
throw new QRCodeDetectorException('module size < 1.0'); |
| 104 |
} |
| 105 |
|
| 106 |
return $moduleSize; |
| 107 |
} |
| 108 |
|
| 109 |
/** |
| 110 |
* Estimates module size based on two finder patterns -- it uses |
| 111 |
* #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int) to figure the |
| 112 |
* width of each, measuring along the axis between their centers. |
| 113 |
*/ |
| 114 |
private function calculateModuleSizeOneWay(FinderPattern $a, FinderPattern $b):float{ |
| 115 |
|
| 116 |
$moduleSizeEst1 = $this->sizeOfBlackWhiteBlackRunBothWays($a->getX(), $a->getY(), $b->getX(), $b->getY()); |
| 117 |
$moduleSizeEst2 = $this->sizeOfBlackWhiteBlackRunBothWays($b->getX(), $b->getY(), $a->getX(), $a->getY()); |
| 118 |
|
| 119 |
if(is_nan($moduleSizeEst1)){ |
| 120 |
return ($moduleSizeEst2 / 7.0); |
| 121 |
} |
| 122 |
|
| 123 |
if(is_nan($moduleSizeEst2)){ |
| 124 |
return ($moduleSizeEst1 / 7.0); |
| 125 |
} |
| 126 |
// Average them, and divide by 7 since we've counted the width of 3 black modules, |
| 127 |
// and 1 white and 1 black module on either side. Ergo, divide sum by 14. |
| 128 |
return (($moduleSizeEst1 + $moduleSizeEst2) / 14.0); |
| 129 |
} |
| 130 |
|
| 131 |
/** |
| 132 |
* See #sizeOfBlackWhiteBlackRun(int, int, int, int); computes the total width of |
| 133 |
* a finder pattern by looking for a black-white-black run from the center in the direction |
| 134 |
* of another po$(another finder pattern center), and in the opposite direction too. |
| 135 |
* |
| 136 |
* @noinspection DuplicatedCode |
| 137 |
*/ |
| 138 |
private function sizeOfBlackWhiteBlackRunBothWays(float $fromX, float $fromY, float $toX, float $toY):float{ |
| 139 |
$result = $this->sizeOfBlackWhiteBlackRun((int)$fromX, (int)$fromY, (int)$toX, (int)$toY); |
| 140 |
$dimension = $this->matrix->getSize(); |
| 141 |
// Now count other way -- don't run off image though of course |
| 142 |
$scale = 1.0; |
| 143 |
$otherToX = ($fromX - ($toX - $fromX)); |
| 144 |
|
| 145 |
if($otherToX < 0){ |
| 146 |
$scale = ($fromX / ($fromX - $otherToX)); |
| 147 |
$otherToX = 0; |
| 148 |
} |
| 149 |
elseif($otherToX >= $dimension){ |
| 150 |
$scale = (($dimension - 1 - $fromX) / ($otherToX - $fromX)); |
| 151 |
$otherToX = ($dimension - 1); |
| 152 |
} |
| 153 |
|
| 154 |
$otherToY = (int)($fromY - ($toY - $fromY) * $scale); |
| 155 |
$scale = 1.0; |
| 156 |
|
| 157 |
if($otherToY < 0){ |
| 158 |
$scale = ($fromY / ($fromY - $otherToY)); |
| 159 |
$otherToY = 0; |
| 160 |
} |
| 161 |
elseif($otherToY >= $dimension){ |
| 162 |
$scale = (($dimension - 1 - $fromY) / ($otherToY - $fromY)); |
| 163 |
$otherToY = ($dimension - 1); |
| 164 |
} |
| 165 |
|
| 166 |
$otherToX = (int)($fromX + ($otherToX - $fromX) * $scale); |
| 167 |
$result += $this->sizeOfBlackWhiteBlackRun((int)$fromX, (int)$fromY, $otherToX, $otherToY); |
| 168 |
|
| 169 |
// Middle pixel is double-counted this way; subtract 1 |
| 170 |
return ($result - 1.0); |
| 171 |
} |
| 172 |
|
| 173 |
/** |
| 174 |
* This method traces a line from a po$in the image, in the direction towards another point. |
| 175 |
* It begins in a black region, and keeps going until it finds white, then black, then white again. |
| 176 |
* It reports the distance from the start to this point. |
| 177 |
* |
| 178 |
* This is used when figuring out how wide a finder pattern is, when the finder pattern |
| 179 |
* may be skewed or rotated. |
| 180 |
*/ |
| 181 |
private function sizeOfBlackWhiteBlackRun(int $fromX, int $fromY, int $toX, int $toY):float{ |
| 182 |
// Mild variant of Bresenham's algorithm; |
| 183 |
// @see https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm |
| 184 |
$steep = abs($toY - $fromY) > abs($toX - $fromX); |
| 185 |
|
| 186 |
if($steep){ |
| 187 |
$temp = $fromX; |
| 188 |
$fromX = $fromY; |
| 189 |
$fromY = $temp; |
| 190 |
$temp = $toX; |
| 191 |
$toX = $toY; |
| 192 |
$toY = $temp; |
| 193 |
} |
| 194 |
|
| 195 |
$dx = abs($toX - $fromX); |
| 196 |
$dy = abs($toY - $fromY); |
| 197 |
$error = (-$dx / 2); |
| 198 |
$xstep = (($fromX < $toX) ? 1 : -1); |
| 199 |
$ystep = (($fromY < $toY) ? 1 : -1); |
| 200 |
|
| 201 |
// In black pixels, looking for white, first or second time. |
| 202 |
$state = 0; |
| 203 |
// Loop up until x == toX, but not beyond |
| 204 |
$xLimit = ($toX + $xstep); |
| 205 |
|
| 206 |
for($x = $fromX, $y = $fromY; $x !== $xLimit; $x += $xstep){ |
| 207 |
$realX = ($steep) ? $y : $x; |
| 208 |
$realY = ($steep) ? $x : $y; |
| 209 |
|
| 210 |
// Does current pixel mean we have moved white to black or vice versa? |
| 211 |
// Scanning black in state 0,2 and white in state 1, so if we find the wrong |
| 212 |
// color, advance to next state or end if we are in state 2 already |
| 213 |
if(($state === 1) === $this->matrix->check($realX, $realY)){ |
| 214 |
|
| 215 |
if($state === 2){ |
| 216 |
return FinderPattern::distance($x, $y, $fromX, $fromY); |
| 217 |
} |
| 218 |
|
| 219 |
$state++; |
| 220 |
} |
| 221 |
|
| 222 |
$error += $dy; |
| 223 |
|
| 224 |
if($error > 0){ |
| 225 |
|
| 226 |
if($y === $toY){ |
| 227 |
break; |
| 228 |
} |
| 229 |
|
| 230 |
$y += $ystep; |
| 231 |
$error -= $dx; |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
// Found black-white-black; give the benefit of the doubt that the next pixel outside the image |
| 236 |
// is "white" so this last po$at (toX+xStep,toY) is the right ending. This is really a |
| 237 |
// small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this. |
| 238 |
if($state === 2){ |
| 239 |
return FinderPattern::distance(($toX + $xstep), $toY, $fromX, $fromY); |
| 240 |
} |
| 241 |
|
| 242 |
// else we didn't find even black-white-black; no estimate is really possible |
| 243 |
return NAN; |
| 244 |
} |
| 245 |
|
| 246 |
/** |
| 247 |
* Computes the dimension (number of modules on a size) of the QR Code based on the position |
| 248 |
* of the finder patterns and estimated module size. |
| 249 |
* |
| 250 |
* @throws \chillerlan\QRCode\Detector\QRCodeDetectorException |
| 251 |
*/ |
| 252 |
private function computeDimension(FinderPattern $nw, FinderPattern $ne, FinderPattern $sw, float $size):int{ |
| 253 |
$tltrCentersDimension = (int)round($nw->getDistance($ne) / $size); |
| 254 |
$tlblCentersDimension = (int)round($nw->getDistance($sw) / $size); |
| 255 |
$dimension = (int)((($tltrCentersDimension + $tlblCentersDimension) / 2) + 7); |
| 256 |
|
| 257 |
switch($dimension % 4){ |
| 258 |
case 0: |
| 259 |
$dimension++; |
| 260 |
break; |
| 261 |
// 1? do nothing |
| 262 |
case 2: |
| 263 |
$dimension--; |
| 264 |
break; |
| 265 |
case 3: |
| 266 |
throw new QRCodeDetectorException('estimated dimension: '.$dimension); |
| 267 |
} |
| 268 |
|
| 269 |
if(($dimension % 4) !== 1){ |
| 270 |
throw new QRCodeDetectorException('dimension mod 4 is not 1'); |
| 271 |
} |
| 272 |
|
| 273 |
return $dimension; |
| 274 |
} |
| 275 |
|
| 276 |
/** |
| 277 |
* Attempts to locate an alignment pattern in a limited region of the image, which is |
| 278 |
* guessed to contain it. |
| 279 |
* |
| 280 |
* @param float $overallEstModuleSize estimated module size so far |
| 281 |
* @param int $estAlignmentX x coordinate of center of area probably containing alignment pattern |
| 282 |
* @param int $estAlignmentY y coordinate of above |
| 283 |
* @param float $allowanceFactor number of pixels in all directions to search from the center |
| 284 |
* |
| 285 |
* @return \chillerlan\QRCode\Detector\AlignmentPattern|null if found, or null otherwise |
| 286 |
*/ |
| 287 |
private function findAlignmentInRegion( |
| 288 |
float $overallEstModuleSize, |
| 289 |
int $estAlignmentX, |
| 290 |
int $estAlignmentY, |
| 291 |
float $allowanceFactor, |
| 292 |
):AlignmentPattern|null{ |
| 293 |
// Look for an alignment pattern (3 modules in size) around where it should be |
| 294 |
$dimension = $this->matrix->getSize(); |
| 295 |
$allowance = (int)($allowanceFactor * $overallEstModuleSize); |
| 296 |
$alignmentAreaLeftX = max(0, ($estAlignmentX - $allowance)); |
| 297 |
$alignmentAreaRightX = min(($dimension - 1), ($estAlignmentX + $allowance)); |
| 298 |
|
| 299 |
if(($alignmentAreaRightX - $alignmentAreaLeftX) < ($overallEstModuleSize * 3)){ |
| 300 |
return null; |
| 301 |
} |
| 302 |
|
| 303 |
$alignmentAreaTopY = max(0, ($estAlignmentY - $allowance)); |
| 304 |
$alignmentAreaBottomY = min(($dimension - 1), ($estAlignmentY + $allowance)); |
| 305 |
|
| 306 |
if(($alignmentAreaBottomY - $alignmentAreaTopY) < ($overallEstModuleSize * 3)){ |
| 307 |
return null; |
| 308 |
} |
| 309 |
|
| 310 |
return (new AlignmentPatternFinder($this->matrix, $overallEstModuleSize))->find( |
| 311 |
$alignmentAreaLeftX, |
| 312 |
$alignmentAreaTopY, |
| 313 |
($alignmentAreaRightX - $alignmentAreaLeftX), |
| 314 |
($alignmentAreaBottomY - $alignmentAreaTopY), |
| 315 |
); |
| 316 |
} |
| 317 |
|
| 318 |
private function createTransform( |
| 319 |
FinderPattern $nw, |
| 320 |
FinderPattern $ne, |
| 321 |
FinderPattern $sw, |
| 322 |
int $size, |
| 323 |
AlignmentPattern|null $ap = null, |
| 324 |
):PerspectiveTransform{ |
| 325 |
$dimMinusThree = ($size - 3.5); |
| 326 |
|
| 327 |
if($ap instanceof AlignmentPattern){ |
| 328 |
$bottomRightX = $ap->getX(); |
| 329 |
$bottomRightY = $ap->getY(); |
| 330 |
$sourceBottomRightX = ($dimMinusThree - 3.0); |
| 331 |
$sourceBottomRightY = $sourceBottomRightX; |
| 332 |
} |
| 333 |
else{ |
| 334 |
// Don't have an alignment pattern, just make up the bottom-right point |
| 335 |
$bottomRightX = ($ne->getX() - $nw->getX() + $sw->getX()); |
| 336 |
$bottomRightY = ($ne->getY() - $nw->getY() + $sw->getY()); |
| 337 |
$sourceBottomRightX = $dimMinusThree; |
| 338 |
$sourceBottomRightY = $dimMinusThree; |
| 339 |
} |
| 340 |
|
| 341 |
return (new PerspectiveTransform)->quadrilateralToQuadrilateral( |
| 342 |
3.5, |
| 343 |
3.5, |
| 344 |
$dimMinusThree, |
| 345 |
3.5, |
| 346 |
$sourceBottomRightX, |
| 347 |
$sourceBottomRightY, |
| 348 |
3.5, |
| 349 |
$dimMinusThree, |
| 350 |
$nw->getX(), |
| 351 |
$nw->getY(), |
| 352 |
$ne->getX(), |
| 353 |
$ne->getY(), |
| 354 |
$bottomRightX, |
| 355 |
$bottomRightY, |
| 356 |
$sw->getX(), |
| 357 |
$sw->getY(), |
| 358 |
); |
| 359 |
} |
| 360 |
|
| 361 |
} |