1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
|
<?php
/**
* Class Binarizer
*
* @created 17.01.2021
* @author ZXing Authors
* @author Smiley <smiley@chillerlan.net>
* @copyright 2021 Smiley
* @license Apache-2.0
*/
namespace chillerlan\QRCode\Decoder;
use chillerlan\QRCode\Common\LuminanceSourceInterface;
use chillerlan\QRCode\Data\QRMatrix;
use function array_fill, count, intdiv, max;
/**
* This class implements a local thresholding algorithm, which while slower than the
* GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
* high frequency images of barcodes with black data on white backgrounds. For this application,
* it does a much better job than a global blackpoint with severe shadows and gradients.
* However, it tends to produce artifacts on lower frequency images and is therefore not
* a good general purpose binarizer for uses outside ZXing.
*
* This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
* and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
* inherently local, and only fails for horizontal gradients. We can revisit that problem later,
* but for now it was not a win to use local blocks for 1D.
*
* This Binarizer is the default for the unit tests and the recommended class for library users.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
final class Binarizer{
// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
// So this is the smallest dimension in each axis we can accept.
private const BLOCK_SIZE_POWER = 3;
private const BLOCK_SIZE = 8; // ...0100...00
private const BLOCK_SIZE_MASK = 7; // ...0011...11
private const MINIMUM_DIMENSION = 40;
private const MIN_DYNAMIC_RANGE = 24;
# private const LUMINANCE_BITS = 5;
private const LUMINANCE_SHIFT = 3;
private const LUMINANCE_BUCKETS = 32;
private LuminanceSourceInterface $source;
private array $luminances;
/**
*
*/
public function __construct(LuminanceSourceInterface $source){
$this->source = $source;
$this->luminances = $this->source->getLuminances();
}
/**
* @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
*/
private function estimateBlackPoint(array $buckets):int{
// Find the tallest peak in the histogram.
$numBuckets = count($buckets);
$maxBucketCount = 0;
$firstPeak = 0;
$firstPeakSize = 0;
for($x = 0; $x < $numBuckets; $x++){
if($buckets[$x] > $firstPeakSize){
$firstPeak = $x;
$firstPeakSize = $buckets[$x];
}
if($buckets[$x] > $maxBucketCount){
$maxBucketCount = $buckets[$x];
}
}
// Find the second-tallest peak which is somewhat far from the tallest peak.
$secondPeak = 0;
$secondPeakScore = 0;
for($x = 0; $x < $numBuckets; $x++){
$distanceToBiggest = ($x - $firstPeak);
// Encourage more distant second peaks by multiplying by square of distance.
$score = ($buckets[$x] * $distanceToBiggest * $distanceToBiggest);
if($score > $secondPeakScore){
$secondPeak = $x;
$secondPeakScore = $score;
}
}
// Make sure firstPeak corresponds to the black peak.
if($firstPeak > $secondPeak){
$temp = $firstPeak;
$firstPeak = $secondPeak;
$secondPeak = $temp;
}
// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
if(($secondPeak - $firstPeak) <= ($numBuckets / 16)){
throw new QRCodeDecoderException('no meaningful dark point found'); // @codeCoverageIgnore
}
// Find a valley between them that is low and closer to the white peak.
$bestValley = ($secondPeak - 1);
$bestValleyScore = -1;
for($x = ($secondPeak - 1); $x > $firstPeak; $x--){
$fromFirst = ($x - $firstPeak);
$score = ($fromFirst * $fromFirst * ($secondPeak - $x) * ($maxBucketCount - $buckets[$x]));
if($score > $bestValleyScore){
$bestValley = $x;
$bestValleyScore = $score;
}
}
return ($bestValley << self::LUMINANCE_SHIFT);
}
/**
* Calculates the final BitMatrix once for all requests. This could be called once from the
* constructor instead, but there are some advantages to doing it lazily, such as making
* profiling easier, and not doing heavy lifting when callers don't expect it.
*
* Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive
* and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
* may not apply sharpening. Therefore, a row from this matrix may not be identical to one
* fetched using getBlackRow(), so don't mix and match between them.
*
* @return \chillerlan\QRCode\Decoder\BitMatrix The 2D array of bits for the image (true means black).
*/
public function getBlackMatrix():BitMatrix{
$width = $this->source->getWidth();
$height = $this->source->getHeight();
if($width >= self::MINIMUM_DIMENSION && $height >= self::MINIMUM_DIMENSION){
$subWidth = ($width >> self::BLOCK_SIZE_POWER);
if(($width & self::BLOCK_SIZE_MASK) !== 0){
$subWidth++;
}
$subHeight = ($height >> self::BLOCK_SIZE_POWER);
if(($height & self::BLOCK_SIZE_MASK) !== 0){
$subHeight++;
}
return $this->calculateThresholdForBlock($subWidth, $subHeight, $width, $height);
}
// If the image is too small, fall back to the global histogram approach.
return $this->getHistogramBlackMatrix($width, $height);
}
/**
*
*/
private function getHistogramBlackMatrix(int $width, int $height):BitMatrix{
// Quickly calculates the histogram by sampling four rows from the image. This proved to be
// more robust on the blackbox tests than sampling a diagonal as we used to do.
$buckets = array_fill(0, self::LUMINANCE_BUCKETS, 0);
$right = intdiv(($width * 4), 5);
$x = intdiv($width, 5);
for($y = 1; $y < 5; $y++){
$row = intdiv(($height * $y), 5);
$localLuminances = $this->source->getRow($row);
for(; $x < $right; $x++){
$pixel = ($localLuminances[$x] & 0xff);
$buckets[($pixel >> self::LUMINANCE_SHIFT)]++;
}
}
$blackPoint = $this->estimateBlackPoint($buckets);
// We delay reading the entire image luminance until the black point estimation succeeds.
// Although we end up reading four rows twice, it is consistent with our motto of
// "fail quickly" which is necessary for continuous scanning.
$matrix = new BitMatrix(max($width, $height));
for($y = 0; $y < $height; $y++){
$offset = ($y * $width);
for($x = 0; $x < $width; $x++){
$matrix->set($x, $y, (($this->luminances[($offset + $x)] & 0xff) < $blackPoint), QRMatrix::M_DATA);
}
}
return $matrix;
}
/**
* Calculates a single black point for each block of pixels and saves it away.
* See the following thread for a discussion of this algorithm:
*
* @see http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
*/
private function calculateBlackPoints(int $subWidth, int $subHeight, int $width, int $height):array{
$blackPoints = array_fill(0, $subHeight, array_fill(0, $subWidth, 0));
for($y = 0; $y < $subHeight; $y++){
$yoffset = ($y << self::BLOCK_SIZE_POWER);
$maxYOffset = ($height - self::BLOCK_SIZE);
if($yoffset > $maxYOffset){
$yoffset = $maxYOffset;
}
for($x = 0; $x < $subWidth; $x++){
$xoffset = ($x << self::BLOCK_SIZE_POWER);
$maxXOffset = ($width - self::BLOCK_SIZE);
if($xoffset > $maxXOffset){
$xoffset = $maxXOffset;
}
$sum = 0;
$min = 255;
$max = 0;
for($yy = 0, $offset = ($yoffset * $width + $xoffset); $yy < self::BLOCK_SIZE; $yy++, $offset += $width){
for($xx = 0; $xx < self::BLOCK_SIZE; $xx++){
$pixel = ((int)($this->luminances[(int)($offset + $xx)]) & 0xff);
$sum += $pixel;
// still looking for good contrast
if($pixel < $min){
$min = $pixel;
}
if($pixel > $max){
$max = $pixel;
}
}
// short-circuit min/max tests once dynamic range is met
if(($max - $min) > self::MIN_DYNAMIC_RANGE){
// finish the rest of the rows quickly
for($yy++, $offset += $width; $yy < self::BLOCK_SIZE; $yy++, $offset += $width){
for($xx = 0; $xx < self::BLOCK_SIZE; $xx++){
$sum += ((int)($this->luminances[(int)($offset + $xx)]) & 0xff);
}
}
}
}
// The default estimate is the average of the values in the block.
$average = ($sum >> (self::BLOCK_SIZE_POWER * 2));
if(($max - $min) <= self::MIN_DYNAMIC_RANGE){
// If variation within the block is low, assume this is a block with only light or only
// dark pixels. In that case we do not want to use the average, as it would divide this
// low contrast area into black and white pixels, essentially creating data out of noise.
//
// The default assumption is that the block is light/background. Since no estimate for
// the level of dark pixels exists locally, use half the min for the block.
$average = ($min / 2);
if($y > 0 && $x > 0){
// Correct the "white background" assumption for blocks that have neighbors by comparing
// the pixels in this block to the previously calculated black points. This is based on
// the fact that dark barcode symbology is always surrounded by some amount of light
// background for which reasonable black point estimates were made. The bp estimated at
// the boundaries is used for the interior.
// The (min < bp) is arbitrary but works better than other heuristics that were tried.
$averageNeighborBlackPoint = (
($blackPoints[($y - 1)][$x] + (2 * $blackPoints[$y][($x - 1)]) + $blackPoints[($y - 1)][($x - 1)]) / 4
);
if($min < $averageNeighborBlackPoint){
$average = $averageNeighborBlackPoint;
}
}
}
$blackPoints[$y][$x] = $average;
}
}
return $blackPoints;
}
/**
* For each block in the image, calculate the average black point using a 5x5 grid
* of the surrounding blocks. Also handles the corner cases (fractional blocks are computed based
* on the last pixels in the row/column which are also used in the previous block).
*/
private function calculateThresholdForBlock(int $subWidth, int $subHeight, int $width, int $height):BitMatrix{
$matrix = new BitMatrix(max($width, $height));
$blackPoints = $this->calculateBlackPoints($subWidth, $subHeight, $width, $height);
for($y = 0; $y < $subHeight; $y++){
$yoffset = ($y << self::BLOCK_SIZE_POWER);
$maxYOffset = ($height - self::BLOCK_SIZE);
if($yoffset > $maxYOffset){
$yoffset = $maxYOffset;
}
for($x = 0; $x < $subWidth; $x++){
$xoffset = ($x << self::BLOCK_SIZE_POWER);
$maxXOffset = ($width - self::BLOCK_SIZE);
if($xoffset > $maxXOffset){
$xoffset = $maxXOffset;
}
$left = $this->cap($x, 2, ($subWidth - 3));
$top = $this->cap($y, 2, ($subHeight - 3));
$sum = 0;
for($z = -2; $z <= 2; $z++){
$br = $blackPoints[($top + $z)];
$sum += ($br[($left - 2)] + $br[($left - 1)] + $br[$left] + $br[($left + 1)] + $br[($left + 2)]);
}
$average = (int)($sum / 25);
// Applies a single threshold to a block of pixels.
for($j = 0, $o = ($yoffset * $width + $xoffset); $j < self::BLOCK_SIZE; $j++, $o += $width){
for($i = 0; $i < self::BLOCK_SIZE; $i++){
// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
$v = (((int)($this->luminances[($o + $i)]) & 0xff) <= $average);
$matrix->set(($xoffset + $i), ($yoffset + $j), $v, QRMatrix::M_DATA);
}
}
}
}
return $matrix;
}
/**
* @noinspection PhpSameParameterValueInspection
*/
private function cap(int $value, int $min, int $max):int{
if($value < $min){
return $min;
}
if($value > $max){
return $max;
}
return $value;
}
}
|