Small style stuff
[zxing.git] / core / src / com / google / zxing / qrcode / detector / FinderPatternFinder.java
index a518631..9968f00 100755 (executable)
 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.common.BitArray;\r
+import com.google.zxing.NotFoundException;\r
+import com.google.zxing.ResultPoint;\r
+import com.google.zxing.ResultPointCallback;\r
+import com.google.zxing.common.BitMatrix;\r
 import com.google.zxing.common.Collections;\r
 import com.google.zxing.common.Comparator;\r
-import com.google.zxing.common.GenericResultPoint;\r
 \r
 import java.util.Hashtable;\r
 import java.util.Vector;\r
@@ -31,34 +31,48 @@ import java.util.Vector;
  * <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 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 MIN_SKIP = 3; // 1 pixel/module times 3 modules/center\r
-  private static final int MAX_MODULES = 57; // support up to version 10 for mobile clients\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 BitMatrix image;\r
   private final Vector possibleCenters;\r
   private boolean hasSkipped;\r
   private final int[] crossCheckStateCount;\r
+  private final ResultPointCallback resultPointCallback;\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(BitMatrix image) {\r
+    this(image, null);\r
+  }\r
+\r
+  public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) {\r
     this.image = image;\r
     this.possibleCenters = new Vector();\r
     this.crossCheckStateCount = new int[5];\r
+    this.resultPointCallback = resultPointCallback;\r
+  }\r
+\r
+  protected BitMatrix getImage() {\r
+    return image;\r
   }\r
 \r
