Remove some redundant 'throws'; allocate more reasonably sized StringBuffers for...
[zxing.git] / core / src / com / google / zxing / qrcode / detector / AlignmentPatternFinder.java
1 /*\r
2  * Copyright 2007 ZXing authors\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.google.zxing.qrcode.detector;\r
18 \r
19 import com.google.zxing.ReaderException;\r
20 import com.google.zxing.common.BitMatrix;\r
21 \r
22 import java.util.Vector;\r
23 \r
24 /**\r
25  * <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder\r
26  * patterns but are smaller and appear at regular intervals throughout the image.</p>\r
27  *\r
28  * <p>At the moment this only looks for the bottom-right alignment pattern.</p>\r
29  *\r
30  * <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,\r
31  * pasted and stripped down here for maximum performance but does unfortunately duplicate\r
32  * some code.</p>\r
33  *\r
34  * <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.\r
35  *\r
36  * @author Sean Owen\r
37  */\r
38 final class AlignmentPatternFinder {\r
39 \r
40   private final BitMatrix image;\r
41   private final Vector possibleCenters;\r
42   private final int startX;\r
43   private final int startY;\r
44   private final int width;\r
45   private final int height;\r
46   private final float moduleSize;\r
47   private final int[] crossCheckStateCount;\r
48 \r
49   /**\r
50    * <p>Creates a finder that will look in a portion of the whole image.</p>\r
51    *\r
52    * @param image image to search\r
53    * @param startX left column from which to start searching\r
54    * @param startY top row from which to start searching\r
55    * @param width width of region to search\r
56    * @param height height of region to search\r
57    * @param moduleSize estimated module size so far\r
58    */\r
59   AlignmentPatternFinder(BitMatrix image,\r
60                          int startX,\r
61                          int startY,\r
62                          int width,\r
63                          int height,\r
64                          float moduleSize) {\r
65     this.image = image;\r
66     this.possibleCenters = new Vector(5);\r
67     this.startX = startX;\r
68     this.startY = startY;\r
69     this.width = width;\r
70     this.height = height;\r
71     this.moduleSize = moduleSize;\r
72     this.crossCheckStateCount = new int[3];\r
73   }\r
74 \r
75   /**\r
76    * <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since\r
77    * it's pretty performance-critical and so is written to be fast foremost.</p>\r
78    *\r
79    * @return {@link AlignmentPattern} if found\r
80    * @throws ReaderException if not found\r
81    */\r
82   AlignmentPattern find() throws ReaderException {\r
83     int startX = this.startX;\r
84     int height = this.height;\r
85     int maxJ = startX + width;\r
86     int middleI = startY + (height >> 1);\r
87     // We are looking for black/white/black modules in 1:1:1 ratio;\r
88     // this tracks the number of black/white/black modules seen so far\r
89     int[] stateCount = new int[3];\r
90     for (int iGen = 0; iGen < height; iGen++) {\r
91       // Search from middle outwards\r
92       int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1));\r
93       stateCount[0] = 0;\r
94       stateCount[1] = 0;\r
95       stateCount[2] = 0;\r
96       int j = startX;\r
97       // Burn off leading white pixels before anything else; if we start in the middle of\r
98       // a white run, it doesn't make sense to count its length, since we don't know if the\r
99       // white run continued to the left of the start point\r
100       while (j < maxJ && !image.get(j, i)) {\r
101         j++;\r
102       }\r
103       int currentState = 0;\r
104       while (j < maxJ) {\r
105         if (image.get(j, i)) {\r
106           // Black pixel\r
107           if (currentState == 1) { // Counting black pixels\r
108             stateCount[currentState]++;\r
109           } else { // Counting white pixels\r
110             if (currentState == 2) { // A winner?\r
111               if (foundPatternCross(stateCount)) { // Yes\r
112                 AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);\r
113                 if (confirmed != null) {\r
114                   return confirmed;\r
115                 }\r
116               }\r
117               stateCount[0] = stateCount[2];\r
118               stateCount[1] = 1;\r
119               stateCount[2] = 0;\r
120               currentState = 1;\r
121             } else {\r
122               stateCount[++currentState]++;\r
123             }\r
124           }\r
125         } else { // White pixel\r
126           if (currentState == 1) { // Counting black pixels\r
127             currentState++;\r
128           }\r
129           stateCount[currentState]++;\r
130         }\r
131         j++;\r
132       }\r
133       if (foundPatternCross(stateCount)) {\r
134         AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ);\r
135         if (confirmed != null) {\r
136           return confirmed;\r
137         }\r
138       }\r
139 \r
140     }\r
141 \r
142     // Hmm, nothing we saw was observed and confirmed twice. If we had\r
143     // any guess at all, return it.\r
144     if (!possibleCenters.isEmpty()) {\r
145       return (AlignmentPattern) possibleCenters.elementAt(0);\r
146     }\r
147 \r
148     throw ReaderException.getInstance();\r
149   }\r
150 \r
151   /**\r
152    * Given a count of black/white/black pixels just seen and an end position,\r
153    * figures the location of the center of this black/white/black run.\r
154    */\r
155   private static float centerFromEnd(int[] stateCount, int end) {\r
156     return (float) (end - stateCount[2]) - stateCount[1] / 2.0f;\r
157   }\r
158 \r
159   /**\r
160    * @param stateCount count of black/white/black pixels just read\r
161    * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios\r
162    *         used by alignment patterns to be considered a match\r
163    */\r
164   private boolean foundPatternCross(int[] stateCount) {\r
165     float moduleSize = this.moduleSize;\r
166     float maxVariance = moduleSize / 2.0f;\r
167     for (int i = 0; i < 3; i++) {\r
168       if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) {\r
169         return false;\r
170       }\r
171     }\r
172     return true;\r
173   }\r
174 \r
175   /**\r
176    * <p>After a horizontal scan finds a potential alignment pattern, this method\r
177    * "cross-checks" by scanning down vertically through the center of the possible\r
178    * alignment pattern to see if the same proportion is detected.</p>\r
179    *\r
180    * @param startI row where an alignment pattern was detected\r
181    * @param centerJ center of the section that appears to cross an alignment pattern\r
182    * @param maxCount maximum reasonable number of modules that should be\r
183    * observed in any reading state, based on the results of the horizontal scan\r
184    * @return vertical center of alignment pattern, or {@link Float#NaN} if not found\r
185    */\r
186   private float crossCheckVertical(int startI, int centerJ, int maxCount,\r
187       int originalStateCountTotal) {\r
188     BitMatrix image = this.image;\r
189 \r
190     int maxI = image.getHeight();\r
191     int[] stateCount = crossCheckStateCount;\r
192     stateCount[0] = 0;\r
193     stateCount[1] = 0;\r
194     stateCount[2] = 0;\r
195 \r
196     // Start counting up from center\r
197     int i = startI;\r
198     while (i >= 0 && image.get(centerJ, i) && stateCount[1] <= maxCount) {\r
199       stateCount[1]++;\r
200       i--;\r
201     }\r
202     // If already too many modules in this state or ran off the edge:\r
203     if (i < 0 || stateCount[1] > maxCount) {\r
204       return Float.NaN;\r
205     }\r
206     while (i >= 0 && !image.get(centerJ, i) && stateCount[0] <= maxCount) {\r
207       stateCount[0]++;\r
208       i--;\r
209     }\r
210     if (stateCount[0] > maxCount) {\r
211       return Float.NaN;\r
212     }\r
213 \r
214     // Now also count down from center\r
215     i = startI + 1;\r
216     while (i < maxI && image.get(centerJ, i) && stateCount[1] <= maxCount) {\r
217       stateCount[1]++;\r
218       i++;\r
219     }\r
220     if (i == maxI || stateCount[1] > maxCount) {\r
221       return Float.NaN;\r
222     }\r
223     while (i < maxI && !image.get(centerJ, i) && stateCount[2] <= maxCount) {\r
224       stateCount[2]++;\r
225       i++;\r
226     }\r
227     if (stateCount[2] > maxCount) {\r
228       return Float.NaN;\r
229     }\r
230 \r
231     int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];\r
232     if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\r
233       return Float.NaN;\r
234     }\r
235 \r
236     return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;\r
237   }\r
238 \r
239   /**\r
240    * <p>This is called when a horizontal scan finds a possible alignment pattern. It will\r
241    * cross check with a vertical scan, and if successful, will see if this pattern had been\r
242    * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have\r
243    * found the alignment pattern.</p>\r
244    *\r
245    * @param stateCount reading state module counts from horizontal scan\r
246    * @param i row where alignment pattern may be found\r
247    * @param j end of possible alignment pattern in row\r
248    * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not\r
249    */\r
250   private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j) {\r
251     int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];\r
252     float centerJ = centerFromEnd(stateCount, j);\r
253     float centerI = crossCheckVertical(i, (int) centerJ, 2 * stateCount[1], stateCountTotal);\r
254     if (!Float.isNaN(centerI)) {\r
255       float estimatedModuleSize = (float) (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;\r
256       int max = possibleCenters.size();\r
257       for (int index = 0; index < max; index++) {\r
258         AlignmentPattern center = (AlignmentPattern) possibleCenters.elementAt(index);\r
259         // Look for about the same center and module size:\r
260         if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {\r
261           return new AlignmentPattern(centerJ, centerI, estimatedModuleSize);\r
262         }\r
263       }\r
264       // Hadn't found this before; save it\r
265       possibleCenters.addElement(new AlignmentPattern(centerJ, centerI, estimatedModuleSize));\r
266     }\r
267     return null;\r
268   }\r
269 \r
270 }