More javadoc
authorsrowen <srowen@59b500cc-1b3d-0410-9834-0bbf25fbcc57>
Wed, 7 Nov 2007 06:42:22 +0000 (06:42 +0000)
committersrowen <srowen@59b500cc-1b3d-0410-9834-0bbf25fbcc57>
Wed, 7 Nov 2007 06:42:22 +0000 (06:42 +0000)
git-svn-id: http://zxing.googlecode.com/svn/trunk@14 59b500cc-1b3d-0410-9834-0bbf25fbcc57

core/src/com/google/zxing/qrcode/detector/AlignmentPattern.java
core/src/com/google/zxing/qrcode/detector/AlignmentPatternFinder.java
core/src/com/google/zxing/qrcode/detector/Detector.java
core/src/com/google/zxing/qrcode/detector/FinderPattern.java
core/src/com/google/zxing/qrcode/detector/FinderPatternFinder.java
core/src/com/google/zxing/qrcode/detector/FinderPatternInfo.java

index da0c633..e9ba31d 100644 (file)
@@ -19,6 +19,9 @@ package com.google.zxing.qrcode.detector;
 import com.google.zxing.ResultPoint;
 
 /**
+ * <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
+ * all but the simplest QR Codes.</p>
+ *
  * @author srowen@google.com (Sean Owen)
  */
 public final class AlignmentPattern implements ResultPoint {
@@ -45,6 +48,10 @@ public final class AlignmentPattern implements ResultPoint {
     return estimatedModuleSize;
   }
 
+  /**
+   * <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated
+   * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
+   */
   boolean aboutEquals(float moduleSize, float i, float j) {
     return
         Math.abs(i - posY) <= moduleSize &&
index 1e74bd9..b4e3550 100644 (file)
@@ -23,8 +23,15 @@ import com.google.zxing.common.BitArray;
 import java.util.Vector;\r
 \r
 /**\r
+ * <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder\r
+ * patterns but are smaller and appear at regular intervals throughout the image.</p>\r
+ *\r
  * <p>At the moment this only looks for the bottom-right alignment pattern.</p>\r
  *\r
+ * <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,\r
+ * pasted and stripped down here for maximum performance but does unfortunately duplicate\r
+ * some code.</p>\r
+ *\r
  * <p>This class is not thread-safe.</p>\r
  *\r
  * @author srowen@google.com (Sean Owen)\r
@@ -39,6 +46,16 @@ final class AlignmentPatternFinder {
   private final int height;\r
   private final float moduleSize;\r
 \r
+  /**\r
+   * <p>Creates a finder that will look in a portion of the whole image.</p>\r
+   *\r
+   * @param image image to search\r
+   * @param startX left column from which to start searching\r
+   * @param startY top row from which to start searching\r
+   * @param width width of region to search\r
+   * @param height height of region to search\r
+   * @param moduleSize estimated module size so far\r
+   */\r
   AlignmentPatternFinder(MonochromeBitmapSource image,\r
                          int startX,\r
                          int startY,\r
@@ -54,17 +71,25 @@ final class AlignmentPatternFinder {
     this.moduleSize = moduleSize;\r
   }\r
 \r
+  /**\r
+   * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since\r
+   * it's pretty performance-critical and so is written to be fast foremost.</p>\r
+   *\r
+   * @return {@link AlignmentPattern} if found\r
+   * @throws ReaderException if not found\r
+   */\r
   AlignmentPattern find() throws ReaderException {\r
     int startX = this.startX;\r
     int height = this.height;\r
     int maxJ = startX + width;\r
     int middleI = startY + (height >> 1);\r
     BitArray luminanceRow = new BitArray(width);\r
-    int[] stateCount = new int[3]; // looking for 1 1 1\r
+    // We are looking for black/white/black modules in 1:1:1 ratio;\r
+    // this tracks the number of black/white/black modules seen so far\r
+    int[] stateCount = new int[3];\r
     for (int iGen = 0; iGen < height; iGen++) {\r
       // Search from middle outwards\r
-      int i = middleI +\r
-          ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1));\r
+      int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1));\r
       image.getBlackRow(i, luminanceRow, startX, width);\r
       stateCount[0] = 0;\r
       stateCount[1] = 0;\r
@@ -85,8 +110,7 @@ final class AlignmentPatternFinder {
           } else { // Counting white pixels\r
             if (currentState == 2) { // A winner?\r
               if (foundPatternCross(stateCount)) { // Yes\r
-                AlignmentPattern confirmed =\r
-                    handlePossibleCenter(stateCount, i, j);\r
+                AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);\r
                 if (confirmed != null) {\r
                   return confirmed;\r
                 }\r
@@ -125,10 +149,19 @@ final class AlignmentPatternFinder {
     throw new ReaderException("Could not find alignment pattern");\r
   }\r
 \r
+  /**\r
+   * Given a count of black/white/black pixels just seen and an end position,\r
+   * figures the location of the center of this black/white/black run.\r
+   */\r
   private static float centerFromEnd(int[] stateCount, int end) {\r
     return (float) (end - stateCount[2]) - stateCount[1] / 2.0f;\r
   }\r
 \r
+  /**\r
+   * @param stateCount count of black/white/black pixels just read\r
+   * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios\r
+   *  used by alignment patterns to be considered a match\r
+   */\r
   private boolean foundPatternCross(int[] stateCount) {\r
     float moduleSize = this.moduleSize;\r
     for (int i = 0; i < 3; i++) {\r
@@ -139,16 +172,30 @@ final class AlignmentPatternFinder {
     return true;\r
   }\r
 \r
+  /**\r
+   * <p>After a horizontal scan finds a potential alignment pattern, this method\r
+   * "cross-checks" by scanning down vertically through the center of the possible\r
+   * alignment pattern to see if the same proportion is detected.</p>\r
+   *\r
+   * @param startI row where an alignment pattern was detected\r
+   * @param centerJ center of the section that appears to cross an alignment 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
+   * @return vertical center of alignment pattern, or {@link Float#NaN} if not found\r
+   */\r
   private float crossCheckVertical(int startI, int centerJ, int maxCount) {\r
     MonochromeBitmapSource image = this.image;\r
 \r
     int maxI = image.getHeight();\r
     int[] stateCount = new int[3];\r
+\r
+    // Start counting up from center\r
     int i = startI;\r
     while (i >= 0 && image.isBlack(centerJ, i) && stateCount[1] <= maxCount) {\r
       stateCount[1]++;\r
       i--;\r
     }\r
+    // If already too many modules in this state or ran off the edge:\r
     if (i < 0 || stateCount[1] > maxCount) {\r
       return Float.NaN;\r
     }\r
@@ -160,17 +207,16 @@ final class AlignmentPatternFinder {
       return Float.NaN;\r
     }\r
 \r
+    // Now also count down from center\r
     i = startI + 1;\r
-    while (i < maxI && image.isBlack(centerJ, i) &&\r
-        stateCount[1] <= maxCount) {\r
+    while (i < maxI && image.isBlack(centerJ, i) && stateCount[1] <= maxCount) {\r
       stateCount[1]++;\r
       i++;\r
     }\r
     if (i == maxI || stateCount[1] > maxCount) {\r
       return Float.NaN;\r
     }\r
-    while (i < maxI && !image.isBlack(centerJ, i) &&\r
-        stateCount[2] <= maxCount) {\r
+    while (i < maxI && !image.isBlack(centerJ, i) && stateCount[2] <= maxCount) {\r
       stateCount[2]++;\r
       i++;\r
     }\r
@@ -178,21 +224,25 @@ final class AlignmentPatternFinder {
       return Float.NaN;\r
     }\r
 \r
-    return\r
-        foundPatternCross(stateCount) ?\r
-            centerFromEnd(stateCount, i) :\r
-            Float.NaN;\r
+    return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;\r
   }\r
 \r
-  private AlignmentPattern handlePossibleCenter(int[] stateCount,\r
-                                                int i,\r
-                                                int j) {\r
+  /**\r
+   * <p>This is called when a horizontal scan finds a possible alignment pattern. It will\r
+   * cross check with a vertical scan, and if successful, will see if this pattern had been\r
+   * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have\r
+   * found the alignment pattern.</p>\r
+   *\r
+   * @param stateCount reading state module counts from horizontal scan\r
+   * @param i row where alignment pattern may be found\r
+   * @param j end of possible alignment pattern in row\r
+   * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not\r
+   */\r
+  private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) {\r
     float centerJ = centerFromEnd(stateCount, j);\r
     float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1]);\r
     if (!Float.isNaN(centerI)) {\r
-      float estimatedModuleSize = (float) (stateCount[0] +\r
-          stateCount[1] +\r
-          stateCount[2]) / 3.0f;\r
+      float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;\r
       int max = possibleCenters.size();\r
       for (int index = 0; index < max; index++) {\r
         AlignmentPattern center = (AlignmentPattern) possibleCenters.elementAt(index);\r
index d10fbcb..9847c93 100644 (file)
@@ -23,6 +23,9 @@ import com.google.zxing.common.BitMatrix;
 import com.google.zxing.qrcode.decoder.Version;
 
 /**
+ * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
+ * is rotated or skewed, or partially obscured.</p>
+ *
  * @author srowen@google.com (Sean Owen)
  */
 public final class Detector {
@@ -33,6 +36,12 @@ public final class Detector {
     this.image = image;
   }
 
+    /**
+     * <p>Detects a QR Code in an image, simply.</p>
+     *
+     * @return {@link DetectorResult} encapsulating results of detecting a QR Code
+     * @throws ReaderException if no QR Code can be found
+     */
   public DetectorResult detect() throws ReaderException {
 
     MonochromeBitmapSource image = this.image;
@@ -71,7 +80,7 @@ public final class Detector {
               estAlignmentY,
               (float) i);
           break;
-        } catch (ReaderException de) {
+        } catch (ReaderException re) {
           // try next round
         }
       }
@@ -82,12 +91,7 @@ public final class Detector {
     }
 
     GridSampler sampler = GridSampler.getInstance();
-    BitMatrix bits = sampler.sampleGrid(image,
-        topLeft,
-        topRight,
-        bottomLeft,
-        alignmentPattern,
-        dimension);
+    BitMatrix bits = sampler.sampleGrid(image, topLeft, topRight, bottomLeft, alignmentPattern, dimension);
 
     /*
     try {
@@ -104,8 +108,7 @@ public final class Detector {
           }
         }
       }
-      ImageIO.write(outImage, "PNG",
-          new File("/home/srowen/out.png"));
+      ImageIO.write(outImage, "PNG", new File("/tmp/out.png"));
     } catch (IOException ioe) {
       ioe.printStackTrace();
     }
@@ -120,21 +123,22 @@ public final class Detector {
     return new DetectorResult(bits, points);
   }
 
+  /**
+   * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
+   * of the finder patterns and estimated module size.</p>
+   */
   private static int computeDimension(ResultPoint topLeft,
                                       ResultPoint topRight,
                                       ResultPoint bottomLeft,
-                                      float moduleSize)
-      throws ReaderException {
-    int tltrCentersDimension =
-        round(FinderPatternFinder.distance(topLeft, topRight) / moduleSize);
-    int tlblCentersDimension =
-        round(FinderPatternFinder.distance(topLeft, bottomLeft) / moduleSize);
+                                      float moduleSize) throws ReaderException {
+    int tltrCentersDimension = round(FinderPatternFinder.distance(topLeft, topRight) / moduleSize);
+    int tlblCentersDimension = round(FinderPatternFinder.distance(topLeft, bottomLeft) / moduleSize);
     int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
     switch (dimension & 0x03) { // mod 4
       case 0:
         dimension++;
         break;
-        // 1? do nothing
+      // 1? do nothing
       case 2:
         dimension--;
         break;
@@ -144,16 +148,22 @@ public final class Detector {
     return dimension;
   }
 
-  private float calculateModuleSize(ResultPoint topLeft,
-                                    ResultPoint topRight,
-                                    ResultPoint bottomLeft) {
+  /**
+   * <p>Computes an average estimated module size based on estimated derived from the positions
+   * of the three finder patterns.</p>
+   */
+  private float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) {
     // Take the average
     return (calculateModuleSizeOneWay(topLeft, topRight) +
             calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
   }
 
-  private float calculateModuleSizeOneWay(ResultPoint pattern,
-                                          ResultPoint otherPattern) {
+    /**
+     * <p>Estimates module size based on two finder patterns -- it uses
+     * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
+     * width of each, measuring along the axis between their centers.</p>
+     */
+  private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) {
     float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
                                                             (int) pattern.getY(),
                                                             (int) otherPattern.getX(),
@@ -173,12 +183,25 @@ public final class Detector {
     return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
   }
 
+  /**
+   * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
+   * a finder pattern by looking for a black-white-black run from the center in the direction
+   * of another point (another finder pattern center), and in the opposite direction too.</p>
+   */
   private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
     float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
     result += sizeOfBlackWhiteBlackRun(fromX, fromY, fromX - (toX - fromX), fromY - (toY - fromY));
     return result - 1.0f; // -1 because we counted the middle pixel twice
   }
 
+  /**
+   * <p>This method traces a line from a point in the image, in the direction towards another point.
+   * It begins in a black region, and keeps going until it finds white, then black, then white again.
+   * It reports the distance from the start to this point.</p>
+   *
+   * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
+   * may be skewed or rotated.</p>
+   */
   private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
     // Mild variant of Bresenham's algorithm;
     // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
@@ -227,6 +250,17 @@ public final class Detector {
     return Float.NaN;
   }
 
+  /**
+   * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
+   * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
+   *
+   * @param overallEstModuleSize estimated module size so far
+   * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
+   * @param estAlignmentY y coordinate of above
+   * @param allowanceFactor number of pixels in all directons to search from the center
+   * @return {@link AlignmentPattern} if found, or null otherwise
+   * @throws ReaderException if an unexpected error occurs during detection
+   */
   private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
                                                  int estAlignmentX,
                                                  int estAlignmentY,
@@ -236,11 +270,9 @@ public final class Detector {
     // should be
     int allowance = (int) (allowanceFactor * overallEstModuleSize);
     int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
-    int alignmentAreaRightX = Math.min(image.getWidth() - 1,
-        estAlignmentX + allowance);
+    int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
     int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
-    int alignmentAreaBottomY = Math.min(image.getHeight() - 1,
-        estAlignmentY + allowance);
+    int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
 
     AlignmentPatternFinder alignmentFinder =
         new AlignmentPatternFinder(
@@ -254,7 +286,8 @@ public final class Detector {
   }
 
   /**
-   * Ends up being a bit faster than Math.round()
+   * Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int,
+   * where x.5 rounds up.
    */
   private static int round(float d) {
     return (int) (d + 0.5f);
index 11e0337..1d98fe9 100644 (file)
@@ -19,6 +19,10 @@ package com.google.zxing.qrcode.detector;
 import com.google.zxing.ResultPoint;
 
 /**
+ * <p>Encapsulates a finder pattern, which are the three square patterns found in
+ * the corners of QR Codes. It also encapsulates a count of similar finder patterns,
+ * as a convenience to {@link FinderPatternFinder}'s bookkeeping.</p>
+ *
  * @author srowen@google.com (Sean Owen)
  */
 public final class FinderPattern implements ResultPoint {
@@ -55,6 +59,10 @@ public final class FinderPattern implements ResultPoint {
     this.count++;
   }
 
+  /**
+   * <p>Determines if this finder pattern "about equals" a finder pattern at the stated
+   * position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
+   */
   boolean aboutEquals(float moduleSize, float i, float j) {
     return Math.abs(i - posY) <= moduleSize &&
            Math.abs(j - posX) <= moduleSize &&
index 47a6d62..4ef3d58 100755 (executable)
@@ -26,6 +26,9 @@ import com.google.zxing.common.Comparator;
 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
  *\r
  * @author srowen@google.com (Sean Owen)\r
@@ -39,6 +42,11 @@ final class FinderPatternFinder {
   private final Vector possibleCenters;\r
   private boolean hasSkipped;\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
     this.image = image;\r
     this.possibleCenters = new Vector(5);\r
@@ -47,13 +55,16 @@ final class FinderPatternFinder {
   FinderPatternInfo find() throws ReaderException {\r
     int maxI = image.getHeight();\r
     int maxJ = image.getWidth();\r
-    int[] stateCount = new int[5]; // looking for 1 1 3 1 1\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
     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
     for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {\r
-      BitArray luminanceRow = image.getBlackRow(i, null, 0, maxJ);\r
+      // Get a row of black/white values\r
+      BitArray blackRow = image.getBlackRow(i, null, 0, maxJ);\r
       stateCount[0] = 0;\r
       stateCount[1] = 0;\r
       stateCount[2] = 0;\r
@@ -61,7 +72,7 @@ final class FinderPatternFinder {
       stateCount[4] = 0;\r
       int currentState = 0;\r
       for (int j = 0; j < maxJ; j++) {\r
-        if (luminanceRow.get(j)) {\r
+        if (blackRow.get(j)) {\r
           // Black pixel\r
           if ((currentState & 1) == 1) { // Counting white pixels\r
             currentState++;\r
@@ -71,8 +82,7 @@ final class FinderPatternFinder {
           if ((currentState & 1) == 0) { // Counting black pixels\r
             if (currentState == 4) { // A winner?\r
               if (foundPatternCross(stateCount)) { // Yes\r
-                boolean confirmed =\r
-                    handlePossibleCenter(stateCount, i, j);\r
+                boolean confirmed = handlePossibleCenter(stateCount, i, j);\r
                 if (confirmed) {\r
                   iSkip = 1; // Go back to examining each line\r
                   if (hasSkipped) {\r
@@ -96,7 +106,7 @@ final class FinderPatternFinder {
                   // Advance to next black pixel\r
                   do {\r
                     j++;\r
-                  } while (j < maxJ && !luminanceRow.get(j));\r
+                  } while (j < maxJ && !blackRow.get(j));\r
                   j--; // back up to that last white pixel\r
                 }\r
                 // Clear state to start looking again\r
@@ -141,14 +151,22 @@ final class FinderPatternFinder {
       totalModuleSize += patternInfo[i].getEstimatedModuleSize();\r
     }\r
 \r
-    return new FinderPatternInfo(totalModuleSize / (float) patternInfo.length,\r
-        patternInfo);\r
+    return new FinderPatternInfo(totalModuleSize / (float) patternInfo.length, patternInfo);\r
   }\r
 \r
+  /**\r
+   * Given a count of black/white/black/white/black pixels just seen and an end position,\r
+   * figures the location of the center of this run.\r
+   */\r
   private static float centerFromEnd(int[] stateCount, int end) {\r
     return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;\r
   }\r
 \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
+   */\r
   private static boolean foundPatternCross(int[] stateCount) {\r
     int totalModuleSize = 0;\r
     for (int i = 0; i < 5; i++) {\r
@@ -162,20 +180,31 @@ final class FinderPatternFinder {
     }\r
     int moduleSize = totalModuleSize / 7;\r
     // Allow less than 50% deviance from 1-1-3-1-1 pattern\r
-    return\r
-        Math.abs(moduleSize - stateCount[0]) << 1 <= moduleSize &&\r
+    return  Math.abs(moduleSize - stateCount[0]) << 1 <= moduleSize &&\r
             Math.abs(moduleSize - stateCount[1]) << 1 <= moduleSize &&\r
             Math.abs(3 * moduleSize - stateCount[2]) << 1 <= 3 * moduleSize &&\r
             Math.abs(moduleSize - stateCount[3]) << 1 <= moduleSize &&\r
             Math.abs(moduleSize - stateCount[4]) << 1 <= moduleSize;\r
   }\r
 \r
+  /**\r
+   * <p>After a horizontal scan finds a potential finder pattern, this method\r
+   * "cross-checks" by scanning down vertically through the center of the possible\r
+   * finder pattern to see if the same proportion is detected.</p>\r
+   *\r
+   * @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
+   * @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
     MonochromeBitmapSource image = this.image;\r
 \r
     int maxI = image.getHeight();\r
     int[] stateCount = new int[5];\r
 \r
+    // Start counting up from center\r
     int i = startI;\r
     while (i >= 0 && image.isBlack(centerJ, i)) {\r
       stateCount[2]++;\r
@@ -200,6 +229,7 @@ final class FinderPatternFinder {
       return Float.NaN;\r
     }\r
 \r
+    // Now also count down from center\r
     i = startI + 1;\r
     while (i < maxI && image.isBlack(centerJ, i)) {\r
       stateCount[2]++;\r
@@ -226,6 +256,11 @@ final class FinderPatternFinder {
     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
+   * 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
     MonochromeBitmapSource image = this.image;\r
 \r
@@ -244,7 +279,6 @@ final class FinderPatternFinder {
       stateCount[1]++;\r
       j--;\r
     }\r
-    // If already too many modules in this state or ran off the edge:\r
     if (j < 0 || stateCount[1] > maxCount) {\r
       return Float.NaN;\r
     }\r
@@ -282,6 +316,22 @@ final class FinderPatternFinder {
     return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;\r
   }\r
 \r
+  /**\r
+   * <p>This is called when a horizontal scan finds a possible alignment pattern. It will\r
+   * cross check with a vertical scan, and if successful, will, ah, cross-cross-check\r
+   * with another horizontal scan. This is needed primarily to locate the real horizontal\r
+   * center of the pattern in cases of extreme skew.</p>\r
+   *\r
+   * <p>If that succeeds the finder pattern location is added to a list that tracks\r
+   * the number of times each location has been nearly-matched as a finder pattern.\r
+   * Each additional find is more evidence that the location is in fact a finder\r
+   * pattern center\r
+   *\r
+   * @param stateCount reading state module counts from horizontal scan\r
+   * @param i row where finder pattern may be found\r
+   * @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
@@ -291,11 +341,8 @@ final class FinderPatternFinder {
       // Re-cross check\r
       centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2]);\r
       if (!Float.isNaN(centerJ)) {\r
-        float estimatedModuleSize = (float) (stateCount[0] +\r
-            stateCount[1] +\r
-            stateCount[2] +\r
-            stateCount[3] +\r
-            stateCount[4]) / 7.0f;\r
+        float estimatedModuleSize =\r
+          (float) (stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]) / 7.0f;\r
         boolean found = false;\r
         int max = possibleCenters.size();\r
         for (int index = 0; index < max; index++) {\r
@@ -308,8 +355,7 @@ final class FinderPatternFinder {
           }\r
         }\r
         if (!found) {\r
-          possibleCenters.addElement(\r
-              new FinderPattern(centerJ, centerI, estimatedModuleSize));\r
+          possibleCenters.addElement(new FinderPattern(centerJ, centerI, estimatedModuleSize));\r
         }\r
         return true;\r
       }\r
@@ -317,6 +363,12 @@ final class FinderPatternFinder {
     return false;\r
   }\r
 \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
+   */\r
   private int findRowSkip() {\r
     int max = possibleCenters.size();\r
     if (max <= 1) {\r
@@ -343,6 +395,10 @@ final class FinderPatternFinder {
     return 0;\r
   }\r
 \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
+   */\r
   private boolean haveMulitplyConfirmedCenters() {\r
     int count = 0;\r
     int max = possibleCenters.size();\r
@@ -356,6 +412,12 @@ final class FinderPatternFinder {
     return false;\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
+   */\r
   private FinderPattern[] selectBestPatterns() throws ReaderException {\r
     Collections.insertionSort(possibleCenters, new CenterComparator());\r
     int size = 0;\r
@@ -393,11 +455,9 @@ final class FinderPatternFinder {
     }\r
     averageModuleSize /= (float) size;\r
 \r
-    Collections.insertionSort(\r
-        possibleCenters,\r
-        new ClosestToAverageComparator(averageModuleSize));\r
+    // We don't have java.util.Collections in J2ME\r
+    Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize));\r
 \r
-    //return confirmedCenters.subList(0, 3).toArray(new FinderPattern[3]);\r
     FinderPattern[] result = new FinderPattern[3];\r
     for (int i = 0; i < 3; i++) {\r
       result[i] = (FinderPattern) possibleCenters.elementAt(i);\r
@@ -405,6 +465,15 @@ final class FinderPatternFinder {
     return result;\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
@@ -415,10 +484,11 @@ final class FinderPatternFinder {
     FinderPattern topLeft;\r
     FinderPattern topRight;\r
     FinderPattern bottomLeft;\r
-    // Assume one closest to other two is top left\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]; // These two are guesses at the moment\r
+      topRight = patterns[1];\r
       bottomLeft = patterns[2];\r
     } else if (acDistance >= bcDistance && acDistance >= abDistance) {\r
       topLeft = patterns[1];\r
@@ -443,18 +513,27 @@ final class FinderPatternFinder {
     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
   private static class CenterComparator implements Comparator {\r
     public int compare(Object center1, Object center2) {\r
       return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount();\r
     }\r
   }\r
 \r
+  /**\r
+   * <p>Orders by variance from average module size, ascending.</p>\r
+   */\r
   private static class ClosestToAverageComparator implements Comparator {\r
     private float averageModuleSize;\r
 \r
index 8f5bc88..10281cd 100644 (file)
@@ -17,6 +17,9 @@
 package com.google.zxing.qrcode.detector;
 
 /**
+ * <p>Encapsulates information about finder patterns in an image, including the location of
+ * the three finder patterns, and their estimated module size.</p>
+ * 
  * @author srowen@google.com (Sean Owen)
  */
 final class FinderPatternInfo {