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