Passed
Push — main ( 3d99ee...53f6dc )
by smiley
10:29
created

GridSampler::sampleGrid()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 45
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 18
nc 8
nop 3
dl 0
loc 45
rs 9.0444
c 1
b 0
f 0
1
<?php
2
/**
3
 * Class GridSampler
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
12
namespace chillerlan\QRCode\Detector;
13
14
use chillerlan\QRCode\Data\QRMatrix;
15
use chillerlan\QRCode\Decoder\BitMatrix;
16
use Throwable;
17
use function array_fill, count, sprintf;
18
19
/**
20
 * Implementations of this class can, given locations of finder patterns for a QR code in an
21
 * image, sample the right points in the image to reconstruct the QR code, accounting for
22
 * perspective distortion. It is abstracted since it is relatively expensive and should be allowed
23
 * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
24
 * Imaging library, but which may not be available in other environments such as J2ME, and vice
25
 * versa.
26
 *
27
 * The implementation used can be controlled by calling #setGridSampler(GridSampler)
28
 * with an instance of a class which implements this interface.
29
 *
30
 * @author Sean Owen
31
 */
32
final class GridSampler{
33
34
	/**
35
	 * Checks a set of points that have been transformed to sample points on an image against
36
	 * the image's dimensions to see if the point are even within the image.
37
	 *
38
	 * This method will actually "nudge" the endpoints back onto the image if they are found to be
39
	 * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
40
	 * patterns in an image where the QR Code runs all the way to the image border.
41
	 *
42
	 * For efficiency, the method will check points from either end of the line until one is found
43
	 * to be within the image. Because the set of points are assumed to be linear, this is valid.
44
	 *
45
	 * @param \chillerlan\QRCode\Decoder\BitMatrix $matrix image into which the points should map
46
	 * @param float[]                              $points actual points in x1,y1,...,xn,yn form
47
	 *
48
	 * @throws \chillerlan\QRCode\Detector\QRCodeDetectorException if an endpoint is lies outside the image boundaries
49
	 */
50
	private function checkAndNudgePoints(BitMatrix $matrix, array $points):void{
51
		$dimension = $matrix->size();
52
		$nudged    = true;
53
		$max       = count($points);
54
55
		// Check and nudge points from start until we see some that are OK:
56
		for($offset = 0; $offset < $max && $nudged; $offset += 2){
57
			$x = (int)$points[$offset];
58
			$y = (int)$points[$offset + 1];
59
60
			if($x < -1 || $x > $dimension || $y < -1 || $y > $dimension){
61
				throw new QRCodeDetectorException(sprintf('checkAndNudgePoints 1, x: %s, y: %s, d: %s', $x, $y, $dimension));
62
			}
63
64
			$nudged = false;
65
66
			if($x === -1){
67
				$points[$offset] = 0.0;
68
				$nudged          = true;
69
			}
70
			elseif($x === $dimension){
71
				$points[$offset] = $dimension - 1;
72
				$nudged          = true;
73
			}
74
			if($y === -1){
75
				$points[$offset + 1] = 0.0;
76
				$nudged              = true;
77
			}
78
			elseif($y === $dimension){
79
				$points[$offset + 1] = $dimension - 1;
80
				$nudged              = true;
81
			}
82
		}
83
		// Check and nudge points from end:
84
		$nudged = true;
85
86
		for($offset = count($points) - 2; $offset >= 0 && $nudged; $offset -= 2){
87
			$x = (int)$points[$offset];
88
			$y = (int)$points[$offset + 1];
89
90
			if($x < -1 || $x > $dimension || $y < -1 || $y > $dimension){
91
				throw new QRCodeDetectorException(sprintf('checkAndNudgePoints 2, x: %s, y: %s, d: %s', $x, $y, $dimension));
92
			}
93
94
			$nudged = false;
95
96
			if($x === -1){
97
				$points[$offset] = 0.0;
98
				$nudged          = true;
99
			}
100
			elseif($x === $dimension){
101
				$points[$offset] = $dimension - 1;
102
				$nudged          = true;
103
			}
104
			if($y === -1){
105
				$points[$offset + 1] = 0.0;
106
				$nudged              = true;
107
			}
108
			elseif($y === $dimension){
109
				$points[$offset + 1] = $dimension - 1;
110
				$nudged              = true;
111
			}
112
		}
113
	}
114
115
	/**
116
	 * Samples an image for a rectangular matrix of bits of the given dimension. The sampling
117
	 * transformation is determined by the coordinates of 4 points, in the original and transformed
118
	 * image space.
119
	 *
120
	 * @return \chillerlan\QRCode\Decoder\BitMatrix representing a grid of points sampled from the image within a region
121
	 *   defined by the "from" parameters
122
	 * @throws \chillerlan\QRCode\Detector\QRCodeDetectorException if image can't be sampled, for example, if the transformation defined
123
	 *   by the given points is invalid or results in sampling outside the image boundaries
124
	 */
125
	public function sampleGrid(BitMatrix $matrix, int $dimension, PerspectiveTransform $transform):BitMatrix{
126
127
		if($dimension <= 0){
128
			throw new QRCodeDetectorException('invalid matrix size');
129
		}
130
131
		$bits   = new BitMatrix($dimension);
132
		$points = array_fill(0, 2 * $dimension, 0.0);
133
134
		for($y = 0; $y < $dimension; $y++){
135
			$max    = count($points);
136
			$iValue = $y + 0.5;
137
138
			for($x = 0; $x < $max; $x += 2){
139
				$points[$x]     = ($x / 2) + 0.5;
140
				$points[$x + 1] = $iValue;
141
			}
142
143
			$transform->transformPoints($points);
144
			// Quick check to see if points transformed to something inside the image;
145
			// sufficient to check the endpoints
146
			$this->checkAndNudgePoints($matrix, $points);
147
148
			try{
149
				for($x = 0; $x < $max; $x += 2){
150
					// Black(-ish) pixel
151
					$bits->set($x / 2, $y, $matrix->check((int)$points[$x], (int)$points[$x + 1]), QRMatrix::M_DATA);
152
				}
153
			}
154
			// @codeCoverageIgnoreStart
155
			catch(Throwable $aioobe){//ArrayIndexOutOfBoundsException
156
				// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
157
				// transform gets "twisted" such that it maps a straight line of points to a set of points
158
				// whose endpoints are in bounds, but others are not. There is probably some mathematical
159
				// way to detect this about the transformation that I don't know yet.
160
				// This results in an ugly runtime exception despite our clever checks above -- can't have
161
				// that. We could check each point's coordinates but that feels duplicative. We settle for
162
				// catching and wrapping ArrayIndexOutOfBoundsException.
163
				throw new QRCodeDetectorException('ArrayIndexOutOfBoundsException');
164
			}
165
			// @codeCoverageIgnoreEnd
166
167
		}
168
169
		return $bits;
170
	}
171
172
}
173