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>
33 class ClosestToAverageComparator {
35 float averageModuleSize_;
37 ClosestToAverageComparator() : averageModuleSize_(0.0f) { }
39 ClosestToAverageComparator(float averageModuleSize) :
40 averageModuleSize_(averageModuleSize) {
42 int operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) {
43 float dA = abs(a->getEstimatedModuleSize() - averageModuleSize_);
44 float dB = abs(b->getEstimatedModuleSize() - averageModuleSize_);
45 return dA < dB ? -1 : dA > dB ? 1 : 0;
49 class CenterComparator {
51 int operator()(Ref<FinderPattern> a, Ref<FinderPattern> b) {
52 return b->getCount() - a->getCount();
56 int FinderPatternFinder::CENTER_QUORUM = 2;
57 int FinderPatternFinder::MIN_SKIP = 3;
58 int FinderPatternFinder::MAX_MODULES = 57;
60 float FinderPatternFinder::centerFromEnd(int* stateCount, int end) {
61 return (float)(end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
64 bool FinderPatternFinder::foundPatternCross(int* stateCount) {
65 int totalModuleSize = 0;
66 for (int i = 0; i < 5; i++) {
67 if (stateCount[i] == 0) {
70 totalModuleSize += stateCount[i];
72 if (totalModuleSize < 7) {
75 float moduleSize = (float)totalModuleSize / 7.0f;
76 float maxVariance = moduleSize / 2.0f;
77 // Allow less than 50% variance from 1-1-3-1-1 proportions
78 return abs(moduleSize - stateCount[0]) < maxVariance && abs(moduleSize - stateCount[1]) < maxVariance && abs(3.0f
79 * moduleSize - stateCount[2]) < 3.0f * maxVariance && abs(moduleSize - stateCount[3]) < maxVariance && abs(
80 moduleSize - stateCount[4]) < maxVariance;
83 float FinderPatternFinder::crossCheckVertical(size_t startI, size_t centerJ, int maxCount, int originalStateCountTotal) {
85 int maxI = image_->getHeight();
87 for (int i = 0; i < 5; i++)
91 // Start counting up from center
93 while (i >= 0 && image_->get(centerJ, i)) {
100 while (i >= 0 && !image_->get(centerJ, i) && stateCount[1] <= maxCount) {
104 // If already too many modules in this state or ran off the edge:
105 if (i < 0 || stateCount[1] > maxCount) {
108 while (i >= 0 && image_->get(centerJ, i) && stateCount[0] <= maxCount) {
112 if (stateCount[0] > maxCount) {
116 // Now also count down from center
118 while (i < maxI && image_->get(centerJ, i)) {
125 while (i < maxI && !image_->get(centerJ, i) && stateCount[3] < maxCount) {
129 if (i == maxI || stateCount[3] >= maxCount) {
132 while (i < maxI && image_->get(centerJ, i) && stateCount[4] < maxCount) {
136 if (stateCount[4] >= maxCount) {
140 // If we found a finder-pattern-like section, but its size is more than 40% different than
141 // the original, assume it's a false positive
142 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
143 if (5 * abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
147 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : NAN;
150 float FinderPatternFinder::crossCheckHorizontal(size_t startJ, size_t centerI, int maxCount,
151 int originalStateCountTotal) {
153 int maxJ = image_->getWidth();
155 for (int i = 0; i < 5; i++)
159 while (j >= 0 && image_->get(j, centerI)) {
166 while (j >= 0 && !image_->get(j, centerI) && stateCount[1] <= maxCount) {
170 if (j < 0 || stateCount[1] > maxCount) {
173 while (j >= 0 && image_->get(j, centerI) && stateCount[0] <= maxCount) {
177 if (stateCount[0] > maxCount) {
182 while (j < maxJ && image_->get(j, centerI)) {
189 while (j < maxJ && !image_->get(j, centerI) && stateCount[3] < maxCount) {
193 if (j == maxJ || stateCount[3] >= maxCount) {
196 while (j < maxJ && image_->get(j, centerI) && stateCount[4] < maxCount) {
200 if (stateCount[4] >= maxCount) {
204 // If we found a finder-pattern-like section, but its size is significantly different than
205 // the original, assume it's a false positive
206 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
207 if (5 * abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
211 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : NAN;
214 bool FinderPatternFinder::handlePossibleCenter(int* stateCount, size_t i, size_t j) {
215 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
216 float centerJ = centerFromEnd(stateCount, j);
217 float centerI = crossCheckVertical(i, (size_t)centerJ, stateCount[2], stateCountTotal);
218 if (!isnan(centerI)) {
220 centerJ = crossCheckHorizontal((size_t)centerJ, (size_t)centerI, stateCount[2], stateCountTotal);
221 if (!isnan(centerJ)) {
222 float estimatedModuleSize = (float)stateCountTotal / 7.0f;
224 size_t max = possibleCenters_.size();
225 for (size_t index = 0; index < max; index++) {
226 Ref<FinderPattern> center = possibleCenters_[index];
227 // Look for about the same center and module size:
228 if (center->aboutEquals(estimatedModuleSize, centerI, centerJ)) {
229 center->incrementCount();
235 Ref<FinderPattern> newPattern(new FinderPattern(centerJ, centerI, estimatedModuleSize));
236 possibleCenters_.push_back(newPattern);
244 int FinderPatternFinder::findRowSkip() {
245 size_t max = possibleCenters_.size();
249 Ref<FinderPattern> firstConfirmedCenter;
250 for (size_t i = 0; i < max; i++) {
251 Ref<FinderPattern> center = possibleCenters_[i];
252 if (center->getCount() >= CENTER_QUORUM) {
253 if (firstConfirmedCenter == 0) {
254 firstConfirmedCenter = center;
256 // We have two confirmed centers
257 // How far down can we skip before resuming looking for the next
258 // pattern? In the worst case, only the difference between the
259 // difference in the x / y coordinates of the two centers.
260 // This is the case where you find top left first. Draw it out.
262 return (int)(abs(firstConfirmedCenter->getX() - center->getX()) - abs(firstConfirmedCenter->getY()
270 bool FinderPatternFinder::haveMultiplyConfirmedCenters() {
271 int confirmedCount = 0;
272 float totalModuleSize = 0.0f;
273 size_t max = possibleCenters_.size();
274 for (size_t i = 0; i < max; i++) {
275 Ref<FinderPattern> pattern = possibleCenters_[i];
276 if (pattern->getCount() >= CENTER_QUORUM) {
278 totalModuleSize += pattern->getEstimatedModuleSize();
281 if (confirmedCount < 3) {
284 // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
285 // and that we need to keep looking. We detect this by asking if the estimated module sizes
286 // vary too much. We arbitrarily say that when the total deviation from average exceeds
287 // 15% of the total module size estimates, it's too much.
288 float average = totalModuleSize / max;
289 float totalDeviation = 0.0f;
290 for (size_t i = 0; i < max; i++) {
291 Ref<FinderPattern> pattern = possibleCenters_[i];
292 totalDeviation += abs(pattern->getEstimatedModuleSize() - average);
294 return totalDeviation <= 0.15f * totalModuleSize;
297 vector<Ref<FinderPattern> > FinderPatternFinder::selectBestPatterns() {
298 sort(possibleCenters_.begin(), possibleCenters_.end(), CenterComparator());
300 size_t max = possibleCenters_.size();
302 if (possibleCenters_[size]->getCount() < CENTER_QUORUM) {
309 // Couldn't find enough finder patterns
310 throw zxing::ReaderException("Could not find three finder patterns");
314 // Found just enough -- hope these are good!
315 vector<Ref<FinderPattern> > result(3);
316 result[0] = possibleCenters_[0];
317 result[1] = possibleCenters_[1];
318 result[2] = possibleCenters_[2];
322 // Hmm, multiple found. We need to pick the best three. Find the most
323 // popular ones whose module size is nearest the average
324 // This does not work for multiple qr codes in the same image
325 float averageModuleSize = 0.0f;
326 for (size_t i = 0; i < size; i++) {
327 averageModuleSize += possibleCenters_[i]->getEstimatedModuleSize();
329 averageModuleSize /= (float)size;
331 sort(possibleCenters_.begin(), possibleCenters_.end(), ClosestToAverageComparator(averageModuleSize));
333 vector<Ref<FinderPattern> > result(3);
334 result[0] = possibleCenters_[0];
335 result[1] = possibleCenters_[1];
336 result[2] = possibleCenters_[2];
340 vector<Ref<FinderPattern> > FinderPatternFinder::orderBestPatterns(vector<Ref<FinderPattern> > patterns) {
341 // Find distances between pattern centers
342 float abDistance = distance(patterns[0], patterns[1]);
343 float bcDistance = distance(patterns[1], patterns[2]);
344 float acDistance = distance(patterns[0], patterns[2]);
346 Ref<FinderPattern> topLeft;
347 Ref<FinderPattern> topRight;
348 Ref<FinderPattern> bottomLeft;
349 // Assume one closest to other two is top left;
350 // topRight and bottomLeft will just be guesses below at first
351 if (bcDistance >= abDistance && bcDistance >= acDistance) {
352 topLeft = patterns[0];
353 topRight = patterns[1];
354 bottomLeft = patterns[2];
355 } else if (acDistance >= bcDistance && acDistance >= abDistance) {
356 topLeft = patterns[1];
357 topRight = patterns[0];
358 bottomLeft = patterns[2];
360 topLeft = patterns[2];
361 topRight = patterns[0];
362 bottomLeft = patterns[1];
365 // Use cross product to figure out which of other1/2 is the bottom left
366 // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right"
367 // should yield a vector with positive z component
368 if ((bottomLeft->getY() - topLeft->getY()) * (topRight->getX() - topLeft->getX()) < (bottomLeft->getX()
369 - topLeft->getX()) * (topRight->getY() - topLeft->getY())) {
370 Ref<FinderPattern> temp = topRight;
371 topRight = bottomLeft;
375 vector<Ref<FinderPattern> > results(3);
376 results[0] = bottomLeft;
377 results[1] = topLeft;
378 results[2] = topRight;
382 float FinderPatternFinder::distance(Ref<ResultPoint> p1, Ref<ResultPoint> p2) {
383 float dx = p1->getX() - p2->getX();
384 float dy = p1->getY() - p2->getY();
385 return (float)sqrt(dx * dx + dy * dy);
388 FinderPatternFinder::FinderPatternFinder(Ref<BitMatrix> image) :
389 image_(image), possibleCenters_(), hasSkipped_(false) {
392 Ref<FinderPatternInfo> FinderPatternFinder::find() {
393 size_t maxI = image_->getHeight();
394 size_t maxJ = image_->getWidth();
397 // We are looking for black/white/black/white/black modules in
398 // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
400 // As this is used often, we use an integer array instead of vector
405 // Let's assume that the maximum version QR Code we support takes up 1/4
406 // the height of the image, and then account for the center being 3
407 // modules in size. This gives the smallest number of pixels the center
408 // could be, so skip this often. When trying harder, look for all
409 // QR versions regardless of how dense they are.
410 size_t iSkip = MIN_SKIP;
412 // This is slightly faster than using the Ref. Efficiency is important here
413 BitMatrix& matrix = *image_;
415 for (size_t i = iSkip - 1; i < maxI && !done; i += iSkip) {
416 // Get a row of black/white values
423 int currentState = 0;
424 for (size_t j = 0; j < maxJ; j++) {
425 if (matrix.get(j, i)) {
427 if ((currentState & 1) == 1) { // Counting white pixels
430 stateCount[currentState]++;
431 } else { // White pixel
432 if ((currentState & 1) == 0) { // Counting black pixels
433 if (currentState == 4) { // A winner?
434 if (foundPatternCross(stateCount)) { // Yes
435 bool confirmed = handlePossibleCenter(stateCount, i, j);
437 iSkip = 1; // Go back to examining each line
439 done = haveMultiplyConfirmedCenters();
441 int rowSkip = findRowSkip();
442 if (rowSkip > stateCount[2]) {
443 // Skip rows between row of lower confirmed center
444 // and top of presumed third confirmed center
445 // but back up a bit to get a full chance of detecting
446 // it, entire width of center of finder pattern
448 // Skip by rowSkip, but back off by stateCount[2] (size
449 // of last center of pattern we saw) to be conservative,
450 // and also back off by iSkip which is about to be
452 i += rowSkip - stateCount[2] - iSkip;
457 // Advance to next black pixel
460 } while (j < maxJ && !image_->get(j, i));
461 j--; // back up to that last white pixel
463 // Clear state to start looking again
470 } else { // No, shift counts back by two
471 stateCount[0] = stateCount[2];
472 stateCount[1] = stateCount[3];
473 stateCount[2] = stateCount[4];
479 stateCount[++currentState]++;
481 } else { // Counting white pixels
482 stateCount[currentState]++;
486 if (foundPatternCross(stateCount)) {
487 bool confirmed = handlePossibleCenter(stateCount, i, maxJ);
489 iSkip = stateCount[0];
492 done = haveMultiplyConfirmedCenters();
498 vector<Ref<FinderPattern> > patternInfo = selectBestPatterns();
499 patternInfo = orderBestPatterns(patternInfo);
501 Ref<FinderPatternInfo> result(new FinderPatternInfo(patternInfo));