2 * FinderPatternFinder.cpp
5 * Created by Christian Brunschen on 13/05/2008.
6 * Copyright 2008 ZXing authors All rights reserved.
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
21 #include <zxing/qrcode/detector/FinderPatternFinder.h>
22 #include <zxing/ReaderException.h>
23 #include <zxing/DecodeHints.h>
34 class FurthestFromAverageComparator {
36 const float averageModuleSize_;
38 FurthestFromAverageComparator(float averageModuleSize) :
39 averageModuleSize_(averageModuleSize) {
41 bool operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) {
42 float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_);
43 float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_);
48 class CenterComparator {
49 const float averageModuleSize_;
51 CenterComparator(float averageModuleSize) :
52 averageModuleSize_(averageModuleSize) {
54 bool operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) {
55 // N.B.: we want the result in descending order ...
56 if (a->getCount() != b->getCount()) {
57 return a->getCount() > b->getCount();
59 float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_);
60 float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_);
66 int FinderPatternFinder::CENTER_QUORUM = 2;
67 int FinderPatternFinder::MIN_SKIP = 3;
68 int FinderPatternFinder::MAX_MODULES = 57;
70 float FinderPatternFinder::centerFromEnd(int* stateCount, int end) {
71 return (float)(end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
74 bool FinderPatternFinder::foundPatternCross(int* stateCount) {
75 int totalModuleSize = 0;
76 for (int i = 0; i < 5; i++) {
77 if (stateCount[i] == 0) {
80 totalModuleSize += stateCount[i];
82 if (totalModuleSize < 7) {
85 float moduleSize = (float)totalModuleSize / 7.0f;
86 float maxVariance = moduleSize / 2.0f;
87 // Allow less than 50% variance from 1-1-3-1-1 proportions
88 return abs(moduleSize - stateCount[0]) < maxVariance && abs(moduleSize - stateCount[1]) < maxVariance && abs(3.0f
89 * moduleSize - stateCount[2]) < 3.0f * maxVariance && abs(moduleSize - stateCount[3]) < maxVariance && abs(
90 moduleSize - stateCount[4]) < maxVariance;
93 float FinderPatternFinder::crossCheckVertical(size_t startI, size_t centerJ, int maxCount, int originalStateCountTotal) {
95 int maxI = image_->getHeight();
97 for (int i = 0; i < 5; i++)
101 // Start counting up from center
103 while (i >= 0 && image_->get(centerJ, i)) {
110 while (i >= 0 && !image_->get(centerJ, i) && stateCount[1] <= maxCount) {
114 // If already too many modules in this state or ran off the edge:
115 if (i < 0 || stateCount[1] > maxCount) {
118 while (i >= 0 && image_->get(centerJ, i) && stateCount[0] <= maxCount) {
122 if (stateCount[0] > maxCount) {
126 // Now also count down from center
128 while (i < maxI && image_->get(centerJ, i)) {
135 while (i < maxI && !image_->get(centerJ, i) && stateCount[3] < maxCount) {
139 if (i == maxI || stateCount[3] >= maxCount) {
142 while (i < maxI && image_->get(centerJ, i) && stateCount[4] < maxCount) {
146 if (stateCount[4] >= maxCount) {
150 // If we found a finder-pattern-like section, but its size is more than 40% different than
151 // the original, assume it's a false positive
152 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
153 if (5 * abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
157 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : NAN;
160 float FinderPatternFinder::crossCheckHorizontal(size_t startJ, size_t centerI, int maxCount,
161 int originalStateCountTotal) {
163 int maxJ = image_->getWidth();
165 for (int i = 0; i < 5; i++)
169 while (j >= 0 && image_->get(j, centerI)) {
176 while (j >= 0 && !image_->get(j, centerI) && stateCount[1] <= maxCount) {
180 if (j < 0 || stateCount[1] > maxCount) {
183 while (j >= 0 && image_->get(j, centerI) && stateCount[0] <= maxCount) {
187 if (stateCount[0] > maxCount) {
192 while (j < maxJ && image_->get(j, centerI)) {
199 while (j < maxJ && !image_->get(j, centerI) && stateCount[3] < maxCount) {
203 if (j == maxJ || stateCount[3] >= maxCount) {
206 while (j < maxJ && image_->get(j, centerI) && stateCount[4] < maxCount) {
210 if (stateCount[4] >= maxCount) {
214 // If we found a finder-pattern-like section, but its size is significantly different than
215 // the original, assume it's a false positive
216 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
217 if (5 * abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
221 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : NAN;
224 bool FinderPatternFinder::handlePossibleCenter(int* stateCount, size_t i, size_t j) {
225 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
226 float centerJ = centerFromEnd(stateCount, j);
227 float centerI = crossCheckVertical(i, (size_t)centerJ, stateCount[2], stateCountTotal);
228 if (!isnan(centerI)) {
230 centerJ = crossCheckHorizontal((size_t)centerJ, (size_t)centerI, stateCount[2], stateCountTotal);
231 if (!isnan(centerJ)) {
232 float estimatedModuleSize = (float)stateCountTotal / 7.0f;
234 size_t max = possibleCenters_.size();
235 for (size_t index = 0; index < max; index++) {
236 Ref<FinderPattern> center = possibleCenters_[index];
237 // Look for about the same center and module size:
238 if (center->aboutEquals(estimatedModuleSize, centerI, centerJ)) {
239 center->incrementCount();
245 Ref<FinderPattern> newPattern(new FinderPattern(centerJ, centerI, estimatedModuleSize));
246 possibleCenters_.push_back(newPattern);
247 if (callback_ != 0) {
248 callback_->foundPossibleResultPoint(*newPattern);
257 int FinderPatternFinder::findRowSkip() {
258 size_t max = possibleCenters_.size();
262 Ref<FinderPattern> firstConfirmedCenter;
263 for (size_t i = 0; i < max; i++) {
264 Ref<FinderPattern> center = possibleCenters_[i];
265 if (center->getCount() >= CENTER_QUORUM) {
266 if (firstConfirmedCenter == 0) {
267 firstConfirmedCenter = center;
269 // We have two confirmed centers
270 // How far down can we skip before resuming looking for the next
271 // pattern? In the worst case, only the difference between the
272 // difference in the x / y coordinates of the two centers.
273 // This is the case where you find top left first. Draw it out.
275 return (int)(abs(firstConfirmedCenter->getX() - center->getX()) - abs(firstConfirmedCenter->getY()
276 - center->getY()))/2;
283 bool FinderPatternFinder::haveMultiplyConfirmedCenters() {
284 int confirmedCount = 0;
285 float totalModuleSize = 0.0f;
286 size_t max = possibleCenters_.size();
287 for (size_t i = 0; i < max; i++) {
288 Ref<FinderPattern> pattern = possibleCenters_[i];
289 if (pattern->getCount() >= CENTER_QUORUM) {
291 totalModuleSize += pattern->getEstimatedModuleSize();
294 if (confirmedCount < 3) {
297 // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
298 // and that we need to keep looking. We detect this by asking if the estimated module sizes
299 // vary too much. We arbitrarily say that when the total deviation from average exceeds
300 // 5% of the total module size estimates, it's too much.
301 float average = totalModuleSize / max;
302 float totalDeviation = 0.0f;
303 for (size_t i = 0; i < max; i++) {
304 Ref<FinderPattern> pattern = possibleCenters_[i];
305 totalDeviation += abs(pattern->getEstimatedModuleSize() - average);
307 return totalDeviation <= 0.05f * totalModuleSize;
310 vector<Ref<FinderPattern> > FinderPatternFinder::selectBestPatterns() {
311 size_t startSize = possibleCenters_.size();
314 // Couldn't find enough finder patterns
315 throw zxing::ReaderException("Could not find three finder patterns");
318 // Filter outlier possibilities whose module size is too different
320 // But we can only afford to do so if we have at least 4 possibilities to choose from
321 float totalModuleSize = 0.0f;
323 for (size_t i = 0; i < startSize; i++) {
324 float size = possibleCenters_[i]->getEstimatedModuleSize();
325 totalModuleSize += size;
326 square += size * size;
328 float average = totalModuleSize / (float) startSize;
329 float stdDev = (float)sqrt(square / startSize - average * average);
331 sort(possibleCenters_.begin(), possibleCenters_.end(), FurthestFromAverageComparator(average));
333 float limit = max(0.2f * average, stdDev);
335 for (size_t i = 0; i < possibleCenters_.size() && possibleCenters_.size() > 3; i++) {
336 if (abs(possibleCenters_[i]->getEstimatedModuleSize() - average) > limit) {
337 possibleCenters_.erase(possibleCenters_.begin()+i);
343 if (possibleCenters_.size() > 3) {
344 // Throw away all but those first size candidate points we found.
345 float totalModuleSize = 0.0f;
346 for (size_t i = 0; i < startSize; i++) {
347 float size = possibleCenters_[i]->getEstimatedModuleSize();
348 totalModuleSize += size;
350 float average = totalModuleSize / (float) startSize;
351 sort(possibleCenters_.begin(), possibleCenters_.end(), CenterComparator(average));
354 if (possibleCenters_.size() > 3) {
355 possibleCenters_.erase(possibleCenters_.begin()+3,possibleCenters_.end());
358 vector<Ref<FinderPattern> > result(3);
359 result[0] = possibleCenters_[0];
360 result[1] = possibleCenters_[1];
361 result[2] = possibleCenters_[2];
365 vector<Ref<FinderPattern> > FinderPatternFinder::orderBestPatterns(vector<Ref<FinderPattern> > patterns) {
366 // Find distances between pattern centers
367 float abDistance = distance(patterns[0], patterns[1]);
368 float bcDistance = distance(patterns[1], patterns[2]);
369 float acDistance = distance(patterns[0], patterns[2]);
371 Ref<FinderPattern> topLeft;
372 Ref<FinderPattern> topRight;
373 Ref<FinderPattern> bottomLeft;
374 // Assume one closest to other two is top left;
375 // topRight and bottomLeft will just be guesses below at first
376 if (bcDistance >= abDistance && bcDistance >= acDistance) {
377 topLeft = patterns[0];
378 topRight = patterns[1];
379 bottomLeft = patterns[2];
380 } else if (acDistance >= bcDistance && acDistance >= abDistance) {
381 topLeft = patterns[1];
382 topRight = patterns[0];
383 bottomLeft = patterns[2];
385 topLeft = patterns[2];
386 topRight = patterns[0];
387 bottomLeft = patterns[1];
390 // Use cross product to figure out which of other1/2 is the bottom left
391 // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right"
392 // should yield a vector with positive z component
393 if ((bottomLeft->getY() - topLeft->getY()) * (topRight->getX() - topLeft->getX()) < (bottomLeft->getX()
394 - topLeft->getX()) * (topRight->getY() - topLeft->getY())) {
395 Ref<FinderPattern> temp = topRight;
396 topRight = bottomLeft;
400 vector<Ref<FinderPattern> > results(3);
401 results[0] = bottomLeft;
402 results[1] = topLeft;
403 results[2] = topRight;
407 float FinderPatternFinder::distance(Ref<ResultPoint> p1, Ref<ResultPoint> p2) {
408 float dx = p1->getX() - p2->getX();
409 float dy = p1->getY() - p2->getY();
410 return (float)sqrt(dx * dx + dy * dy);
413 FinderPatternFinder::FinderPatternFinder(Ref<BitMatrix> image,
414 Ref<ResultPointCallback>const& callback) :
415 image_(image), possibleCenters_(), hasSkipped_(false), callback_(callback) {
418 Ref<FinderPatternInfo> FinderPatternFinder::find(DecodeHints const& hints) {
419 bool tryHarder = hints.getTryHarder();
421 size_t maxI = image_->getHeight();
422 size_t maxJ = image_->getWidth();
425 // We are looking for black/white/black/white/black modules in
426 // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
428 // As this is used often, we use an integer array instead of vector
433 // Let's assume that the maximum version QR Code we support takes up 1/4
434 // the height of the image, and then account for the center being 3
435 // modules in size. This gives the smallest number of pixels the center
436 // could be, so skip this often. When trying harder, look for all
437 // QR versions regardless of how dense they are.
438 int iSkip = (3 * maxI) / (4 * MAX_MODULES);
439 if (iSkip < MIN_SKIP || tryHarder) {
443 // This is slightly faster than using the Ref. Efficiency is important here
444 BitMatrix& matrix = *image_;
446 for (size_t i = iSkip - 1; i < maxI && !done; i += iSkip) {
447 // Get a row of black/white values
454 int currentState = 0;
455 for (size_t j = 0; j < maxJ; j++) {
456 if (matrix.get(j, i)) {
458 if ((currentState & 1) == 1) { // Counting white pixels
461 stateCount[currentState]++;
462 } else { // White pixel
463 if ((currentState & 1) == 0) { // Counting black pixels
464 if (currentState == 4) { // A winner?
465 if (foundPatternCross(stateCount)) { // Yes
466 bool confirmed = handlePossibleCenter(stateCount, i, j);
468 // Start examining every other line. Checking each line turned out to be too
469 // expensive and didn't improve performance.
472 done = haveMultiplyConfirmedCenters();
474 int rowSkip = findRowSkip();
475 if (rowSkip > stateCount[2]) {
476 // Skip rows between row of lower confirmed center
477 // and top of presumed third confirmed center
478 // but back up a bit to get a full chance of detecting
479 // it, entire width of center of finder pattern
481 // Skip by rowSkip, but back off by stateCount[2] (size
482 // of last center of pattern we saw) to be conservative,
483 // and also back off by iSkip which is about to be
485 i += rowSkip - stateCount[2] - iSkip;
490 stateCount[0] = stateCount[2];
491 stateCount[1] = stateCount[3];
492 stateCount[2] = stateCount[4];
498 // Clear state to start looking again
505 } else { // No, shift counts back by two
506 stateCount[0] = stateCount[2];
507 stateCount[1] = stateCount[3];
508 stateCount[2] = stateCount[4];
514 stateCount[++currentState]++;
516 } else { // Counting white pixels
517 stateCount[currentState]++;
521 if (foundPatternCross(stateCount)) {
522 bool confirmed = handlePossibleCenter(stateCount, i, maxJ);
524 iSkip = stateCount[0];
527 done = haveMultiplyConfirmedCenters();
533 vector<Ref<FinderPattern> > patternInfo = selectBestPatterns();
534 patternInfo = orderBestPatterns(patternInfo);
536 Ref<FinderPatternInfo> result(new FinderPatternInfo(patternInfo));