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
16 namespace com.google.zxing.qrcode.detector
\r
19 using com.google.zxing;
\r
20 using com.google.zxing.common;
\r
22 public sealed class FinderPatternFinder
\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
29 private MonochromeBitmapSource image;
\r
30 private System.Collections.ArrayList possibleCenters;
\r
31 private bool hasSkipped;
\r
32 private int[] crossCheckStateCount;
\r
35 * <p>Creates a finder that will search the image for three finder patterns.</p>
\r
37 * @param image image to search
\r
39 public FinderPatternFinder(MonochromeBitmapSource image) {
\r
41 this.possibleCenters = new System.Collections.ArrayList();
\r
42 this.crossCheckStateCount = new int[5];
\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
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
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
72 int currentState = 0;
\r
73 for (int j = 0; j < maxJ; j++) {
\r
74 if (blackRow.get(j)) {
\r
76 if ((currentState & 1) == 1) { // Counting white pixels
\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
86 // Start examining every other line. Checking each line turned out to be too
\r
87 // expensive and didn't improve performance.
\r
90 done = haveMulitplyConfirmedCenters();
\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
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
107 // Advance to next black pixel
\r
110 } while (j < maxJ && !blackRow.get(j));
\r
111 j--; // back up to that last white pixel
\r
113 // Clear state to start looking again
\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
129 stateCount[++currentState]++;
\r
131 } else { // Counting white pixels
\r
132 stateCount[currentState]++;
\r
136 if (foundPatternCross(stateCount)) {
\r
137 bool confirmed = handlePossibleCenter(stateCount, i, maxJ);
\r
139 iSkip = stateCount[0];
\r
141 // Found a third one
\r
142 done = haveMulitplyConfirmedCenters();
\r
148 FinderPattern[] patternInfo = selectBestPatterns();
\r
149 GenericResultPoint.orderBestPatterns(patternInfo);
\r
151 return new FinderPatternInfo(patternInfo);
\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
158 private static float centerFromEnd(int[] stateCount, int end) {
\r
159 return (float) (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
\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
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
174 totalModuleSize += count;
\r
176 if (totalModuleSize < 7) {
\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
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
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
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
209 private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) {
\r
210 MonochromeBitmapSource image = this.image;
\r
212 int maxI = image.getHeight();
\r
213 int[] stateCount = getCrossCheckStateCount();
\r
215 // Start counting up from center
\r
217 while (i >= 0 && image.isBlack(centerJ, i)) {
\r
224 while (i >= 0 && !image.isBlack(centerJ, i) && stateCount[1] <= maxCount) {
\r
228 // If already too many modules in this state or ran off the edge:
\r
229 if (i < 0 || stateCount[1] > maxCount) {
\r
232 while (i >= 0 && image.isBlack(centerJ, i) && stateCount[0] <= maxCount) {
\r
236 if (stateCount[0] > maxCount) {
\r
240 // Now also count down from center
\r
242 while (i < maxI && image.isBlack(centerJ, i)) {
\r
249 while (i < maxI && !image.isBlack(centerJ, i) && stateCount[3] < maxCount) {
\r
253 if (i == maxI || stateCount[3] >= maxCount) {
\r
256 while (i < maxI && image.isBlack(centerJ, i) && stateCount[4] < maxCount) {
\r
260 if (stateCount[4] >= maxCount) {
\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
271 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : float.NaN;
\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
279 private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) {
\r
280 MonochromeBitmapSource image = this.image;
\r
282 int maxJ = image.getWidth();
\r
283 int[] stateCount = getCrossCheckStateCount();
\r
286 while (j >= 0 && image.isBlack(j, centerI)) {
\r
293 while (j >= 0 && !image.isBlack(j, centerI) && stateCount[1] <= maxCount) {
\r
297 if (j < 0 || stateCount[1] > maxCount) {
\r
300 while (j >= 0 && image.isBlack(j, centerI) && stateCount[0] <= maxCount) {
\r
304 if (stateCount[0] > maxCount) {
\r
309 while (j < maxJ && image.isBlack(j, centerI)) {
\r
316 while (j < maxJ && !image.isBlack(j, centerI) && stateCount[3] < maxCount) {
\r
320 if (j == maxJ || stateCount[3] >= maxCount) {
\r
323 while (j < maxJ && image.isBlack(j, centerI) && stateCount[4] < maxCount) {
\r
327 if (stateCount[4] >= maxCount) {
\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
338 return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : float.NaN;
\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
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
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
357 private bool handlePossibleCenter(int[] stateCount,
\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
365 centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
\r
366 if (!Single.IsNaN(centerJ))
\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
381 possibleCenters.Add(new FinderPattern(centerJ, centerI, estimatedModuleSize));
\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
395 private int findRowSkip() {
\r
396 int max = possibleCenters.Count;
\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
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
413 return (int) (Math.Abs(firstConfirmedCenter.getX() - center.getX()) -
\r
414 Math.Abs(firstConfirmedCenter.getY() - center.getY())) / 2;
\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
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
434 totalModuleSize += pattern.getEstimatedModuleSize();
\r
437 if (confirmedCount < 3) {
\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
450 return totalDeviation <= 0.15f * totalModuleSize;
\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
459 private FinderPattern[] selectBestPatterns(){
\r
460 Collections.insertionSort(possibleCenters, new CenterComparator());
\r
462 int max = possibleCenters.Count;
\r
463 while (size < max) {
\r
464 if (((FinderPattern) possibleCenters[size]).getCount() < CENTER_QUORUM) {
\r
471 // Couldn't find enough finder patterns
\r
472 throw new ReaderException();
\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
484 averageModuleSize /= (float) size;
\r
485 // We don't have java.util.Collections in J2ME
\r
486 Collections.insertionSort(possibleCenters, new ClosestToAverageComparator(averageModuleSize));
\r
489 return new FinderPattern[]{
\r
490 (FinderPattern) possibleCenters[0],
\r
491 (FinderPattern) possibleCenters[1],
\r
492 (FinderPattern) possibleCenters[2]
\r
497 * <p>Orders by {@link FinderPattern#getCount()}, descending.</p>
\r
499 private class CenterComparator : Comparator {
\r
500 public int compare(object center1, object center2)
\r
502 return ((FinderPattern) center2).getCount() - ((FinderPattern) center1).getCount();
\r
507 * <p>Orders by variance from average module size, ascending.</p>
\r
509 private class ClosestToAverageComparator : Comparator {
\r
510 private float averageModuleSize;
\r
512 public ClosestToAverageComparator(float averageModuleSize) {
\r
513 this.averageModuleSize = averageModuleSize;
\r
516 public int compare(object center1, object center2)
\r
518 return Math.Abs(((FinderPattern) center1).getEstimatedModuleSize() - averageModuleSize) <
\r
519 Math.Abs(((FinderPattern) center2).getEstimatedModuleSize() - averageModuleSize) ?
\r