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