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