2 * Copyright 2007 ZXing authors
\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
8 * http://www.apache.org/licenses/LICENSE-2.0
\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
17 using DecodeHintType = com.google.zxing.DecodeHintType;
\r
18 using ReaderException = com.google.zxing.ReaderException;
\r
19 using ResultPoint = com.google.zxing.ResultPoint;
\r
20 using ResultPointCallback = com.google.zxing.ResultPointCallback;
\r
21 using Collections = com.google.zxing.common.Collections;
\r
22 using Comparator = com.google.zxing.common.Comparator;
\r
23 using BitMatrix = com.google.zxing.common.BitMatrix;
\r
24 namespace com.google.zxing.qrcode.detector
\r
27 /// <summary> <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
\r
28 /// markers at three corners of a QR Code.</p>
\r
30 /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
\r
33 /// <author> Sean Owen
\r
35 /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
\r
37 public class FinderPatternFinder
\r
39 virtual protected internal BitMatrix Image
\r
47 virtual protected internal System.Collections.ArrayList PossibleCenters
\r
51 return possibleCenters;
\r
55 private int[] CrossCheckStateCount
\r
59 crossCheckStateCount[0] = 0;
\r
60 crossCheckStateCount[1] = 0;
\r
61 crossCheckStateCount[2] = 0;
\r
62 crossCheckStateCount[3] = 0;
\r
63 crossCheckStateCount[4] = 0;
\r
64 return crossCheckStateCount;
\r
69 private const int CENTER_QUORUM = 2;
\r
70 protected internal const int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center
\r
71 protected internal const int MAX_MODULES = 57; // support up to version 10 for mobile clients
\r
72 private const int INTEGER_MATH_SHIFT = 8;
\r
74 //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
\r
75 private BitMatrix image;
\r
76 //UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
\r
77 private System.Collections.ArrayList possibleCenters;
\r
78 private bool hasSkipped;
\r
79 //UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
\r
80 private int[] crossCheckStateCount;
\r
81 //UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
\r
82 private ResultPointCallback resultPointCallback;
\r
84 /// <summary> <p>Creates a finder that will search the image for three finder patterns.</p>
\r
87 /// <param name="image">image to search
\r
89 public FinderPatternFinder(BitMatrix image):this(image, null)
\r
93 public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback)
\r
96 this.possibleCenters = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
\r
97 this.crossCheckStateCount = new int[5];
\r
98 this.resultPointCallback = resultPointCallback;
\r
101 internal virtual FinderPatternInfo find(System.Collections.Hashtable hints)
\r
103 bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
\r
104 int maxI = image.Height;
\r
105 int maxJ = image.Width;
\r
106 // We are looking for black/white/black/white/black modules in
\r
107 // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far
\r
109 // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
\r
110 // image, and then account for the center being 3 modules in size. This gives the smallest
\r
111 // number of pixels the center could be, so skip this often. When trying harder, look for all
\r
112 // QR versions regardless of how dense they are.
\r
113 int iSkip = (3 * maxI) / (4 * MAX_MODULES);
\r
114 if (iSkip < MIN_SKIP || tryHarder)
\r
120 int[] stateCount = new int[5];
\r
121 for (int i = iSkip - 1; i < maxI && !done; i += iSkip)
\r
123 // Get a row of black/white values
\r
129 int currentState = 0;
\r
130 for (int j = 0; j < maxJ; j++)
\r
132 if (image.get_Renamed(j, i))
\r
135 if ((currentState & 1) == 1)
\r
137 // Counting white pixels
\r
140 stateCount[currentState]++;
\r
145 if ((currentState & 1) == 0)
\r
147 // Counting black pixels
\r
148 if (currentState == 4)
\r
151 if (foundPatternCross(stateCount))
\r
154 bool confirmed = handlePossibleCenter(stateCount, i, j);
\r
157 // Start examining every other line. Checking each line turned out to be too
\r
158 // expensive and didn't improve performance.
\r
162 done = haveMultiplyConfirmedCenters();
\r
166 int rowSkip = findRowSkip();
\r
167 if (rowSkip > stateCount[2])
\r
169 // Skip rows between row of lower confirmed center
\r
170 // and top of presumed third confirmed center
\r
171 // but back up a bit to get a full chance of detecting
\r
172 // it, entire width of center of finder pattern
\r
174 // Skip by rowSkip, but back off by stateCount[2] (size of last center
\r
175 // of pattern we saw) to be conservative, and also back off by iSkip which
\r
176 // is about to be re-added
\r
177 i += rowSkip - stateCount[2] - iSkip;
\r
184 // Advance to next black pixel
\r
189 while (j < maxJ && !image.get_Renamed(j, i));
\r
190 j--; // back up to that last white pixel
\r
192 // Clear state to start looking again
\r
202 // No, shift counts back by two
\r
203 stateCount[0] = stateCount[2];
\r
204 stateCount[1] = stateCount[3];
\r
205 stateCount[2] = stateCount[4];
\r
213 stateCount[++currentState]++;
\r
218 // Counting white pixels
\r
219 stateCount[currentState]++;
\r
223 if (foundPatternCross(stateCount))
\r
225 bool confirmed = handlePossibleCenter(stateCount, i, maxJ);
\r
228 iSkip = stateCount[0];
\r
231 // Found a third one
\r
232 done = haveMultiplyConfirmedCenters();
\r
238 FinderPattern[] patternInfo = selectBestPatterns();
\r
239 ResultPoint.orderBestPatterns(patternInfo);
\r
241 return new FinderPatternInfo(patternInfo);
\r
244 /// <summary> Given a count of black/white/black/white/black pixels just seen and an end position,
\r
245 /// figures the location of the center of this run.
\r
247 private static float centerFromEnd(int[] stateCount, int end)
\r
249 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
250 return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
\r
253 /// <param name="stateCount">count of black/white/black/white/black pixels just read
\r
255 /// <returns> true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios
\r
256 /// used by finder patterns to be considered a match
\r
258 protected internal static bool foundPatternCross(int[] stateCount)
\r
260 int totalModuleSize = 0;
\r
261 for (int i = 0; i < 5; i++)
\r
263 int count = stateCount[i];
\r
268 totalModuleSize += count;
\r
270 if (totalModuleSize < 7)
\r
274 int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7;
\r
275 int maxVariance = moduleSize / 2;
\r
276 // Allow less than 50% variance from 1-1-3-1-1 proportions
\r
277 return System.Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && System.Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance;
\r
280 /// <summary> <p>After a horizontal scan finds a potential finder pattern, this method
\r
281 /// "cross-checks" by scanning down vertically through the center of the possible
\r
282 /// finder pattern to see if the same proportion is detected.</p>
\r
285 /// <param name="startI">row where a finder pattern was detected
\r
287 /// <param name="centerJ">center of the section that appears to cross a finder pattern
\r
289 /// <param name="maxCount">maximum reasonable number of modules that should be
\r
290 /// observed in any reading state, based on the results of the horizontal scan
\r
292 /// <returns> vertical center of finder pattern, or {@link Float#NaN} if not found
\r
294 private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
\r
296 BitMatrix image = this.image;
\r
298 int maxI = image.Height;
\r
299 int[] stateCount = CrossCheckStateCount;
\r
301 // Start counting up from center
\r
303 while (i >= 0 && image.get_Renamed(centerJ, i))
\r
310 return System.Single.NaN;
\r
312 while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount)
\r
317 // If already too many modules in this state or ran off the edge:
\r
318 if (i < 0 || stateCount[1] > maxCount)
\r
320 return System.Single.NaN;
\r
322 while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount)
\r
327 if (stateCount[0] > maxCount)
\r
329 return System.Single.NaN;
\r
332 // Now also count down from center
\r
334 while (i < maxI && image.get_Renamed(centerJ, i))
\r
341 return System.Single.NaN;
\r
343 while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[3] < maxCount)
\r
348 if (i == maxI || stateCount[3] >= maxCount)
\r
350 return System.Single.NaN;
\r
352 while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[4] < maxCount)
\r
357 if (stateCount[4] >= maxCount)
\r
359 return System.Single.NaN;
\r
362 // If we found a finder-pattern-like section, but its size is more than 40% different than
\r
363 // the original, assume it's a false positive
\r
364 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
\r
365 if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
\r
367 return System.Single.NaN;
\r
370 return foundPatternCross(stateCount)?centerFromEnd(stateCount, i):System.Single.NaN;
\r
373 /// <summary> <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,
\r
374 /// except it reads horizontally instead of vertically. This is used to cross-cross
\r
375 /// check a vertical cross check and locate the real center of the alignment pattern.</p>
\r
377 private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal)
\r
379 BitMatrix image = this.image;
\r
381 int maxJ = image.Width;
\r
382 int[] stateCount = CrossCheckStateCount;
\r
385 while (j >= 0 && image.get_Renamed(j, centerI))
\r
392 return System.Single.NaN;
\r
394 while (j >= 0 && !image.get_Renamed(j, centerI) && stateCount[1] <= maxCount)
\r
399 if (j < 0 || stateCount[1] > maxCount)
\r
401 return System.Single.NaN;
\r
403 while (j >= 0 && image.get_Renamed(j, centerI) && stateCount[0] <= maxCount)
\r
408 if (stateCount[0] > maxCount)
\r
410 return System.Single.NaN;
\r
414 while (j < maxJ && image.get_Renamed(j, centerI))
\r
421 return System.Single.NaN;
\r
423 while (j < maxJ && !image.get_Renamed(j, centerI) && stateCount[3] < maxCount)
\r
428 if (j == maxJ || stateCount[3] >= maxCount)
\r
430 return System.Single.NaN;
\r
432 while (j < maxJ && image.get_Renamed(j, centerI) && stateCount[4] < maxCount)
\r
437 if (stateCount[4] >= maxCount)
\r
439 return System.Single.NaN;
\r
442 // If we found a finder-pattern-like section, but its size is significantly different than
\r
443 // the original, assume it's a false positive
\r
444 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
\r
445 if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal)
\r
447 return System.Single.NaN;
\r
450 return foundPatternCross(stateCount)?centerFromEnd(stateCount, j):System.Single.NaN;
\r
453 /// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will
\r
454 /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check
\r
455 /// with another horizontal scan. This is needed primarily to locate the real horizontal
\r
456 /// center of the pattern in cases of extreme skew.</p>
\r
458 /// <p>If that succeeds the finder pattern location is added to a list that tracks
\r
459 /// the number of times each location has been nearly-matched as a finder pattern.
\r
460 /// Each additional find is more evidence that the location is in fact a finder
\r
464 /// <param name="stateCount">reading state module counts from horizontal scan
\r
466 /// <param name="i">row where finder pattern may be found
\r
468 /// <param name="j">end of possible finder pattern in row
\r
470 /// <returns> true if a finder pattern candidate was found this time
\r
472 protected internal virtual bool handlePossibleCenter(int[] stateCount, int i, int j)
\r
474 int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
\r
475 float centerJ = centerFromEnd(stateCount, j);
\r
476 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
477 float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);
\r
478 if (!System.Single.IsNaN(centerI))
\r
481 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
482 centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
\r
483 if (!System.Single.IsNaN(centerJ))
\r
485 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
486 float estimatedModuleSize = (float) stateCountTotal / 7.0f;
\r
487 bool found = false;
\r
488 int max = possibleCenters.Count;
\r
489 for (int index = 0; index < max; index++)
\r
491 FinderPattern center = (FinderPattern) possibleCenters[index];
\r
492 // Look for about the same center and module size:
\r
493 if (center.aboutEquals(estimatedModuleSize, centerI, centerJ))
\r
495 center.incrementCount();
\r
502 ResultPoint point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
\r
503 possibleCenters.Add(point);
\r
504 if (resultPointCallback != null)
\r
506 resultPointCallback.foundPossibleResultPoint(point);
\r
515 /// <returns> number of rows we could safely skip during scanning, based on the first
\r
516 /// two finder patterns that have been located. In some cases their position will
\r
517 /// allow us to infer that the third pattern must lie below a certain point farther
\r
518 /// down in the image.
\r
520 private int findRowSkip()
\r
522 int max = possibleCenters.Count;
\r
527 FinderPattern firstConfirmedCenter = null;
\r
528 for (int i = 0; i < max; i++)
\r
530 FinderPattern center = (FinderPattern) possibleCenters[i];
\r
531 if (center.Count >= CENTER_QUORUM)
\r
533 if (firstConfirmedCenter == null)
\r
535 firstConfirmedCenter = center;
\r
539 // We have two confirmed centers
\r
540 // How far down can we skip before resuming looking for the next
\r
541 // pattern? In the worst case, only the difference between the
\r
542 // difference in the x / y coordinates of the two centers.
\r
543 // This is the case where you find top left last.
\r
545 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
546 return (int) (System.Math.Abs(firstConfirmedCenter.X - center.X) - System.Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2;
\r
553 /// <returns> true iff we have found at least 3 finder patterns that have been detected
\r
554 /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the
\r
555 /// candidates is "pretty similar"
\r
557 private bool haveMultiplyConfirmedCenters()
\r
559 int confirmedCount = 0;
\r
560 float totalModuleSize = 0.0f;
\r
561 int max = possibleCenters.Count;
\r
562 for (int i = 0; i < max; i++)
\r
564 FinderPattern pattern = (FinderPattern) possibleCenters[i];
\r
565 if (pattern.Count >= CENTER_QUORUM)
\r
568 totalModuleSize += pattern.EstimatedModuleSize;
\r
571 if (confirmedCount < 3)
\r
575 // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
\r
576 // and that we need to keep looking. We detect this by asking if the estimated module sizes
\r
577 // vary too much. We arbitrarily say that when the total deviation from average exceeds
\r
578 // 5% of the total module size estimates, it's too much.
\r
579 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
580 float average = totalModuleSize / (float) max;
\r
581 float totalDeviation = 0.0f;
\r
582 for (int i = 0; i < max; i++)
\r
584 FinderPattern pattern = (FinderPattern) possibleCenters[i];
\r
585 totalDeviation += System.Math.Abs(pattern.EstimatedModuleSize - average);
\r
587 return totalDeviation <= 0.05f * totalModuleSize;
\r
590 /// <returns> the 3 best {@link FinderPattern}s from our list of candidates. The "best" are
\r
591 /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module
\r
592 /// size differs from the average among those patterns the least
\r
594 /// <throws> ReaderException if 3 such finder patterns do not exist </throws>
\r
595 private FinderPattern[] selectBestPatterns()
\r
598 int startSize = possibleCenters.Count;
\r
601 // Couldn't find enough finder patterns
\r
602 throw ReaderException.Instance;
\r
605 // Filter outlier possibilities whose module size is too different
\r
608 // But we can only afford to do so if we have at least 4 possibilities to choose from
\r
609 float totalModuleSize = 0.0f;
\r
610 for (int i = 0; i < startSize; i++)
\r
612 totalModuleSize += ((FinderPattern) possibleCenters[i]).EstimatedModuleSize;
\r
614 //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
\r
615 float average = totalModuleSize / (float) startSize;
\r
616 for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++)
\r
618 FinderPattern pattern = (FinderPattern) possibleCenters[i];
\r
619 if (System.Math.Abs(pattern.EstimatedModuleSize - average) > 0.2f * average)
\r
621 possibleCenters.RemoveAt(i);
\r
627 if (possibleCenters.Count > 3)
\r
629 // Throw away all but those first size candidate points we found.
\r
630 Collections.insertionSort(possibleCenters, new CenterComparator());
\r
631 SupportClass.SetCapacity(possibleCenters, 3);
\r
634 return new FinderPattern[]{(FinderPattern) possibleCenters[0], (FinderPattern) possibleCenters[1], (FinderPattern) possibleCenters[2]};
\r
637 /// <summary> <p>Orders by {@link FinderPattern#getCount()}, descending.</p></summary>
\r
638 private class CenterComparator : Comparator
\r
640 public virtual int compare(System.Object center1, System.Object center2)
\r
642 return ((FinderPattern) center2).Count - ((FinderPattern) center1).Count;
\r