2 * Copyright 2007 Google Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.qrcode.detector;
19 import com.google.zxing.BlackPointEstimationMethod;
20 import com.google.zxing.MonochromeBitmapSource;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.ResultPoint;
23 import com.google.zxing.common.BitMatrix;
24 import com.google.zxing.common.DetectorResult;
25 import com.google.zxing.qrcode.decoder.Version;
28 * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
29 * is rotated or skewed, or partially obscured.</p>
31 * @author srowen@google.com (Sean Owen)
33 public final class Detector {
35 private final MonochromeBitmapSource image;
37 public Detector(MonochromeBitmapSource image) {
42 * <p>Detects a QR Code in an image, simply.</p>
44 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
45 * @throws ReaderException if no QR Code can be found
47 public DetectorResult detect() throws ReaderException {
49 MonochromeBitmapSource image = this.image;
50 if (!BlackPointEstimationMethod.TWO_D_SAMPLING.equals(image.getLastEstimationMethod())) {
51 image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
54 FinderPatternFinder finder = new FinderPatternFinder(image);
55 FinderPatternInfo info = finder.find();
57 FinderPattern topLeft = info.getTopLeft();
58 FinderPattern topRight = info.getTopRight();
59 FinderPattern bottomLeft = info.getBottomLeft();
61 float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
62 int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
63 Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
64 int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
66 AlignmentPattern alignmentPattern = null;
67 // Anything above version 1 has an alignment pattern
68 if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
70 // Guess where a "bottom right" finder pattern would have been
71 float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
72 float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
74 // Estimate that alignment pattern is closer by 3 modules
75 // from "bottom right" to known top left location
76 float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
77 int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
78 int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
80 // Kind of arbitrary -- expand search radius before giving up
81 for (int i = 4; i <= 16; i <<= 1) {
83 alignmentPattern = findAlignmentInRegion(moduleSize,
88 } catch (ReaderException re) {
92 if (alignmentPattern == null) {
93 throw new ReaderException("Could not find alignment pattern");
98 GridSampler sampler = GridSampler.getInstance();
99 BitMatrix bits = sampler.sampleGrid(image, topLeft, topRight, bottomLeft, alignmentPattern, dimension);
101 ResultPoint[] points;
102 if (alignmentPattern == null) {
103 points = new ResultPoint[]{bottomLeft, topLeft, topRight};
105 points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
107 return new DetectorResult(bits, points);
111 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
112 * of the finder patterns and estimated module size.</p>
114 private static int computeDimension(ResultPoint topLeft,
115 ResultPoint topRight,
116 ResultPoint bottomLeft,
117 float moduleSize) throws ReaderException {
118 int tltrCentersDimension = round(FinderPatternFinder.distance(topLeft, topRight) / moduleSize);
119 int tlblCentersDimension = round(FinderPatternFinder.distance(topLeft, bottomLeft) / moduleSize);
120 int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
121 switch (dimension & 0x03) { // mod 4
130 throw new ReaderException("Bad dimension: " + dimension);
136 * <p>Computes an average estimated module size based on estimated derived from the positions
137 * of the three finder patterns.</p>
139 private float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) {
141 return (calculateModuleSizeOneWay(topLeft, topRight) +
142 calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
146 * <p>Estimates module size based on two finder patterns -- it uses
147 * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
148 * width of each, measuring along the axis between their centers.</p>
150 private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) {
151 float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
152 (int) pattern.getY(),
153 (int) otherPattern.getX(),
154 (int) otherPattern.getY());
155 float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(),
156 (int) otherPattern.getY(),
157 (int) pattern.getX(),
158 (int) pattern.getY());
159 if (Float.isNaN(moduleSizeEst1)) {
160 return moduleSizeEst2;
162 if (Float.isNaN(moduleSizeEst2)) {
163 return moduleSizeEst1;
165 // Average them, and divide by 7 since we've counted the width of 3 black modules,
166 // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
167 return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
171 * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
172 * a finder pattern by looking for a black-white-black run from the center in the direction
173 * of another point (another finder pattern center), and in the opposite direction too.</p>
175 private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
177 float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
179 // Now count other way -- don't run off image though of course
180 int otherToX = fromX - (toX - fromX);
182 // "to" should the be the first value not included, so, the first value off
185 } else if (otherToX >= image.getWidth()) {
186 otherToX = image.getWidth();
188 int otherToY = fromY - (toY - fromY);
191 } else if (otherToY >= image.getHeight()) {
192 otherToY = image.getHeight();
194 result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
195 return result - 1.0f; // -1 because we counted the middle pixel twice
199 * <p>This method traces a line from a point in the image, in the direction towards another point.
200 * It begins in a black region, and keeps going until it finds white, then black, then white again.
201 * It reports the distance from the start to this point.</p>
203 * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
204 * may be skewed or rotated.</p>
206 private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
207 // Mild variant of Bresenham's algorithm;
208 // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
209 boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
219 int dx = Math.abs(toX - fromX);
220 int dy = Math.abs(toY - fromY);
221 int error = -dx >> 1;
222 int ystep = fromY < toY ? 1 : -1;
223 int xstep = fromX < toX ? 1 : -1;
224 int state = 0; // In black pixels, looking for white, first or second time
225 for (int x = fromX, y = fromY; x != toX; x += xstep) {
227 int realX = steep ? y : x;
228 int realY = steep ? x : y;
229 if (state == 1) { // In white pixels, looking for black
230 if (image.isBlack(realX, realY)) {
234 if (!image.isBlack(realX, realY)) {
239 if (state == 3) { // Found black, white, black, and stumbled back onto white; done
240 int diffX = x - fromX;
241 int diffY = y - fromY;
242 return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
250 int diffX = toX - fromX;
251 int diffY = toY - fromY;
252 return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
256 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
257 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
259 * @param overallEstModuleSize estimated module size so far
260 * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
261 * @param estAlignmentY y coordinate of above
262 * @param allowanceFactor number of pixels in all directons to search from the center
263 * @return {@link AlignmentPattern} if found, or null otherwise
264 * @throws ReaderException if an unexpected error occurs during detection
266 private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
269 float allowanceFactor)
270 throws ReaderException {
271 // Look for an alignment pattern (3 modules in size) around where it
273 int allowance = (int) (allowanceFactor * overallEstModuleSize);
274 int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
275 int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
276 int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
277 int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
279 AlignmentPatternFinder alignmentFinder =
280 new AlignmentPatternFinder(
284 alignmentAreaRightX - alignmentAreaLeftX,
285 alignmentAreaBottomY - alignmentAreaTopY,
286 overallEstModuleSize);
287 return alignmentFinder.find();
291 * Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int,
292 * where x.5 rounds up.
294 private static int round(float d) {
295 return (int) (d + 0.5f);