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