2 * Copyright 2007 ZXing authors
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
17 package com.google.zxing.qrcode.detector;
\r
19 import com.google.zxing.DecodeHintType;
\r
20 import com.google.zxing.MonochromeBitmapSource;
\r
21 import com.google.zxing.ReaderException;
\r
22 import com.google.zxing.common.BitArray;
\r
23 import com.google.zxing.common.Collections;
\r
24 import com.google.zxing.common.Comparator;
\r
25 import com.google.zxing.common.GenericResultPoint;
\r
27 import java.util.Hashtable;
\r
28 import java.util.Vector;
\r
31 * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
\r
32 * markers at three corners of a QR Code.</p>
\r
34 * <p>This class is not thread-safe and should not be reused.</p>
\r
36 * @author srowen@google.com (Sean Owen)
\r
38 final class FinderPatternFinder {
\r
40 private static final int CENTER_QUORUM = 2;
\r
41 private static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
\r
42 private static final int MAX_MODULES = 57; // support up to version 10 for mobile clients
\r
43 private static final int INTEGER_MATH_SHIFT = 8;
\r
45 private final MonochromeBitmapSource image;
\r
46 private final Vector possibleCenters;
\r
47 private boolean hasSkipped;
\r
48 private final int[] crossCheckStateCount;
\r
51 * <p>Creates a finder that will search the image for three finder patterns.</p>
\r
53 * @param image image to search
\r
55 FinderPatternFinder(MonochromeBitmapSource image) {
\r
57 this.possibleCenters = new Vector();
\r
58 this.crossCheckStateCount = new int[5];
\r
61 FinderPatternInfo find(Hashtable hints) throws ReaderException {
\r
62 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
\r
63 int maxI = image.getHeight();
\r
64 int maxJ = image.getWidth();
\r
65 // We are looking for black/white/black/white/black modules in
\r
66 // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
\r
68 // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
\r
69 // image, and then account for the center being 3 modules in size. This gives the smallest
\r
70 // number of pixels the center could be, so skip this often. When trying harder, look for all
\r
71 // QR versions regardless of how dense they are.
\r
72 int iSkip = (int) (maxI / (MAX_MODULES * 4.0f) * 3);
\r
73 if (iSkip < MIN_SKIP || tryHarder) {
\r
77 boolean done = false;
\r
78 int[] stateCount = new int[5];
\r
79 BitArray blackRow = new BitArray(maxJ);
\r
80 for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {
\r
81 // Get a row of black/white values
\r
82 blackRow = image.getBlackRow(i, blackRow, 0, maxJ);
\r
88 int currentState = 0;
\r
89 for (int j = 0; j < maxJ; j++) {
\r
90 if (blackRow.get(j)) {
\r
92 if ((currentState & 1) == 1) { // Counting white pixels
\r
95 stateCount[currentState]++;
\r
96 } else { // White pixel
\r
97 if ((currentState & 1) == 0) { // Counting black pixels
\r
98 if (currentState == 4) { // A winner?
\r
99 if (foundPatternCross(stateCount)) { // Yes
\r
100 boolean confirmed = handlePossibleCenter(stateCount, i, j);
\r
102 // Start examining every other line. Checking each line turned out to be too
\r
103 // expensive and didn't improve performance.
\r
106 done = haveMulitplyConfirmedCenters();
\r
108 int rowSkip = findRowSkip();
\r
109 if (rowSkip > stateCount[2]) {
\r
110 // Skip rows between row of lower confirmed center
\r
111 // and top of presumed third confirmed center
\r
112 // but back up a bit to get a full chance of detecting
\r
113 // it, entire width of center of finder pattern
\r
115 // Skip by rowSkip, but back off by stateCount[2] (size of last center
\r
116 // of pattern we saw) to be conservative, and also back off by iSkip which
\r
117 // is about to be re-added
\r
118 i += rowSkip - stateCount[2] - iSkip;
\r
123 // Advance to next black pixel
\r
126 } while (j < maxJ && !blackRow.get(j));
\r
127 j--; // back up to that last white pixel
\r
129 // Clear state to start looking again
\r
136 } else { // No, shift counts back by two
\r
137 stateCount[0] = stateCount[2];
\r
138 stateCount[1] = stateCount[3];
\r
139 stateCount[2] = stateCount[4];
\r
145 stateCount[++currentState]++;
\r
147 } else { // Counting white pixels
\r
148 stateCount[currentState]++;
\r
152 if (foundPatternCross(stateCount)) {
\r
153 boolean confirmed = handlePossibleCenter(stateCount, i, maxJ);
\r
155 iSkip = stateCount[0];
\r
157 // Found a third one
\r
158 done = haveMulitplyConfirmedCenters();
\r
164 FinderPattern[] patternInfo = selectBestPatterns();
\r
165 GenericResultPoint.orderBestPatterns(patternInfo);
\r
167 return new FinderPatternInfo(patternInfo);
\r
171 * Given a count of black/white/black/white/black pixels just seen and an end position,
\r
172 * figures the location of the center of this run.
\r
174 private static float centerFromEnd(int[] stateCount, int end) {
\r
175 return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
\r
179 * @param stateCount count of black/white/black/white/black pixels just read
\r
180 * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
\r
181 * used by finder patterns to be considered a match
\r
183 private static boolean foundPatternCross(int[] stateCount) {
\r
184 int totalModuleSize = 0;
\r
185 for (int i = 0; i < 5; i++) {
\r
186 int count = stateCount[i];
\r
190 totalModuleSize += count;
\r
192 if (totalModuleSize < 7) {
\r
195 int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;
\r
196 int maxVariance = moduleSize / 2;
\r
197 // Allow less than 50% variance from 1-1-3-1-1 proportions
\r
198 return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance &&
\r
199 Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance &&
\r
200 Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance &&
\r
201 Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance &&
\r
202 Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
\r
205 private int[] getCrossCheckStateCount() {
\r
206 crossCheckStateCount[0] = 0;
\r
207 crossCheckStateCount[1] = 0;
\r
208 crossCheckStateCount[2] = 0;
\r
209 crossCheckStateCount[3] = 0;
\r
210 crossCheckStateCount[4] = 0;
\r
211 return crossCheckStateCount;
\r
215 * <p>After a horizontal scan finds a potential finder pattern, this method
\r
216 * "cross-checks" by scanning down vertically through the center of the possible
\r
217 * finder pattern to see if the same proportion is detected.</p>
\r
219 * @param startI row where a finder pattern was detected
\r
220 * @param centerJ center of the section that appears to cross a finder pattern
\r
221 * @param maxCount maximum reasonable number of modules that should be
\r
222 * observed in any reading state, based on the results of the horizontal scan
\r
223 * @return vertical center of finder pattern, or {@link Float#NaN} if not found
\r
225 private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) {
\r
226 MonochromeBitmapSource image = this.image;
\r
228 int maxI = image.getHeight();
\r
229 int[] stateCount = getCrossCheckStateCount();
\r
231 // Start counting up from center
\r
233 while (i >= 0 && image.isBlack(centerJ, i)) {
\r
240 while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) {
\r
244 // If already too many modules in this state or ran off the edge:
\r
245 if (i < 0 || stateCount[1] > maxCount) {
\r
248 while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) {
\r
252 if (stateCount[0] > maxCount) {
\r
256 // Now also count down from center
\r
258 while (i < maxI && image.isBlack(centerJ, i)) {
\r
265 while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) {
\r
269 if (i == maxI || stateCount[3] >= maxCount) {
\r
272 while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) {
\r
276 if (stateCount[4] >= maxCount) {
\r
280 // If we found a finder-pattern-like section, but its size is more than 20% different than
\r
281 // the original, assume it's a false positive
\r
282 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
\r
283 if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
\r
287 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;
\r
291 * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
\r
292 * except it reads horizontally instead of vertically. This is used to cross-cross
\r
293 * check a vertical cross check and locate the real center of the alignment pattern.</p>
\r
295 private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) {
\r
296 MonochromeBitmapSource image = this.image;
\r
298 int maxJ = image.getWidth();
\r
299 int[] stateCount = getCrossCheckStateCount();
\r
302 while (j >= 0 && image.isBlack(j, centerI)) {
\r
309 while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) {
\r
313 if (j < 0 || stateCount[1] > maxCount) {
\r
316 while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) {
\r
320 if (stateCount[0] > maxCount) {
\r
325 while (j < maxJ && image.isBlack(j, centerI)) {
\r
332 while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) {
\r
336 if (j == maxJ || stateCount[3] >= maxCount) {
\r
339 while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) {
\r
343 if (stateCount[4] >= maxCount) {
\r
347 // If we found a finder-pattern-like section, but its size is significantly different than
\r
348 // the original, assume it's a false positive
\r
349 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
\r
350 if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
\r
354 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;
\r
358 * <p>This is called when a horizontal scan finds a possible alignment pattern. It will
\r
359 * cross check with a vertical scan, and if successful, will, ah, cross-cross-check
\r
360 * with another horizontal scan. This is needed primarily to locate the real horizontal
\r
361 * center of the pattern in cases of extreme skew.</p>
\r
363 * <p>If that succeeds the finder pattern location is added to a list that tracks
\r
364 * the number of times each location has been nearly-matched as a finder pattern.
\r
365 * Each additional find is more evidence that the location is in fact a finder
\r
368 * @param stateCount reading state module counts from horizontal scan
\r
369 * @param i row where finder pattern may be found
\r
370 * @param j end of possible finder pattern in row
\r
371 * @return true if a finder pattern candidate was found this time
\r
373 private boolean handlePossibleCenter(int[] stateCount,
\r
376 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
\r
377 float centerJ = centerFromEnd(stateCount, j);
\r
378 float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);
\r
379 if (!Float.isNaN(centerI)) {
\r
381 centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
\r
382 if (!Float.isNaN(centerJ)) {
\r
383 float estimatedModuleSize = (float) stateCountTotal / 7.0f;
\r
384 boolean found = false;
\r
385 int max = possibleCenters.size();
\r
386 for (int index = 0; index < max; index++) {
\r
387 FinderPattern center = (FinderPattern) possibleCenters.elementAt(index);
\r
388 // Look for about the same center and module size:
\r
389 if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
\r
390 center.incrementCount();
\r
396 possibleCenters.addElement(new FinderPattern(centerJ, centerI, estimatedModuleSize));
\r
405 * @return number of rows we could safely skip during scanning, based on the first
\r
406 * two finder patterns that have been located. In some cases their position will
\r
407 * allow us to infer that the third pattern must lie below a certain point farther
\r
408 * down in the image.
\r
410 private int findRowSkip() {
\r
411 int max = possibleCenters.size();
\r
415 FinderPattern firstConfirmedCenter = null;
\r
416 for (int i = 0; i < max; i++) {
\r
417 FinderPattern center = (FinderPattern) possibleCenters.elementAt(i);
\r
418 if (center.getCount() >= CENTER_QUORUM) {
\r
419 if (firstConfirmedCenter == null) {
\r
420 firstConfirmedCenter = center;
\r
422 // We have two confirmed centers
\r
423 // How far down can we skip before resuming looking for the next
\r
424 // pattern? In the worst case, only the difference between the
\r
425 // difference in the x / y coordinates of the two centers.
\r
426 // This is the case where you find top left first. Draw it out.
\r
428 return (int) (Math.abs(firstConfirmedCenter.getX() - center.getX()) -
\r
429 Math.abs(firstConfirmedCenter.getY() - center.getY()));
\r
437 * @return true iff we have found at least 3 finder patterns that have been detected
\r
438 * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
\r
439 * candidates is "pretty similar"
\r
441 private boolean haveMulitplyConfirmedCenters() {
\r
442 int confirmedCount = 0;
\r
443 float totalModuleSize = 0.0f;
\r
444 int max = possibleCenters.size();
\r
445 for (int i = 0; i < max; i++) {
\r
446 FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);
\r
447 if (pattern.getCount() >= CENTER_QUORUM) {
\r
449 totalModuleSize += pattern.getEstimatedModuleSize();
\r
452 if (confirmedCount < 3) {
\r
455 // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
\r
456 // and that we need to keep looking. We detect this by asking if the estimated module sizes
\r
457 // vary too much. We arbitrarily say that when the total deviation from average exceeds
\r
458 // 15% of the total module size estimates, it's too much.
\r
459 float average = totalModuleSize / max;
\r
460 float totalDeviation = 0.0f;
\r
461 for (int i = 0; i < max; i++) {
\r
462 FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);
\r
463 totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);
\r
465 return totalDeviation <= 0.15f * totalModuleSize;
\r
469 * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
\r
470 * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
\r
471 * size differs from the average among those patterns the least
\r
472 * @throws ReaderException if 3 such finder patterns do not exist
\r
474 private FinderPattern[] selectBestPatterns() throws ReaderException {
\r
475 Collections.insertionSort(possibleCenters, new CenterComparator());
\r
477 int max = possibleCenters.size();
\r
478 while (size < max) {
\r
479 if (((FinderPattern) possibleCenters.elementAt(size)).getCount() < CENTER_QUORUM) {
\r
486 // Couldn't find enough finder patterns
\r
487 throw new ReaderException("Could not find three finder patterns");
\r
491 // Throw away all but those first size candidate points we found.
\r
492 possibleCenters.setSize(size);
\r
493 // We need to pick the best three. Find the most
\r
494 // popular ones whose module size is nearest the average
\r
495 float averageModuleSize = 0.0f;
\r
496 for (int i = 0; i < size; i++) {
\r
497 averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize();
\r
499 averageModuleSize /= (float) size;
\r
500 // We don't have java.util.Collections in J2ME
\r
501 Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize));
\r
504 return new FinderPattern[]{
\r
505 (FinderPattern) possibleCenters.elementAt(0),
\r
506 (FinderPattern) possibleCenters.elementAt(1),
\r
507 (FinderPattern) possibleCenters.elementAt(2)
\r
512 * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
\r
514 private static class CenterComparator implements Comparator {
\r
515 public int compare(Object center1, Object center2) {
\r
516 return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount();
\r
521 * <p>Orders by variance from average module size, ascending.</p>
\r
523 private static class ClosestToAverageComparator implements Comparator {
\r
524 private final float averageModuleSize;
\r
526 private ClosestToAverageComparator(float averageModuleSize) {
\r
527 this.averageModuleSize = averageModuleSize;
\r
530 public int compare(Object center1, Object center2) {
\r
531 return Math.abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) <
\r
532 Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ?
\r