X-Git-Url: http://git.rot13.org/?a=blobdiff_plain;f=core%2Fsrc%2Fcom%2Fgoogle%2Fzxing%2Fqrcode%2Fdetector%2FFinderPatternFinder.java;h=e0b0dc9f22476e7894928094ea928855e50c7591;hb=40b048f52284d19b6605ecc34393abe03e415e37;hp=91f847382d024c03662bf306eddbf2215049f056;hpb=61db77fd4960c475243bfb49cc3b6877aef5d8de;p=zxing.git diff --git a/core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java b/core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java index 91f84738..e0b0dc9f 100755 --- a/core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java +++ b/core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 Google Inc. + * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package com.google.zxing.qrcode.detector; +import com.google.zxing.DecodeHintType; import com.google.zxing.MonochromeBitmapSource; import com.google.zxing.ReaderException; import com.google.zxing.ResultPoint; @@ -23,6 +24,7 @@ import com.google.zxing.common.BitArray; import com.google.zxing.common.Collections; import com.google.zxing.common.Comparator; +import java.util.Hashtable; import java.util.Vector; /** @@ -31,40 +33,61 @@ import java.util.Vector; * *

This class is not thread-safe and should not be reused.

* - * @author srowen@google.com (Sean Owen) + * @author Sean Owen */ -final class FinderPatternFinder { +public class FinderPatternFinder { private static final int CENTER_QUORUM = 2; - private static final int BIG_SKIP = 3; + protected static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center + protected static final int MAX_MODULES = 57; // support up to version 10 for mobile clients + private static final int INTEGER_MATH_SHIFT = 8; private final MonochromeBitmapSource image; private final Vector possibleCenters; private boolean hasSkipped; + private final int[] crossCheckStateCount; /** *

Creates a finder that will search the image for three finder patterns.

* * @param image image to search */ - FinderPatternFinder(MonochromeBitmapSource image) { + public FinderPatternFinder(MonochromeBitmapSource image) { this.image = image; this.possibleCenters = new Vector(); + this.crossCheckStateCount = new int[5]; } - FinderPatternInfo find() throws ReaderException { + protected MonochromeBitmapSource getImage() { + return image; + } + + protected Vector getPossibleCenters() { + return possibleCenters; + } + + FinderPatternInfo find(Hashtable hints) throws ReaderException { + boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); int maxI = image.getHeight(); int maxJ = image.getWidth(); // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far - int[] stateCount = new int[5]; + + // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the + // image, and then account for the center being 3 modules in size. This gives the smallest + // number of pixels the center could be, so skip this often. When trying harder, look for all + // QR versions regardless of how dense they are. + int iSkip = (3 * maxI) / (4 * MAX_MODULES); + if (iSkip < MIN_SKIP || tryHarder) { + iSkip = MIN_SKIP; + } + boolean done = false; - // We can afford to examine every few lines until we've started finding - // the patterns - int iSkip = BIG_SKIP; + int[] stateCount = new int[5]; + BitArray blackRow = new BitArray(maxJ); for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values - BitArray blackRow = image.getBlackRow(i, null, 0, maxJ); + blackRow = image.getBlackRow(i, blackRow, 0, maxJ); stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; @@ -84,9 +107,11 @@ final class FinderPatternFinder { if (foundPatternCross(stateCount)) { // Yes boolean confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { - iSkip = 1; // Go back to examining each line + // Start examining every other line. Checking each line turned out to be too + // expensive and didn't improve performance. + iSkip = 2; if (hasSkipped) { - done = haveMulitplyConfirmedCenters(); + done = haveMultiplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { @@ -138,14 +163,14 @@ final class FinderPatternFinder { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one - done = haveMulitplyConfirmedCenters(); + done = haveMultiplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = selectBestPatterns(); - patternInfo = orderBestPatterns(patternInfo); + ResultPoint.orderBestPatterns(patternInfo); return new FinderPatternInfo(patternInfo); } @@ -160,28 +185,38 @@ final class FinderPatternFinder { /** * @param stateCount count of black/white/black/white/black pixels just read - * @return true iff the proportions of the counts is close enough to the 1/13/1/1 ratios + * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios * used by finder patterns to be considered a match */ - private static boolean foundPatternCross(int[] stateCount) { + protected static boolean foundPatternCross(int[] stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { - if (stateCount[i] == 0) { + int count = stateCount[i]; + if (count == 0) { return false; } - totalModuleSize += stateCount[i]; + totalModuleSize += count; } if (totalModuleSize < 7) { return false; } - float moduleSize = (float) totalModuleSize / 7.0f; - float maxVariance = moduleSize / 2.0f; + int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; + int maxVariance = moduleSize / 2; // Allow less than 50% variance from 1-1-3-1-1 proportions - return Math.abs(moduleSize - stateCount[0]) < maxVariance && - Math.abs(moduleSize - stateCount[1]) < maxVariance && - Math.abs(3.0f * moduleSize - stateCount[2]) < 3.0f * maxVariance && - Math.abs(moduleSize - stateCount[3]) < maxVariance && - Math.abs(moduleSize - stateCount[4]) < maxVariance; + return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && + Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && + Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && + Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && + Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; + } + + private int[] getCrossCheckStateCount() { + crossCheckStateCount[0] = 0; + crossCheckStateCount[1] = 0; + crossCheckStateCount[2] = 0; + crossCheckStateCount[3] = 0; + crossCheckStateCount[4] = 0; + return crossCheckStateCount; } /** @@ -199,7 +234,7 @@ final class FinderPatternFinder { MonochromeBitmapSource image = this.image; int maxI = image.getHeight(); - int[] stateCount = new int[5]; + int[] stateCount = getCrossCheckStateCount(); // Start counting up from center int i = startI; @@ -269,7 +304,7 @@ final class FinderPatternFinder { MonochromeBitmapSource image = this.image; int maxJ = image.getWidth(); - int[] stateCount = new int[5]; + int[] stateCount = getCrossCheckStateCount(); int j = startJ; while (j >= 0 && image.isBlack(j, centerI)) { @@ -343,7 +378,7 @@ final class FinderPatternFinder { * @param j end of possible finder pattern in row * @return true if a finder pattern candidate was found this time */ - private boolean handlePossibleCenter(int[] stateCount, + protected boolean handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; @@ -396,10 +431,10 @@ final class FinderPatternFinder { // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. - // This is the case where you find top left first. Draw it out. + // This is the case where you find top left last. hasSkipped = true; - return (int) Math.abs(Math.abs(firstConfirmedCenter.getX() - center.getX()) - - Math.abs(firstConfirmedCenter.getY() - center.getY())); + return (int) (Math.abs(firstConfirmedCenter.getX() - center.getX()) - + Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2; } } } @@ -408,19 +443,34 @@ final class FinderPatternFinder { /** * @return true iff we have found at least 3 finder patterns that have been detected - * at least {@link #CENTER_QUORUM} times each + * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the + * candidates is "pretty similar" */ - private boolean haveMulitplyConfirmedCenters() { - int count = 0; + private boolean haveMultiplyConfirmedCenters() { + int confirmedCount = 0; + float totalModuleSize = 0.0f; int max = possibleCenters.size(); for (int i = 0; i < max; i++) { - if (((FinderPattern) possibleCenters.elementAt(i)).getCount() >= CENTER_QUORUM) { - if (++count == 3) { - return true; - } + FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i); + if (pattern.getCount() >= CENTER_QUORUM) { + confirmedCount++; + totalModuleSize += pattern.getEstimatedModuleSize(); } } - return false; + if (confirmedCount < 3) { + return false; + } + // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" + // and that we need to keep looking. We detect this by asking if the estimated module sizes + // vary too much. We arbitrarily say that when the total deviation from average exceeds + // 15% of the total module size estimates, it's too much. + float average = totalModuleSize / (float) max; + float totalDeviation = 0.0f; + for (int i = 0; i < max; i++) { + FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i); + totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average); + } + return totalDeviation <= 0.05f * totalModuleSize; } /** @@ -442,31 +492,22 @@ final class FinderPatternFinder { if (size < 3) { // Couldn't find enough finder patterns - throw new ReaderException("Could not find three finder patterns"); + throw ReaderException.getInstance(); } - if (size == 3) { - // Found just enough -- hope these are good! - return new FinderPattern[]{ - (FinderPattern) possibleCenters.elementAt(0), - (FinderPattern) possibleCenters.elementAt(1), - (FinderPattern) possibleCenters.elementAt(2) - }; - } - - possibleCenters.setSize(size); - - // Hmm, multiple found. We need to pick the best three. Find the most - // popular ones whose module size is nearest the average - - float averageModuleSize = 0.0f; - for (int i = 0; i < size; i++) { - averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize(); + if (size > 3) { + // Throw away all but those first size candidate points we found. + possibleCenters.setSize(size); + // We need to pick the best three. Find the most + // popular ones whose module size is nearest the average + float averageModuleSize = 0.0f; + for (int i = 0; i < size; i++) { + averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize(); + } + averageModuleSize /= (float) size; + // We don't have java.util.Collections in J2ME + Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize)); } - averageModuleSize /= (float) size; - - // We don't have java.util.Collections in J2ME - Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize)); return new FinderPattern[]{ (FinderPattern) possibleCenters.elementAt(0), @@ -475,63 +516,6 @@ final class FinderPatternFinder { }; } - /** - *

Having found three "best" finder patterns we need to decide which is the top-left, top-right, - * bottom-left. We assume that the one closest to the other two is the top-left one; this is not - * strictly true (imagine extreme perspective distortion) but for the moment is a serviceable assumption. - * Lastly we sort top-right from bottom-left by figuring out orientation from vector cross products.

- * - * @param patterns three best {@link FinderPattern}s - * @return same {@link FinderPattern}s ordered bottom-left, top-left, top-right - */ - private static FinderPattern[] orderBestPatterns(FinderPattern[] patterns) { - - // Find distances between pattern centers - float abDistance = distance(patterns[0], patterns[1]); - float bcDistance = distance(patterns[1], patterns[2]); - float acDistance = distance(patterns[0], patterns[2]); - - FinderPattern topLeft; - FinderPattern topRight; - FinderPattern bottomLeft; - // Assume one closest to other two is top left; - // topRight and bottomLeft will just be guesses below at first - if (bcDistance >= abDistance && bcDistance >= acDistance) { - topLeft = patterns[0]; - topRight = patterns[1]; - bottomLeft = patterns[2]; - } else if (acDistance >= bcDistance && acDistance >= abDistance) { - topLeft = patterns[1]; - topRight = patterns[0]; - bottomLeft = patterns[2]; - } else { - topLeft = patterns[2]; - topRight = patterns[0]; - bottomLeft = patterns[1]; - } - - // Use cross product to figure out which of other1/2 is the bottom left - // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right" - // should yield a vector with positive z component - if ((bottomLeft.getY() - topLeft.getY()) * (topRight.getX() - topLeft.getX()) < - (bottomLeft.getX() - topLeft.getX()) * (topRight.getY() - topLeft.getY())) { - FinderPattern temp = topRight; - topRight = bottomLeft; - bottomLeft = temp; - } - - return new FinderPattern[]{bottomLeft, topLeft, topRight}; - } - - /** - * @return distance between two points - */ - static float distance(ResultPoint pattern1, ResultPoint pattern2) { - float xDiff = pattern1.getX() - pattern2.getX(); - float yDiff = pattern1.getY() - pattern2.getY(); - return (float) Math.sqrt((double) (xDiff * xDiff + yDiff * yDiff)); - } - /** *

Orders by {@link FinderPattern#getCount()}, descending.

*/