/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*namespace com.google.zxing.qrcode.detector {*/ import DecodeHintType from './../../DecodeHintType'; import ResultPoint from './../../ResultPoint'; import ResultPointCallback from './../../ResultPointCallback'; import BitMatrix from './../../common/BitMatrix'; import FinderPattern from './FinderPattern'; import FinderPatternInfo from './FinderPatternInfo'; import Exception from './../../Exception'; /*import java.io.Serializable;*/ /*import java.util.ArrayList;*/ /*import java.util.Collections;*/ /*import java.util.Comparator;*/ /*import java.util.List;*/ /*import java.util.Map;*/ /** *
This class attempts to find finder patterns in a QR Code. Finder patterns are the square * markers at three corners of a QR Code.
* *This class is thread-safe but not reentrant. Each thread must allocate its own object. * * @author Sean Owen */ export default class FinderPatternFinder { private static CENTER_QUORUM = 2; protected static MIN_SKIP = 3; // 1 pixel/module times 3 modules/center protected static MAX_MODULES = 57; // support up to version 10 for mobile clients private possibleCenters: FinderPattern[]; private hasSkipped: boolean; private crossCheckStateCount: Int32Array; /** *
Creates a finder that will search the image for three finder patterns.
* * @param image image to search */ // public constructor(image: BitMatrix) { // this(image, null) // } public constructor(private image: BitMatrix, private resultPointCallback: ResultPointCallback) { this.possibleCenters = []; this.crossCheckStateCount = new Int32Array(5); this.resultPointCallback = resultPointCallback; } protected getImage(): BitMatrix { return this.image; } protected getPossibleCenters(): FinderPattern[] { return this.possibleCenters; } public find(hints: MapAfter a horizontal scan finds a potential finder pattern, this method * "cross-checks" by scanning down vertically through the center of the possible * finder pattern to see if the same proportion is detected.
* * @param startI row where a finder pattern was detected * @param centerJ center of the section that appears to cross a finder pattern * @param maxCount maximum reasonable number of modules that should be * observed in any reading state, based on the results of the horizontal scan * @return vertical center of finder pattern, or {@link Float#NaN} if not found */ private crossCheckVertical(startI: number /*int*/, centerJ: number /*int*/, maxCount: number /*int*/, originalStateCountTotal: number /*int*/): number/*float*/ { const image: BitMatrix = this.image; const maxI = image.getHeight(); const stateCount: Int32Array = this.getCrossCheckStateCount(); // Start counting up from center let i = startI; while (i >= 0 && image.get(centerJ, i)) { stateCount[2]++; i--; } if (i < 0) { return NaN; } while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return NaN; } while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image.get(centerJ, i)) { stateCount[2]++; i++; } if (i === maxI) { return NaN; } while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i === maxI || stateCount[3] >= maxCount) { return NaN; } while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return NaN; } // If we found a finder-pattern-like section, but its size is more than 40% different than // the original, assume it's a false positive const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return NaN; } return FinderPatternFinder.foundPatternCross(stateCount) ? FinderPatternFinder.centerFromEnd(stateCount, i) : NaN; } /** *Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, * except it reads horizontally instead of vertically. This is used to cross-cross * check a vertical cross check and locate the real center of the alignment pattern.
*/ private crossCheckHorizontal(startJ: number /*int*/, centerI: number /*int*/, maxCount: number /*int*/, originalStateCountTotal: number /*int*/): number/*float*/ { const image: BitMatrix = this.image; const maxJ = image.getWidth(); const stateCount: Int32Array = this.getCrossCheckStateCount(); let j = startJ; while (j >= 0 && image.get(j, centerI)) { stateCount[2]++; j--; } if (j < 0) { return NaN; } while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return NaN; } while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return NaN; } j = startJ + 1; while (j < maxJ && image.get(j, centerI)) { stateCount[2]++; j++; } if (j === maxJ) { return NaN; } while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j === maxJ || stateCount[3] >= maxCount) { return NaN; } while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return NaN; } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return NaN; } return FinderPatternFinder.foundPatternCross(stateCount) ? FinderPatternFinder.centerFromEnd(stateCount, j) : NaN; } /** *This is called when a horizontal scan finds a possible alignment pattern. It will * cross check with a vertical scan, and if successful, will, ah, cross-cross-check * with another horizontal scan. This is needed primarily to locate the real horizontal * center of the pattern in cases of extreme skew. * And then we cross-cross-cross check with another diagonal scan.
* *If that succeeds the finder pattern location is added to a list that tracks * the number of times each location has been nearly-matched as a finder pattern. * Each additional find is more evidence that the location is in fact a finder * pattern center * * @param stateCount reading state module counts from horizontal scan * @param i row where finder pattern may be found * @param j end of possible finder pattern in row * @param pureBarcode true if in "pure barcode" mode * @return true if a finder pattern candidate was found this time */ protected handlePossibleCenter(stateCount: Int32Array, i: number /*int*/, j: number /*int*/, pureBarcode: boolean): boolean { const stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; let centerJ: number /*float*/ = FinderPatternFinder.centerFromEnd(stateCount, j); let centerI: number /*float*/ = this.crossCheckVertical(i, /*(int) */Math.floor(centerJ), stateCount[2], stateCountTotal); if (!isNaN(centerI)) { // Re-cross check centerJ = this.crossCheckHorizontal(/*(int) */Math.floor(centerJ), /*(int) */Math.floor(centerI), stateCount[2], stateCountTotal); if (!isNaN(centerJ) && (!pureBarcode || this.crossCheckDiagonal(/*(int) */Math.floor(centerI), /*(int) */Math.floor(centerJ), stateCount[2], stateCountTotal))) { const estimatedModuleSize: number /*float*/ = stateCountTotal / 7.0; let found: boolean = false; const possibleCenters = this.possibleCenters; for (let index = 0, length = possibleCenters.length; index < length; index++) { const center: FinderPattern = possibleCenters[index]; // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { possibleCenters[index] = center.combineEstimate(centerI, centerJ, estimatedModuleSize); found = true; break; } } if (!found) { const point: FinderPattern = new FinderPattern(centerJ, centerI, estimatedModuleSize); possibleCenters.push(point); if (this.resultPointCallback !== null && this.resultPointCallback !== undefined) { this.resultPointCallback.foundPossibleResultPoint(point); } } return true; } } return false; } /** * @return number of rows we could safely skip during scanning, based on the first * two finder patterns that have been located. In some cases their position will * allow us to infer that the third pattern must lie below a certain point farther * down in the image. */ private findRowSkip(): number /*int*/ { const max = this.possibleCenters.length; if (max <= 1) { return 0; } let firstConfirmedCenter: ResultPoint = null; for (const center of this.possibleCenters) { if (center.getCount() >= FinderPatternFinder.CENTER_QUORUM) { if (firstConfirmedCenter == null) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left last. this.hasSkipped = true; return /*(int) */Math.floor((Math.abs(firstConfirmedCenter.getX() - center.getX()) - Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2); } } } return 0; } /** * @return true iff we have found at least 3 finder patterns that have been detected * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the * candidates is "pretty similar" */ private haveMultiplyConfirmedCenters(): boolean { let confirmedCount = 0; let totalModuleSize: number /*float*/ = 0.0; const max = this.possibleCenters.length; for (const pattern of this.possibleCenters) { if (pattern.getCount() >= FinderPatternFinder.CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern.getEstimatedModuleSize(); } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. const average: number /*float*/ = totalModuleSize / max; let totalDeviation: number /*float*/ = 0.0; for (const pattern of this.possibleCenters) { totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average); } return totalDeviation <= 0.05 * totalModuleSize; } /** * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module * size differs from the average among those patterns the least * @throws NotFoundException if 3 such finder patterns do not exist */ private selectBestPatterns(): FinderPattern[] /*throws NotFoundException */ { const startSize = this.possibleCenters.length; if (startSize < 3) { // Couldn't find enough finder patterns throw new Exception(Exception.NotFoundException); } const possibleCenters = this.possibleCenters; let average: number; /*float*/ // Filter outlier possibilities whose module size is too different if (startSize > 3) { // But we can only afford to do so if we have at least 4 possibilities to choose from let totalModuleSize: number /*float*/ = 0.0; let square: number /*float*/ = 0.0; for (const center of this.possibleCenters) { const size: number /*float*/ = center.getEstimatedModuleSize(); totalModuleSize += size; square += size * size; } average = totalModuleSize / startSize; let stdDev: number /*float*/ = /*(float) */Math.sqrt(square / startSize - average * average); possibleCenters.sort( /** *
Orders by furthest from average
*/ // FurthestFromAverageComparator implements ComparatorOrders by {@link FinderPattern#getCount()}, descending.
*/ // CenterComparator implements Comparator