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