-  FinderPatternInfo find(Hashtable hints) throws ReaderException {\r
+  protected Vector getPossibleCenters() {\r
+    return possibleCenters;\r
+  }\r
+\r
+  FinderPatternInfo find(Hashtable hints) throws NotFoundException {\r
     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);\r
     int maxI = image.getHeight();\r
     int maxJ = image.getWidth();\r
@@ -69,17 +83,15 @@ final class FinderPatternFinder {
     // 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 = (int) (maxI / (MAX_MODULES * 4.0f) * 3);\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
     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
-      blackRow = image.getBlackRow(i, blackRow, 0, maxJ);\r
       stateCount[0] = 0;\r
       stateCount[1] = 0;\r
       stateCount[2] = 0;\r
@@ -87,7 +99,7 @@ final class FinderPatternFinder {
       stateCount[4] = 0;\r
       int currentState = 0;\r
       for (int j = 0; j < maxJ; j++) {\r
-        if (blackRow.get(j)) {\r
+        if (image.get(j, i)) {\r
           // Black pixel\r
           if ((currentState & 1) == 1) { // Counting white pixels\r
             currentState++;\r
@@ -103,7 +115,7 @@ final class FinderPatternFinder {
                   // 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
@@ -120,11 +132,13 @@ final class FinderPatternFinder {
                     }\r
                   }\r
                 } else {\r
-                  // Advance to next black pixel\r
-                  do {\r
-                    j++;\r
-                  } while (j < maxJ && !blackRow.get(j));\r
-                  j--; // back up to that last white pixel\r
+                  stateCount[0] = stateCount[2];\r
+                  stateCount[1] = stateCount[3];\r
+                  stateCount[2] = stateCount[4];\r
+                  stateCount[3] = 1;\r
+                  stateCount[4] = 0;\r
+                  currentState = 3;\r
+                  continue;\r
                 }\r
                 // Clear state to start looking again\r
                 currentState = 0;\r
@@ -155,14 +169,14 @@ 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
-    GenericResultPoint.orderBestPatterns(patternInfo);\r
+    ResultPoint.orderBestPatterns(patternInfo);\r
 \r
     return new FinderPatternInfo(patternInfo);\r
   }\r
@@ -180,7 +194,7 @@ final class FinderPatternFinder {
    * @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
       int count = stateCount[i];\r
@@ -222,22 +236,23 @@ final class FinderPatternFinder {
    * 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, int originalStateCountTotal) {\r
-    MonochromeBitmapSource image = this.image;\r
+  private float crossCheckVertical(int startI, int centerJ, int maxCount,\r
+      int originalStateCountTotal) {\r
+    BitMatrix image = this.image;\r
 \r
     int maxI = image.getHeight();\r
     int[] stateCount = getCrossCheckStateCount();\r
 \r
     // Start counting up from center\r
     int i = startI;\r
-    while (i >= 0 && image.isBlack(centerJ, i)) {\r
+    while (i >= 0 && image.get(centerJ, i)) {\r
       stateCount[2]++;\r
       i--;\r
     }\r
     if (i < 0) {\r
       return Float.NaN;\r
     }\r
-    while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) {\r
+    while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {\r
       stateCount[1]++;\r
       i--;\r
     }\r
@@ -245,7 +260,7 @@ final class FinderPatternFinder {
     if (i < 0 || stateCount[1] > maxCount) {\r
       return Float.NaN;\r
     }\r
-    while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) {\r
+    while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {\r
       stateCount[0]++;\r
       i--;\r
     }\r
@@ -255,21 +270,21 @@ final class FinderPatternFinder {
 \r
     // Now also count down from center\r
     i = startI + 1;\r
-    while (i < maxI && image.isBlack(centerJ, i)) {\r
+    while (i < maxI && image.get(centerJ, i)) {\r
       stateCount[2]++;\r
       i++;\r
     }\r
     if (i == maxI) {\r
       return Float.NaN;\r
     }\r
-    while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) {\r
+    while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {\r
       stateCount[3]++;\r
       i++;\r
     }\r
     if (i == maxI || stateCount[3] >= maxCount) {\r
       return Float.NaN;\r
     }\r
-    while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) {\r
+    while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {\r
       stateCount[4]++;\r
       i++;\r
     }\r
@@ -277,10 +292,11 @@ 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
+    // If we found a finder-pattern-like section, but its size is more than 40% 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
+    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\r
+        stateCount[4];\r
+    if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {\r
       return Float.NaN;\r
     }\r
 \r
@@ -292,28 +308,29 @@ final class FinderPatternFinder {
    * 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, int originalStateCountTotal) {\r
-    MonochromeBitmapSource image = this.image;\r
+  private float crossCheckHorizontal(int startJ, int centerI, int maxCount,\r
+      int originalStateCountTotal) {\r
+    BitMatrix image = this.image;\r
 \r
     int maxJ = image.getWidth();\r
     int[] stateCount = getCrossCheckStateCount();\r
 \r
     int j = startJ;\r
-    while (j >= 0 && image.isBlack(j, centerI)) {\r
+    while (j >= 0 && image.get(j, centerI)) {\r
       stateCount[2]++;\r
       j--;\r
     }\r
     if (j < 0) {\r
       return Float.NaN;\r
     }\r
-    while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) {\r
+    while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {\r
       stateCount[1]++;\r
       j--;\r
     }\r
     if (j < 0 || stateCount[1] > maxCount) {\r
       return Float.NaN;\r
     }\r
-    while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) {\r
+    while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {\r
       stateCount[0]++;\r
       j--;\r
     }\r
@@ -322,21 +339,21 @@ final class FinderPatternFinder {
     }\r
 \r
     j = startJ + 1;\r
-    while (j < maxJ && image.isBlack(j, centerI)) {\r
+    while (j < maxJ && image.get(j, centerI)) {\r
       stateCount[2]++;\r
       j++;\r
     }\r
     if (j == maxJ) {\r
       return Float.NaN;\r
     }\r
-    while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) {\r
+    while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {\r
       stateCount[3]++;\r
       j++;\r
     }\r
     if (j == maxJ || stateCount[3] >= maxCount) {\r
       return Float.NaN;\r
     }\r
-    while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) {\r
+    while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {\r
       stateCount[4]++;\r
       j++;\r
     }\r
@@ -346,7 +363,8 @@ final class FinderPatternFinder {
 \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
+    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\r
+        stateCount[4];\r
     if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\r
       return Float.NaN;\r
     }\r
@@ -370,10 +388,9 @@ 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
-                                       int i,\r
-                                       int j) {\r
-    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];\r
+  protected boolean handlePossibleCenter(int[] stateCount, int i, int j) {\r
+    int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\r
+        stateCount[4];\r
     float centerJ = centerFromEnd(stateCount, j);\r
     float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);\r
     if (!Float.isNaN(centerI)) {\r
@@ -393,7 +410,11 @@ final class FinderPatternFinder {
           }\r
         }\r
         if (!found) {\r
-          possibleCenters.addElement(new FinderPattern(centerJ, centerI, estimatedModuleSize));\r
+          ResultPoint point = new FinderPattern(centerJ, centerI, estimatedModuleSize);\r
+          possibleCenters.addElement(point);\r
+          if (resultPointCallback != null) {\r
+            resultPointCallback.foundPossibleResultPoint(point);\r
+          }\r
         }\r
         return true;\r
       }\r
@@ -423,10 +444,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(firstConfirmedCenter.getX() - center.getX()) -\r
-              Math.abs(firstConfirmedCenter.getY() - center.getY()));\r
+              Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2;\r
         }\r
       }\r
     }\r
@@ -438,7 +459,7 @@ final class FinderPatternFinder {
    *         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
+  private boolean haveMultiplyConfirmedCenters() {\r
     int confirmedCount = 0;\r
     float totalModuleSize = 0.0f;\r
     int max = possibleCenters.size();\r
@@ -455,50 +476,69 @@ final class FinderPatternFinder {
     // 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 / max;\r
+    // 5% 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.15f * totalModuleSize;\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
-   * @throws ReaderException if 3 such finder patterns do not exist\r
+   * @throws NotFoundException if 3 such finder patterns do not exist\r
    */\r
-  private FinderPattern[] selectBestPatterns() throws ReaderException {\r
-    Collections.insertionSort(possibleCenters, new CenterComparator());\r
-    int size = 0;\r
-    int max = possibleCenters.size();\r
-    while (size < max) {\r
-      if (((FinderPattern) possibleCenters.elementAt(size)).getCount() < CENTER_QUORUM) {\r
-        break;\r
-      }\r
-      size++;\r
-    }\r
+  private FinderPattern[] selectBestPatterns() throws NotFoundException {\r
 \r
-    if (size < 3) {\r
+    int startSize = possibleCenters.size();\r
+    if (startSize < 3) {\r
       // Couldn't find enough finder patterns\r
-      throw ReaderException.getInstance();\r
+      throw NotFoundException.getNotFoundInstance();\r
+    }\r
+\r
+    // Filter outlier possibilities whose module size is too different\r
+    if (startSize > 3) {\r
+      // But we can only afford to do so if we have at least 4 possibilities to choose from\r
+      float totalModuleSize = 0.0f;\r
+      float square = 0.0f;\r
+      for (int i = 0; i < startSize; i++) {\r
+        float size = ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize();\r
+        totalModuleSize += size;\r
+        square += size * size;\r
+      }\r
+      float average = totalModuleSize / (float) startSize;\r
+      float stdDev = (float) Math.sqrt(square / startSize - average * average);\r
+\r
+      Collections.insertionSort(possibleCenters, new FurthestFromAverageComparator(average));\r
+\r
+      float limit = Math.max(0.2f * average, stdDev);\r
+\r
+      for (int i = 0; i < possibleCenters.size() && possibleCenters.size() > 3; i++) {\r
+        FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);\r
+        if (Math.abs(pattern.getEstimatedModuleSize() - average) > limit) {\r
+          possibleCenters.removeElementAt(i);\r
+          i--;\r
+        }\r
+      }\r
     }\r
 \r
-    if (size > 3) {\r
+    if (possibleCenters.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
+      float totalModuleSize = 0.0f;\r
+      for (int i = 0; i < possibleCenters.size(); i++) {\r
+        totalModuleSize += ((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
+      float average = totalModuleSize / (float) possibleCenters.size();\r
+\r
+      Collections.insertionSort(possibleCenters, new CenterComparator(average));\r
+\r
+      possibleCenters.setSize(3);\r
     }\r
 \r
     return new FinderPattern[]{\r
@@ -509,29 +549,36 @@ final class FinderPatternFinder {
   }\r
 \r
   /**\r
-   * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>\r
+   * <p>Orders by furthest from average</p>\r
    */\r
-  private static class CenterComparator implements Comparator {\r
+  private static class FurthestFromAverageComparator implements Comparator {\r
+    private final float average;\r
+    private FurthestFromAverageComparator(float f) {\r
+      average = f;\r
+    }\r
     public int compare(Object center1, Object center2) {\r
-      return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount();\r
+      float dA = Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - average);\r
+      float dB = Math.abs(((FinderPattern) center1).getEstimatedModuleSize() - average);\r
+      return dA < dB ? -1 : (dA == dB ? 0 : 1);\r
     }\r
   }\r
 \r
   /**\r
-   * <p>Orders by variance from average module size, ascending.</p>\r
+   * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>\r
    */\r
-  private static class ClosestToAverageComparator implements Comparator {\r
-    private final float averageModuleSize;\r
-\r
-    private ClosestToAverageComparator(float averageModuleSize) {\r
-      this.averageModuleSize = averageModuleSize;\r
+  private static class CenterComparator implements Comparator {\r
+    private final float average;\r
+    private CenterComparator(float f) {\r
+      average = f;\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
+      if (((FinderPattern) center2).getCount() == ((FinderPattern) center1).getCount()) {\r
+        float dA = Math.abs(((FinderPattern) center2).getEstimatedModuleSize() - average);\r
+        float dB = Math.abs(((FinderPattern) center1).getEstimatedModuleSize() - average);\r
+        return dA < dB ? 1 : (dA == dB ? 0 : -1);\r
+      } else {\r
+        return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount();\r
+      }\r
     }\r
   }\r
 \r