Committed C# port from Mohamad
[zxing.git] / csharp / qrcode / detector / AlignmentPatternFinder.cs
diff --git a/csharp/qrcode/detector/AlignmentPatternFinder.cs b/csharp/qrcode/detector/AlignmentPatternFinder.cs
new file mode 100755 (executable)
index 0000000..ed7c41c
--- /dev/null
@@ -0,0 +1,258 @@
+/*\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
+* You may obtain a copy of the License at\r
+*\r
+*      http://www.apache.org/licenses/LICENSE-2.0\r
+*\r
+* Unless required by applicable law or agreed to in writing, software\r
+* distributed under the License is distributed on an "AS IS" BASIS,\r
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+* See the License for the specific language governing permissions and\r
+* limitations under the License.\r
+*/\r
+using System;\r
+using com.google.zxing;\r
+using com.google.zxing.common;\r
+\r
+namespace com.google.zxing.qrcode.detector\r
+{\r
+    public sealed class AlignmentPatternFinder\r
+    { \r
+          private  MonochromeBitmapSource image;\r
+          private  System.Collections.ArrayList possibleCenters;\r
+          private  int startX;\r
+          private  int startY;\r
+          private  int width;\r
+          private  int height;\r
+          private  float moduleSize;\r
+          private  int[] crossCheckStateCount;\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
+          public AlignmentPatternFinder(MonochromeBitmapSource image,\r
+                                 int startX,\r
+                                 int startY,\r
+                                 int width,\r
+                                 int height,\r
+                                 float moduleSize) {\r
+            this.image = image;\r
+            this.possibleCenters = new System.Collections.ArrayList(5);\r
+            this.startX = startX;\r
+            this.startY = startY;\r
+            this.width = width;\r
+            this.height = height;\r
+            this.moduleSize = moduleSize;\r
+            this.crossCheckStateCount = new int[3];\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
+          public AlignmentPattern find() {\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
+            // 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 + ((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
+              stateCount[2] = 0;\r
+              int j = startX;\r
+              // Burn off leading white pixels before anything else; if we start in the middle of\r
+              // a white run, it doesn't make sense to count its length, since we don't know if the\r
+              // white run continued to the left of the start point\r
+              while (j < maxJ && !luminanceRow.get(j - startX)) {\r
+                j++;\r
+              }\r
+              int currentState = 0;\r
+              while (j < maxJ) {\r
+                if (luminanceRow.get(j - startX)) {\r
+                  // Black pixel\r
+                  if (currentState == 1) { // Counting black pixels\r
+                    stateCount[currentState]++;\r
+                  } else { // Counting white pixels\r
+                    if (currentState == 2) { // A winner?\r
+                      if (foundPatternCross(stateCount)) { // Yes\r
+                        AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);\r
+                        if (confirmed != null) {\r
+                          return confirmed;\r
+                        }\r
+                      }\r
+                      stateCount[0] = stateCount[2];\r
+                      stateCount[1] = 1;\r
+                      stateCount[2] = 0;\r
+                      currentState = 1;\r
+                    } else {\r
+                      stateCount[++currentState]++;\r
+                    }\r
+                  }\r
+                } else { // White pixel\r
+                  if (currentState == 1) { // Counting black pixels\r
+                    currentState++;\r
+                  }\r
+                  stateCount[currentState]++;\r
+                }\r
+                j++;\r
+              }\r
+              if (foundPatternCross(stateCount)) {\r
+                AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ);\r
+                if (confirmed != null) {\r
+                  return confirmed;\r
+                }\r
+              }\r
+\r
+            }\r
+\r
+            // Hmm, nothing we saw was observed and confirmed twice. If we had\r
+            // any guess at all, return it.\r
+            if (!(possibleCenters.Count==0)) {\r
+              return (AlignmentPattern) possibleCenters[0];\r
+            }\r
+\r
+            throw new ReaderException();\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 bool foundPatternCross(int[] stateCount) {\r
+            float moduleSize = this.moduleSize;\r
+            float maxVariance = moduleSize / 2.0f;\r
+            for (int i = 0; i < 3; i++) {\r
+              if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance) {\r
+                return false;\r
+              }\r
+            }\r
+            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, int originalStateCountTotal) {\r
+            MonochromeBitmapSource image = this.image;\r
+\r
+            int maxI = image.getHeight();\r
+            int[] stateCount = crossCheckStateCount;\r
+            stateCount[0] = 0;\r
+            stateCount[1] = 0;\r
+            stateCount[2] = 0;\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
+            while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[0] <= maxCount) {\r
+              stateCount[0]++;\r
+              i--;\r
+            }\r
+            if (stateCount[0] > maxCount) {\r
+                return float.NaN;\r
+            }\r
+\r
+            // Now also count down from center\r
+            i = startI + 1;\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) && stateCount[2] <= maxCount) {\r
+              stateCount[2]++;\r
+              i++;\r
+            }\r
+            if (stateCount[2] > maxCount) {\r
+                return float.NaN;\r
+            }\r
+\r
+            int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];\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>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
+            int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];\r
+            float centerJ = centerFromEnd(stateCount, j);\r
+            float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal);\r
+            if (!Single.IsNaN(centerI))\r
+            {\r
+              float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;\r
+              int max = possibleCenters.Count;\r
+              for (int index = 0; index < max; index++) {\r
+                AlignmentPattern center = (AlignmentPattern) possibleCenters[index];\r
+                // Look for about the same center and module size:\r
+                if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {\r
+                  return new AlignmentPattern(centerJ, centerI, estimatedModuleSize);\r
+                }\r
+              }\r
+              // Hadn't found this before; save it\r
+              possibleCenters.Add(new AlignmentPattern(centerJ, centerI, estimatedModuleSize));\r
+            }\r
+            return null;\r
+          }\r
+    \r
+    \r
+    }\r
+}
\ No newline at end of file