eb23e79397dcbab9a72ee3dc053590b93bc51098
[zxing.git] / core / src / com / google / zxing / qrcode / detector / FinderPatternFinder.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.DecodeHintType;\r
20 import com.google.zxing.ReaderException;\r
21 import com.google.zxing.ResultPoint;\r
22 import com.google.zxing.ResultPointCallback;\r
23 import com.google.zxing.common.Collections;\r
24 import com.google.zxing.common.Comparator;\r
25 import com.google.zxing.common.BitMatrix;\r
26 \r
27 import java.util.Hashtable;\r
28 import java.util.Vector;\r
29 \r
30 /**\r
31  * <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square\r
32  * markers at three corners of a QR 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 public class FinderPatternFinder {\r
39 \r
40   private static final int CENTER_QUORUM = 2;\r
41   protected static final int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center\r
42   protected static final int MAX_MODULES = 57; // support up to version 10 for mobile clients\r
43   private static final int INTEGER_MATH_SHIFT = 8;\r
44 \r
45   private final BitMatrix image;\r
46   private final Vector possibleCenters;\r
47   private boolean hasSkipped;\r
48   private final int[] crossCheckStateCount;\r
49   private final ResultPointCallback resultPointCallback;\r
50 \r
51   /**\r
52    * <p>Creates a finder that will search the image for three finder patterns.</p>\r
53    *\r
54    * @param image image to search\r
55    */\r
56   public FinderPatternFinder(BitMatrix image) {\r
57     this(image, null);\r
58   }\r
59 \r
60   public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) {\r
61     this.image = image;\r
62     this.possibleCenters = new Vector();\r
63     this.crossCheckStateCount = new int[5];\r
64     this.resultPointCallback = resultPointCallback;\r
65   }\r
66 \r
67   protected BitMatrix getImage() {\r
68     return image;\r
69   }\r
70 \r
71   protected Vector getPossibleCenters() {\r
72     return possibleCenters;\r
73   }\r
74 \r
75   FinderPatternInfo find(Hashtable hints) throws ReaderException {\r
76     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);\r
77     int maxI = image.getHeight();\r
78     int maxJ = image.getWidth();\r
79     // We are looking for black/white/black/white/black modules in\r
80     // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far\r
81 \r
82     // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the\r
83     // image, and then account for the center being 3 modules in size. This gives the smallest\r
84     // number of pixels the center could be, so skip this often. When trying harder, look for all\r
85     // QR versions regardless of how dense they are.\r
86     int iSkip = (3 * maxI) / (4 * MAX_MODULES);\r
87     if (iSkip < MIN_SKIP || tryHarder) {\r
88       iSkip = MIN_SKIP;\r
89     }\r
90 \r
91     boolean done = false;\r
92     int[] stateCount = new int[5];\r
93     for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {\r
94       // Get a row of black/white values\r
95       stateCount[0] = 0;\r
96       stateCount[1] = 0;\r
97       stateCount[2] = 0;\r
98       stateCount[3] = 0;\r
99       stateCount[4] = 0;\r
100       int currentState = 0;\r
101       for (int j = 0; j < maxJ; j++) {\r
102         if (image.get(j, i)) {\r
103           // Black pixel\r
104           if ((currentState & 1) == 1) { // Counting white pixels\r
105             currentState++;\r
106           }\r
107           stateCount[currentState]++;\r
108         } else { // White pixel\r
109           if ((currentState & 1) == 0) { // Counting black pixels\r
110             if (currentState == 4) { // A winner?\r
111               if (foundPatternCross(stateCount)) { // Yes\r
112                 boolean confirmed = handlePossibleCenter(stateCount, i, j);\r
113                 if (confirmed) {\r
114                   // Start examining every other line. Checking each line turned out to be too\r
115                   // expensive and didn't improve performance.\r
116                   iSkip = 2;\r
117                   if (hasSkipped) {\r
118                     done = haveMultiplyConfirmedCenters();\r
119                   } else {\r
120                     int rowSkip = findRowSkip();\r
121                     if (rowSkip > stateCount[2]) {\r
122                       // Skip rows between row of lower confirmed center\r
123                       // and top of presumed third confirmed center\r
124                       // but back up a bit to get a full chance of detecting\r
125                       // it, entire width of center of finder pattern\r
126 \r
127                       // Skip by rowSkip, but back off by stateCount[2] (size of last center\r
128                       // of pattern we saw) to be conservative, and also back off by iSkip which\r
129                       // is about to be re-added\r
130                       i += rowSkip - stateCount[2] - iSkip;\r
131                       j = maxJ - 1;\r
132                     }\r
133                   }\r
134                 } else {\r
135                   // Advance to next black pixel\r
136                   do {\r
137                     j++;\r
138                   } while (j < maxJ && !image.get(j, i));\r
139                   j--; // back up to that last white pixel\r
140                 }\r
141                 // Clear state to start looking again\r
142                 currentState = 0;\r
143                 stateCount[0] = 0;\r
144                 stateCount[1] = 0;\r
145                 stateCount[2] = 0;\r
146                 stateCount[3] = 0;\r
147                 stateCount[4] = 0;\r
148               } else { // No, shift counts back by two\r
149                 stateCount[0] = stateCount[2];\r
150                 stateCount[1] = stateCount[3];\r
151                 stateCount[2] = stateCount[4];\r
152                 stateCount[3] = 1;\r
153                 stateCount[4] = 0;\r
154                 currentState = 3;\r
155               }\r
156             } else {\r
157               stateCount[++currentState]++;\r
158             }\r
159           } else { // Counting white pixels\r
160             stateCount[currentState]++;\r
161           }\r
162         }\r
163       }\r
164       if (foundPatternCross(stateCount)) {\r
165         boolean confirmed = handlePossibleCenter(stateCount, i, maxJ);\r
166         if (confirmed) {\r
167           iSkip = stateCount[0];\r
168           if (hasSkipped) {\r
169             // Found a third one\r
170             done = haveMultiplyConfirmedCenters();\r
171           }\r
172         }\r
173       }\r
174     }\r
175 \r
176     FinderPattern[] patternInfo = selectBestPatterns();\r
177     ResultPoint.orderBestPatterns(patternInfo);\r
178 \r
179     return new FinderPatternInfo(patternInfo);\r
180   }\r
181 \r
182   /**\r
183    * Given a count of black/white/black/white/black pixels just seen and an end position,\r
184    * figures the location of the center of this run.\r
185    */\r
186   private static float centerFromEnd(int[] stateCount, int end) {\r
187     return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;\r
188   }\r
189 \r
190   /**\r
191    * @param stateCount count of black/white/black/white/black pixels just read\r
192    * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios\r
193    *         used by finder patterns to be considered a match\r
194    */\r
195   protected static boolean foundPatternCross(int[] stateCount) {\r
196     int totalModuleSize = 0;\r
197     for (int i = 0; i < 5; i++) {\r
198       int count = stateCount[i];\r
199       if (count == 0) {\r
200         return false;\r
201       }\r
202       totalModuleSize += count;\r
203     }\r
204     if (totalModuleSize < 7) {\r
205       return false;\r
206     }\r
207     int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;\r
208     int maxVariance = moduleSize / 2;\r
209     // Allow less than 50% variance from 1-1-3-1-1 proportions\r
210     return Math.abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance &&\r
211         Math.abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance &&\r
212         Math.abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance &&\r
213         Math.abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance &&\r
214         Math.abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;\r
215   }\r
216 \r
217   private int[] getCrossCheckStateCount() {\r
218     crossCheckStateCount[0] = 0;\r
219     crossCheckStateCount[1] = 0;\r
220     crossCheckStateCount[2] = 0;\r
221     crossCheckStateCount[3] = 0;\r
222     crossCheckStateCount[4] = 0;\r
223     return crossCheckStateCount;\r
224   }\r
225 \r
226   /**\r
227    * <p>After a horizontal scan finds a potential finder pattern, this method\r
228    * "cross-checks" by scanning down vertically through the center of the possible\r
229    * finder pattern to see if the same proportion is detected.</p>\r
230    *\r
231    * @param startI row where a finder pattern was detected\r
232    * @param centerJ center of the section that appears to cross a finder pattern\r
233    * @param maxCount maximum reasonable number of modules that should be\r
234    * observed in any reading state, based on the results of the horizontal scan\r
235    * @return vertical center of finder pattern, or {@link Float#NaN} if not found\r
236    */\r
237   private float crossCheckVertical(int startI, int centerJ, int maxCount,\r
238       int originalStateCountTotal) {\r
239     BitMatrix image = this.image;\r
240 \r
241     int maxI = image.getHeight();\r
242     int[] stateCount = getCrossCheckStateCount();\r
243 \r
244     // Start counting up from center\r
245     int i = startI;\r
246     while (i >= 0 && image.get(centerJ, i)) {\r
247       stateCount[2]++;\r
248       i--;\r
249     }\r
250     if (i < 0) {\r
251       return Float.NaN;\r
252     }\r
253     while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {\r
254       stateCount[1]++;\r
255       i--;\r
256     }\r
257     // If already too many modules in this state or ran off the edge:\r
258     if (i < 0 || stateCount[1] > maxCount) {\r
259       return Float.NaN;\r
260     }\r
261     while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {\r
262       stateCount[0]++;\r
263       i--;\r
264     }\r
265     if (stateCount[0] > maxCount) {\r
266       return Float.NaN;\r
267     }\r
268 \r
269     // Now also count down from center\r
270     i = startI + 1;\r
271     while (i < maxI && image.get(centerJ, i)) {\r
272       stateCount[2]++;\r
273       i++;\r
274     }\r
275     if (i == maxI) {\r
276       return Float.NaN;\r
277     }\r
278     while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {\r
279       stateCount[3]++;\r
280       i++;\r
281     }\r
282     if (i == maxI || stateCount[3] >= maxCount) {\r
283       return Float.NaN;\r
284     }\r
285     while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {\r
286       stateCount[4]++;\r
287       i++;\r
288     }\r
289     if (stateCount[4] >= maxCount) {\r
290       return Float.NaN;\r
291     }\r
292 \r
293     // If we found a finder-pattern-like section, but its size is more than 20% different than\r
294     // the original, assume it's a false positive\r
295     int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\r
296         stateCount[4];\r
297     if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\r
298       return Float.NaN;\r
299     }\r
300 \r
301     return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;\r
302   }\r
303 \r
304   /**\r
305    * <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,\r
306    * except it reads horizontally instead of vertically. This is used to cross-cross\r
307    * check a vertical cross check and locate the real center of the alignment pattern.</p>\r
308    */\r
309   private float crossCheckHorizontal(int startJ, int centerI, int maxCount,\r
310       int originalStateCountTotal) {\r
311     BitMatrix image = this.image;\r
312 \r
313     int maxJ = image.getWidth();\r
314     int[] stateCount = getCrossCheckStateCount();\r
315 \r
316     int j = startJ;\r
317     while (j >= 0 && image.get(j, centerI)) {\r
318       stateCount[2]++;\r
319       j--;\r
320     }\r
321     if (j < 0) {\r
322       return Float.NaN;\r
323     }\r
324     while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {\r
325       stateCount[1]++;\r
326       j--;\r
327     }\r
328     if (j < 0 || stateCount[1] > maxCount) {\r
329       return Float.NaN;\r
330     }\r
331     while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {\r
332       stateCount[0]++;\r
333       j--;\r
334     }\r
335     if (stateCount[0] > maxCount) {\r
336       return Float.NaN;\r
337     }\r
338 \r
339     j = startJ + 1;\r
340     while (j < maxJ && image.get(j, centerI)) {\r
341       stateCount[2]++;\r
342       j++;\r
343     }\r
344     if (j == maxJ) {\r
345       return Float.NaN;\r
346     }\r
347     while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {\r
348       stateCount[3]++;\r
349       j++;\r
350     }\r
351     if (j == maxJ || stateCount[3] >= maxCount) {\r
352       return Float.NaN;\r
353     }\r
354     while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {\r
355       stateCount[4]++;\r
356       j++;\r
357     }\r
358     if (stateCount[4] >= maxCount) {\r
359       return Float.NaN;\r
360     }\r
361 \r
362     // If we found a finder-pattern-like section, but its size is significantly different than\r
363     // the original, assume it's a false positive\r
364     int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\r
365         stateCount[4];\r
366     if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\r
367       return Float.NaN;\r
368     }\r
369 \r
370     return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;\r
371   }\r
372 \r
373   /**\r
374    * <p>This is called when a horizontal scan finds a possible alignment pattern. It will\r
375    * cross check with a vertical scan, and if successful, will, ah, cross-cross-check\r
376    * with another horizontal scan. This is needed primarily to locate the real horizontal\r
377    * center of the pattern in cases of extreme skew.</p>\r
378    *\r
379    * <p>If that succeeds the finder pattern location is added to a list that tracks\r
380    * the number of times each location has been nearly-matched as a finder pattern.\r
381    * Each additional find is more evidence that the location is in fact a finder\r
382    * pattern center\r
383    *\r
384    * @param stateCount reading state module counts from horizontal scan\r
385    * @param i row where finder pattern may be found\r
386    * @param j end of possible finder pattern in row\r
387    * @return true if a finder pattern candidate was found this time\r
388    */\r
389   protected boolean handlePossibleCenter(int[] stateCount, int i, int j) {\r
390     int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\r
391         stateCount[4];\r
392     float centerJ = centerFromEnd(stateCount, j);\r
393     float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);\r
394     if (!Float.isNaN(centerI)) {\r
395       // Re-cross check\r
396       centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);\r
397       if (!Float.isNaN(centerJ)) {\r
398         float estimatedModuleSize = (float) stateCountTotal / 7.0f;\r
399         boolean found = false;\r
400         int max = possibleCenters.size();\r
401         for (int index = 0; index < max; index++) {\r
402           FinderPattern center = (FinderPattern) possibleCenters.elementAt(index);\r
403           // Look for about the same center and module size:\r
404           if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {\r
405             center.incrementCount();\r
406             found = true;\r
407             break;\r
408           }\r
409         }\r
410         if (!found) {\r
411           ResultPoint point = new FinderPattern(centerJ, centerI, estimatedModuleSize);\r
412           possibleCenters.addElement(point);\r
413           if (resultPointCallback != null) {\r
414             resultPointCallback.foundPossibleResultPoint(point);\r
415           }\r
416         }\r
417         return true;\r
418       }\r
419     }\r
420     return false;\r
421   }\r
422 \r
423   /**\r
424    * @return number of rows we could safely skip during scanning, based on the first\r
425    *         two finder patterns that have been located. In some cases their position will\r
426    *         allow us to infer that the third pattern must lie below a certain point farther\r
427    *         down in the image.\r
428    */\r
429   private int findRowSkip() {\r
430     int max = possibleCenters.size();\r
431     if (max <= 1) {\r
432       return 0;\r
433     }\r
434     FinderPattern firstConfirmedCenter = null;\r
435     for (int i = 0; i < max; i++) {\r
436       FinderPattern center = (FinderPattern) possibleCenters.elementAt(i);\r
437       if (center.getCount() >= CENTER_QUORUM) {\r
438         if (firstConfirmedCenter == null) {\r
439           firstConfirmedCenter = center;\r
440         } else {\r
441           // We have two confirmed centers\r
442           // How far down can we skip before resuming looking for the next\r
443           // pattern? In the worst case, only the difference between the\r
444           // difference in the x / y coordinates of the two centers.\r
445           // This is the case where you find top left last.\r
446           hasSkipped = true;\r
447           return (int) (Math.abs(firstConfirmedCenter.getX() - center.getX()) -\r
448               Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2;\r
449         }\r
450       }\r
451     }\r
452     return 0;\r
453   }\r
454 \r
455   /**\r
456    * @return true iff we have found at least 3 finder patterns that have been detected\r
457    *         at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the\r
458    *         candidates is "pretty similar"\r
459    */\r
460   private boolean haveMultiplyConfirmedCenters() {\r
461     int confirmedCount = 0;\r
462     float totalModuleSize = 0.0f;\r
463     int max = possibleCenters.size();\r
464     for (int i = 0; i < max; i++) {\r
465       FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);\r
466       if (pattern.getCount() >= CENTER_QUORUM) {\r
467         confirmedCount++;\r
468         totalModuleSize += pattern.getEstimatedModuleSize();\r
469       }\r
470     }\r
471     if (confirmedCount < 3) {\r
472       return false;\r
473     }\r
474     // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"\r
475     // and that we need to keep looking. We detect this by asking if the estimated module sizes\r
476     // vary too much. We arbitrarily say that when the total deviation from average exceeds\r
477     // 5% of the total module size estimates, it's too much.\r
478     float average = totalModuleSize / (float) max;\r
479     float totalDeviation = 0.0f;\r
480     for (int i = 0; i < max; i++) {\r
481       FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);\r
482       totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);\r
483     }\r
484     return totalDeviation <= 0.05f * totalModuleSize;\r
485   }\r
486 \r
487   /**\r
488    * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are\r
489    *         those that have been detected at least {@link #CENTER_QUORUM} times, and whose module\r
490    *         size differs from the average among those patterns the least\r
491    * @throws ReaderException if 3 such finder patterns do not exist\r
492    */\r
493   private FinderPattern[] selectBestPatterns() throws ReaderException {\r
494 \r
495     int startSize = possibleCenters.size();\r
496     if (startSize < 3) {\r
497       // Couldn't find enough finder patterns\r
498       throw ReaderException.getInstance();\r
499     }\r
500 \r
501     // Filter outlier possibilities whose module size is too different\r
502     if (startSize > 3) {\r
503       // But we can only afford to do so if we have at least 4 possibilities to choose from\r
504       float totalModuleSize = 0.0f;\r
505       for (int i = 0; i < startSize; i++) {\r
506         totalModuleSize += ((FinderPattern) possibleCenters.elementAt(i)).getEstimatedModuleSize();\r
507       }\r
508       float average = totalModuleSize / (float) startSize;\r
509       for (int i = 0; i < possibleCenters.size() && possibleCenters.size() > 3; i++) {\r
510         FinderPattern pattern = (FinderPattern) possibleCenters.elementAt(i);\r
511         if (Math.abs(pattern.getEstimatedModuleSize() - average) > 0.2f * average) {\r
512           possibleCenters.removeElementAt(i);\r
513           i--;\r
514         }\r
515       }\r
516     }\r
517 \r
518     if (possibleCenters.size() > 3) {\r
519       // Throw away all but those first size candidate points we found.\r
520       Collections.insertionSort(possibleCenters, new CenterComparator());      \r
521       possibleCenters.setSize(3);\r
522     }\r
523 \r
524     return new FinderPattern[]{\r
525         (FinderPattern) possibleCenters.elementAt(0),\r
526         (FinderPattern) possibleCenters.elementAt(1),\r
527         (FinderPattern) possibleCenters.elementAt(2)\r
528     };\r
529   }\r
530 \r
531   /**\r
532    * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>\r
533    */\r
534   private static class CenterComparator implements Comparator {\r
535     public int compare(Object center1, Object center2) {\r
536       return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount();\r
537     }\r
538   }\r
539 \r
540 }\r