Modified some comments to reflect that these objects are thread-safe but not reentrant.
[zxing.git] / core / src / com / google / zxing / qrcode / detector / FinderPatternFinder.java
index a834f06..1540402 100755 (executable)
@@ -1,5 +1,5 @@
 /*\r
- * Copyright 2007 Google Inc.\r
+ * Copyright 2007 ZXing authors\r
  *\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
@@ -16,6 +16,7 @@
 \r
 package com.google.zxing.qrcode.detector;\r
 \r
+import com.google.zxing.DecodeHintType;\r
 import com.google.zxing.MonochromeBitmapSource;\r
 import com.google.zxing.ReaderException;\r
 import com.google.zxing.ResultPoint;\r
@@ -23,48 +24,70 @@ import com.google.zxing.common.BitArray;
 import com.google.zxing.common.Collections;\r
 import com.google.zxing.common.Comparator;\r
 \r
+import java.util.Hashtable;\r
 import java.util.Vector;\r
 \r
 /**\r
  * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square\r
  * markers at three corners of a QR Code.</p>\r
  *\r
- * <p>This class is not thread-safe and should not be reused.</p>\r
+ * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.\r
  *\r
- * @author srowen@google.com (Sean Owen)\r
+ * @author Sean Owen\r
  */\r
-final class FinderPatternFinder {\r
+public class FinderPatternFinder {\r
 \r
   private static final int CENTER_QUORUM = 2;\r
-  private static final int BIG_SKIP = 3;\r
+  protected static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center\r
+  protected static final int MAX_MODULES = 57; // support up to version 10 for mobile clients\r
+  private static final int INTEGER_MATH_SHIFT = 8;\r
 \r
   private final MonochromeBitmapSource image;\r
   private final Vector possibleCenters;\r
   private boolean hasSkipped;\r
+  private final int[] crossCheckStateCount;\r
 \r
   /**\r
    * <p>Creates a finder that will search the image for three finder patterns.</p>\r
    *\r
    * @param image image to search\r
    */\r
-  FinderPatternFinder(MonochromeBitmapSource image) {\r
+  public FinderPatternFinder(MonochromeBitmapSource image) {\r
     this.image = image;\r
     this.possibleCenters = new Vector();\r
+    this.crossCheckStateCount = new int[5];\r
   }\r
 \r
-  FinderPatternInfo find() throws ReaderException {\r
+  protected MonochromeBitmapSource getImage() {\r
+    return image;\r
+  }\r
+\r
+  protected Vector getPossibleCenters() {\r
+    return possibleCenters;\r
+  }\r
+\r
+  FinderPatternInfo find(Hashtable hints) throws ReaderException {\r
+    boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);\r
     int maxI = image.getHeight();\r
     int maxJ = image.getWidth();\r
     // We are looking for black/white/black/white/black modules in\r
     // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far\r
-    int[] stateCount = new int[5];\r
+\r
+    // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the\r
+    // image, and then account for the center being 3 modules in size. This gives the smallest\r
+    // number of pixels the center could be, so skip this often. When trying harder, look for all\r
+    // QR versions regardless of how dense they are.\r
+    int iSkip = (3 * maxI) / (4 * MAX_MODULES);\r
+    if (iSkip < MIN_SKIP || tryHarder) {\r
+      iSkip = MIN_SKIP;\r
+    }\r
+\r
     boolean done = false;\r
-    // We can afford to examine every few lines until we've started finding\r
-    // the patterns\r
-    int iSkip = BIG_SKIP;\r
+    int[] stateCount = new int[5];\r
+    BitArray blackRow = new BitArray(maxJ);\r
     for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {\r
       // Get a row of black/white values\r
-      BitArray blackRow = image.getBlackRow(i, null, 0, maxJ);\r
+      blackRow = image.getBlackRow(i, blackRow, 0, maxJ);\r
       stateCount[0] = 0;\r
       stateCount[1] = 0;\r
       stateCount[2] = 0;\r
@@ -84,9 +107,11 @@ final class FinderPatternFinder {
               if (foundPatternCross(stateCount)) { // Yes\r
                 boolean confirmed = handlePossibleCenter(stateCount, i, j);\r
                 if (confirmed) {\r
-                  iSkip = 1; // Go back to examining each line\r
+                  // Start examining every other line. Checking each line turned out to be too\r
+                  // expensive and didn't improve performance.\r
+                  iSkip = 2;\r
                   if (hasSkipped) {\r
-                    done = haveMulitplyConfirmedCenters();\r
+                    done = haveMultiplyConfirmedCenters();\r
                   } else {\r
                     int rowSkip = findRowSkip();\r
                     if (rowSkip > stateCount[2]) {\r
@@ -138,20 +163,16 @@ final class FinderPatternFinder {
           iSkip = stateCount[0];\r
           if (hasSkipped) {\r
             // Found a third one\r
-            done = haveMulitplyConfirmedCenters();\r
+            done = haveMultiplyConfirmedCenters();\r
           }\r
         }\r
       }\r
     }\r
 \r
     FinderPattern[] patternInfo = selectBestPatterns();\r
-    patternInfo = orderBestPatterns(patternInfo);\r
-    float totalModuleSize = 0.0f;\r
-    for (int i = 0; i < patternInfo.length; i++) {\r
-      totalModuleSize += patternInfo[i].getEstimatedModuleSize();\r
-    }\r
+    ResultPoint.orderBestPatterns(patternInfo);\r
 \r
-    return new FinderPatternInfo(totalModuleSize / (float) patternInfo.length, patternInfo);\r
+    return new FinderPatternInfo(patternInfo);\r
   }\r
 \r
   /**\r
@@ -164,28 +185,38 @@ final class FinderPatternFinder {
 \r
   /**\r
    * @param stateCount count of black/white/black/white/black pixels just read\r
-   * @return true iff the proportions of the counts is close enough to the 1/13/1/1 ratios\r
-   *  used by finder patterns to be considered a match\r
+   * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios\r
+   *         used by finder patterns to be considered a match\r
    */\r
-  private static boolean foundPatternCross(int[] stateCount) {\r
+  protected static boolean foundPatternCross(int[] stateCount) {\r
     int totalModuleSize = 0;\r
     for (int i = 0; i < 5; i++) {\r
-      if (stateCount[i] == 0) {\r
+      int count = stateCount[i];\r
+      if (count == 0) {\r
         return false;\r
       }\r
-      totalModuleSize += stateCount[i];\r
+      totalModuleSize += count;\r
     }\r
     if (totalModuleSize < 7) {\r
       return false;\r
     }\r
-    float moduleSize = (float) totalModuleSize / 7.0f;\r
-    float maxVariance = moduleSize / 2.5f;\r
-    // Allow less than 40% variance from 1-1-3-1-1 proportions\r
-    return  Math.abs(moduleSize - stateCount[0]) < maxVariance &&\r
-            Math.abs(moduleSize - stateCount[1]) < maxVariance &&\r
-            Math.abs(3.0f * moduleSize - stateCount[2]) < 3.0f * maxVariance &&\r
-            Math.abs(moduleSize - stateCount[3]) < maxVariance &&\r
-            Math.abs(moduleSize - stateCount[4]) < maxVariance;\r
+    int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;\r
+    int maxVariance = moduleSize / 2;\r
+    // Allow less than 50% variance from 1-1-3-1-1 proportions\r
+    return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance &&\r
+        Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance &&\r
+        Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance &&\r
+        Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance &&\r
+        Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;\r
+  }\r
+\r
+  private int[] getCrossCheckStateCount() {\r
+    crossCheckStateCount[0] = 0;\r
+    crossCheckStateCount[1] = 0;\r
+    crossCheckStateCount[2] = 0;\r
+    crossCheckStateCount[3] = 0;\r
+    crossCheckStateCount[4] = 0;\r
+    return crossCheckStateCount;\r
   }\r
 \r
   /**\r
@@ -196,14 +227,14 @@ final class FinderPatternFinder {
    * @param startI row where a finder pattern was detected\r
    * @param centerJ center of the section that appears to cross a finder pattern\r
    * @param maxCount maximum reasonable number of modules that should be\r
-   *  observed in any reading state, based on the results of the horizontal scan\r
+   * observed in any reading state, based on the results of the horizontal scan\r
    * @return vertical center of finder pattern, or {@link Float#NaN} if not found\r
    */\r
-  private float crossCheckVertical(int startI, int centerJ, int maxCount) {\r
+  private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) {\r
     MonochromeBitmapSource image = this.image;\r
 \r
     int maxI = image.getHeight();\r
-    int[] stateCount = new int[5];\r
+    int[] stateCount = getCrossCheckStateCount();\r
 \r
     // Start counting up from center\r
     int i = startI;\r
@@ -226,7 +257,7 @@ final class FinderPatternFinder {
       stateCount[0]++;\r
       i--;\r
     }\r
-    if (i < 0 || stateCount[0] > maxCount) {\r
+    if (stateCount[0] > maxCount) {\r
       return Float.NaN;\r
     }\r
 \r
@@ -254,19 +285,26 @@ final class FinderPatternFinder {
       return Float.NaN;\r
     }\r
 \r
+    // If we found a finder-pattern-like section, but its size is more than 20% different than\r
+    // the original, assume it's a false positive\r
+    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];\r
+    if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\r
+      return Float.NaN;\r
+    }\r
+\r
     return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;\r
   }\r
 \r
   /**\r
-   * <p>Like {@link #crossCheckVertical(int, int, int)}, and in fact is basically identical,\r
+   * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,\r
    * except it reads horizontally instead of vertically. This is used to cross-cross\r
    * check a vertical cross check and locate the real center of the alignment pattern.</p>\r
    */\r
-  private float crossCheckHorizontal(int startJ, int centerI, int maxCount) {\r
+  private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) {\r
     MonochromeBitmapSource image = this.image;\r
 \r
     int maxJ = image.getWidth();\r
-    int[] stateCount = new int[5];\r
+    int[] stateCount = getCrossCheckStateCount();\r
 \r
     int j = startJ;\r
     while (j >= 0 && image.isBlack(j, centerI)) {\r
@@ -287,7 +325,7 @@ final class FinderPatternFinder {
       stateCount[0]++;\r
       j--;\r
     }\r
-    if (j < 0 || stateCount[0] > maxCount) {\r
+    if (stateCount[0] > maxCount) {\r
       return Float.NaN;\r
     }\r
 \r
@@ -314,6 +352,13 @@ final class FinderPatternFinder {
       return Float.NaN;\r
     }\r
 \r
+    // If we found a finder-pattern-like section, but its size is significantly different than\r
+    // the original, assume it's a false positive\r
+    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];\r
+    if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\r
+      return Float.NaN;\r
+    }\r
+\r
     return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;\r
   }\r
 \r
@@ -333,17 +378,17 @@ final class FinderPatternFinder {
    * @param j end of possible finder pattern in row\r
    * @return true if a finder pattern candidate was found this time\r
    */\r
-  private boolean handlePossibleCenter(int[] stateCount,\r
+  protected boolean handlePossibleCenter(int[] stateCount,\r
                                        int i,\r
                                        int j) {\r
+    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];\r
     float centerJ = centerFromEnd(stateCount, j);\r
-    float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2]);\r
+    float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);\r
     if (!Float.isNaN(centerI)) {\r
       // Re-cross check\r
-      centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2]);\r
+      centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);\r
       if (!Float.isNaN(centerJ)) {\r
-        float estimatedModuleSize =\r
-          (float) (stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]) / 7.0f;\r
+        float estimatedModuleSize = (float) stateCountTotal / 7.0f;\r
         boolean found = false;\r
         int max = possibleCenters.size();\r
         for (int index = 0; index < max; index++) {\r
@@ -366,9 +411,9 @@ final class FinderPatternFinder {
 \r
   /**\r
    * @return number of rows we could safely skip during scanning, based on the first\r
-   *  two finder patterns that have been located. In some cases their position will\r
-   *  allow us to infer that the third pattern must lie below a certain point farther\r
-   *  down in the image.\r
+   *         two finder patterns that have been located. In some cases their position will\r
+   *         allow us to infer that the third pattern must lie below a certain point farther\r
+   *         down in the image.\r
    */\r
   private int findRowSkip() {\r
     int max = possibleCenters.size();\r
@@ -386,10 +431,10 @@ final class FinderPatternFinder {
           // How far down can we skip before resuming looking for the next\r
           // pattern? In the worst case, only the difference between the\r
           // difference in the x / y coordinates of the two centers.\r
-          // This is the case where you find top left first. Draw it out.\r
+          // This is the case where you find top left last.\r
           hasSkipped = true;\r
-          return (int) Math.abs(Math.abs(firstConfirmedCenter.getX() - center.getX()) -\r
-                                Math.abs(firstConfirmedCenter.getY() - center.getY()));\r
+          return (int) (Math.abs(firstConfirmedCenter.getX() - center.getX()) -\r
+              Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2;\r
         }\r
       }\r
     }\r
@@ -398,25 +443,40 @@ final class FinderPatternFinder {
 \r
   /**\r
    * @return true iff we have found at least 3 finder patterns that have been detected\r
-   *  at least {@link #CENTER_QUORUM} times each\r
+   *         at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the\r
+   *         candidates is "pretty similar"\r
    */\r
-  private boolean haveMulitplyConfirmedCenters() {\r
-    int count = 0;\r
+  private boolean haveMultiplyConfirmedCenters() {\r
+    int confirmedCount = 0;\r
+    float totalModuleSize = 0.0f;\r
     int max = possibleCenters.size();\r
     for (int i = 0; i < max; i++) {\r
-      if (((FinderPattern) possibleCenters.elementAt(i)).getCount() >= CENTER_QUORUM) {\r
-        if (++count == 3) {\r
-          return true;\r
-        }\r
+      FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);\r
+      if (pattern.getCount() >= CENTER_QUORUM) {\r
+        confirmedCount++;\r
+        totalModuleSize += pattern.getEstimatedModuleSize();\r
       }\r
     }\r
-    return false;\r
+    if (confirmedCount < 3) {\r
+      return false;\r
+    }\r
+    // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"\r
+    // and that we need to keep looking. We detect this by asking if the estimated module sizes\r
+    // vary too much. We arbitrarily say that when the total deviation from average exceeds\r
+    // 15% of the total module size estimates, it's too much.\r
+    float average = totalModuleSize / (float) max;\r
+    float totalDeviation = 0.0f;\r
+    for (int i = 0; i < max; i++) {\r
+      FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);\r
+      totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);\r
+    }\r
+    return totalDeviation <= 0.05f * totalModuleSize;\r
   }\r
 \r
   /**\r
    * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are\r
-   *  those that have been detected at least {@link #CENTER_QUORUM} times, and whose module\r
-   *  size differs from the average among those patterns the least\r
+   *         those that have been detected at least {@link #CENTER_QUORUM} times, and whose module\r
+   *         size differs from the average among those patterns the least\r
    * @throws ReaderException if 3 such finder patterns do not exist\r
    */\r
   private FinderPattern[] selectBestPatterns() throws ReaderException {\r
@@ -432,96 +492,30 @@ final class FinderPatternFinder {
 \r
     if (size < 3) {\r
       // Couldn't find enough finder patterns\r
-      throw new ReaderException("Could not find three finder patterns");\r
-    }\r
-\r
-    if (size == 3) {\r
-      // Found just enough -- hope these are good!\r
-      return new FinderPattern[] {\r
-        (FinderPattern) possibleCenters.elementAt(0),\r
-        (FinderPattern) possibleCenters.elementAt(1),\r
-        (FinderPattern) possibleCenters.elementAt(2) \r
-      };\r
+      throw ReaderException.getInstance();\r
     }\r
 \r
-    possibleCenters.setSize(size);\r
-\r
-    // Hmm, multiple found. We need to pick the best three. Find the most\r
-    // popular ones whose module size is nearest the average\r
-\r
-    float averageModuleSize = 0.0f;\r
-    for (int i = 0; i < size; i++) {\r
-      averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize();\r
+    if (size > 3) {\r
+      // Throw away all but those first size candidate points we found.\r
+      possibleCenters.setSize(size);\r
+      //  We need to pick the best three. Find the most\r
+      // popular ones whose module size is nearest the average\r
+      float averageModuleSize = 0.0f;\r
+      for (int i = 0; i < size; i++) {\r
+        averageModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize();\r
+      }\r
+      averageModuleSize /= (float) size;\r
+      // We don't have java.util.Collections in J2ME\r
+      Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize));\r
     }\r
-    averageModuleSize /= (float) size;\r
-\r
-    // We don't have java.util.Collections in J2ME\r
-    Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize));\r
 \r
-    return new FinderPattern[] {\r
-      (FinderPattern) possibleCenters.elementAt(0),\r
-      (FinderPattern) possibleCenters.elementAt(1),\r
-      (FinderPattern) possibleCenters.elementAt(2)\r
+    return new FinderPattern[]{\r
+        (FinderPattern) possibleCenters.elementAt(0),\r
+        (FinderPattern) possibleCenters.elementAt(1),\r
+        (FinderPattern) possibleCenters.elementAt(2)\r
     };\r
   }\r
 \r
-  /**\r
-   * <p>Having found three "best" finder patterns we need to decide which is the top-left, top-right,\r
-   * bottom-left. We assume that the one closest to the other two is the top-left one; this is not\r
-   * strictly true (imagine extreme perspective distortion) but for the moment is a serviceable assumption.\r
-   * Lastly we sort top-right from bottom-left by figuring out orientation from vector cross products.</p>\r
-   *\r
-   * @param patterns three best {@link FinderPattern}s\r
-   * @return same {@link FinderPattern}s ordered bottom-left, top-left, top-right\r
-   */\r
-  private static FinderPattern[] orderBestPatterns(FinderPattern[] patterns) {\r
-\r
-    // Find distances between pattern centers\r
-    float abDistance = distance(patterns[0], patterns[1]);\r
-    float bcDistance = distance(patterns[1], patterns[2]);\r
-    float acDistance = distance(patterns[0], patterns[2]);\r
-\r
-    FinderPattern topLeft;\r
-    FinderPattern topRight;\r
-    FinderPattern bottomLeft;\r
-    // Assume one closest to other two is top left;\r
-    // topRight and bottomLeft will just be guesses below at first\r
-    if (bcDistance >= abDistance && bcDistance >= acDistance) {\r
-      topLeft = patterns[0];\r
-      topRight = patterns[1];\r
-      bottomLeft = patterns[2];\r
-    } else if (acDistance >= bcDistance && acDistance >= abDistance) {\r
-      topLeft = patterns[1];\r
-      topRight = patterns[0];\r
-      bottomLeft = patterns[2];\r
-    } else {\r
-      topLeft = patterns[2];\r
-      topRight = patterns[0];\r
-      bottomLeft = patterns[1];\r
-    }\r
-\r
-    // Use cross product to figure out which of other1/2 is the bottom left\r
-    // pattern. The vector "top-left -> bottom-left" x "top-left -> top-right"\r
-    // should yield a vector with positive z component\r
-    if ((bottomLeft.getY() - topLeft.getY()) * (topRight.getX() - topLeft.getX()) <\r
-        (bottomLeft.getX() - topLeft.getX()) * (topRight.getY() - topLeft.getY())) {\r
-      FinderPattern temp = topRight;\r
-      topRight = bottomLeft;\r
-      bottomLeft = temp;\r
-    }\r
-\r
-    return new FinderPattern[] {bottomLeft, topLeft, topRight};\r
-  }\r
-\r
-  /**\r
-   * @return distance between two points\r
-   */\r
-  static float distance(ResultPoint pattern1, ResultPoint pattern2) {\r
-    float xDiff = pattern1.getX() - pattern2.getX();\r
-    float yDiff = pattern1.getY() - pattern2.getY();\r
-    return (float) Math.sqrt((double) (xDiff * xDiff + yDiff * yDiff));\r
-  }\r
-\r
   /**\r
    * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>\r
    */\r
@@ -536,14 +530,16 @@ final class FinderPatternFinder {
    */\r
   private static class ClosestToAverageComparator implements Comparator {\r
     private final float averageModuleSize;\r
+\r
     private ClosestToAverageComparator(float averageModuleSize) {\r
       this.averageModuleSize = averageModuleSize;\r
     }\r
+\r
     public int compare(Object center1, Object center2) {\r
       return Math.abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) <\r
-             Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ?\r
-             -1 :\r
-              1;\r
+          Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ?\r
+          -1 :\r
+          1;\r
     }\r
   }\r
 \r