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.qrcode.decoder.Version;
27 * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
28 * is rotated or skewed, or partially obscured.</p>
30 * @author srowen@google.com (Sean Owen)
32 public final class Detector {
34 private final MonochromeBitmapSource image;
36 public Detector(MonochromeBitmapSource image) {
41 * <p>Detects a QR Code in an image, simply.</p>
43 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
44 * @throws ReaderException if no QR Code can be found
46 public DetectorResult detect() throws ReaderException {
48 MonochromeBitmapSource image = this.image;
49 if (!BlackPointEstimationMethod.TWO_D_SAMPLING.equals(image.getLastEstimationMethod())) {
50 image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
53 FinderPatternFinder finder = new FinderPatternFinder(image);
54 FinderPatternInfo info = finder.find();
56 FinderPattern topLeft = info.getTopLeft();
57 FinderPattern topRight = info.getTopRight();
58 FinderPattern bottomLeft = info.getBottomLeft();
60 float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
61 int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
62 Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
63 int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
65 // Guess where a "bottom right" finder pattern would have been
66 float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
67 float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
69 AlignmentPattern alignmentPattern = null;
70 // Anything above version 1 has an alignment pattern
71 if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
73 // Estimate that alignment pattern is closer by 3 modules
74 // from "bottom right" to known top left location
75 float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
76 int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
77 int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
79 // Kind of arbitrary -- expand search radius before giving up
80 for (int i = 4; i <= 16; i <<= 1) {
82 alignmentPattern = findAlignmentInRegion(moduleSize,
87 } catch (ReaderException re) {
91 if (alignmentPattern == null) {
92 throw new ReaderException("Could not find alignment pattern");
97 GridSampler sampler = GridSampler.getInstance();
98 BitMatrix bits = sampler.sampleGrid(image, topLeft, topRight, bottomLeft, alignmentPattern, dimension);
100 ResultPoint[] points;
101 if (alignmentPattern == null) {
102 points = new ResultPoint[] { bottomLeft, topLeft, topRight };
104 points = new ResultPoint[] { bottomLeft, topLeft, topRight, alignmentPattern };
106 return new DetectorResult(bits, points);
110 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
111 * of the finder patterns and estimated module size.</p>
113 private static int computeDimension(ResultPoint topLeft,
114 ResultPoint topRight,
115 ResultPoint bottomLeft,
116 float moduleSize) throws ReaderException {
117 int tltrCentersDimension = round(FinderPatternFinder.distance(topLeft, topRight) / moduleSize);
118 int tlblCentersDimension = round(FinderPatternFinder.distance(topLeft, bottomLeft) / moduleSize);
119 int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
120 switch (dimension & 0x03) { // mod 4
129 throw new ReaderException("Bad dimension: " + dimension);
135 * <p>Computes an average estimated module size based on estimated derived from the positions
136 * of the three finder patterns.</p>
138 private float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) {
140 return (calculateModuleSizeOneWay(topLeft, topRight) +
141 calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
145 * <p>Estimates module size based on two finder patterns -- it uses
146 * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
147 * width of each, measuring along the axis between their centers.</p>
149 private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) {
150 float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
151 (int) pattern.getY(),
152 (int) otherPattern.getX(),
153 (int) otherPattern.getY());
154 float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(),
155 (int) otherPattern.getY(),
156 (int) pattern.getX(),
157 (int) pattern.getY());
158 if (Float.isNaN(moduleSizeEst1)) {
159 return moduleSizeEst2;
161 if (Float.isNaN(moduleSizeEst2)) {
162 return moduleSizeEst1;
164 // Average them, and divide by 7 since we've counted the width of 3 black modules,
165 // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
166 return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
170 * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
171 * a finder pattern by looking for a black-white-black run from the center in the direction
172 * of another point (another finder pattern center), and in the opposite direction too.</p>
174 private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
175 float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
176 result += sizeOfBlackWhiteBlackRun(fromX, fromY, fromX - (toX - fromX), fromY - (toY - fromY));
177 return result - 1.0f; // -1 because we counted the middle pixel twice
181 * <p>This method traces a line from a point in the image, in the direction towards another point.
182 * It begins in a black region, and keeps going until it finds white, then black, then white again.
183 * It reports the distance from the start to this point.</p>
185 * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
186 * may be skewed or rotated.</p>
188 private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
189 // Mild variant of Bresenham's algorithm;
190 // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
191 boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
201 int dx = Math.abs(toX - fromX);
202 int dy = Math.abs(toY - fromY);
203 int error = -dx >> 1;
204 int ystep = fromY < toY ? 1 : -1;
205 int xstep = fromX < toX ? 1 : -1;
206 int state = 0; // In black pixels, looking for white, first or second time
207 for (int x = fromX, y = fromY; x != toX; x += xstep) {
209 int realX = steep ? y : x;
210 int realY = steep ? x : y;
211 if (state == 1) { // In white pixels, looking for black
212 if (image.isBlack(realX, realY)) {
216 if (!image.isBlack(realX, realY)) {
221 if (state == 3) { // Found black, white, black, and stumbled back onto white; done
222 int diffX = x - fromX;
223 int diffY = y - fromY;
224 return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
232 // Hmm, couldn't find all of what we wanted -- don't know
237 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
238 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
240 * @param overallEstModuleSize estimated module size so far
241 * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
242 * @param estAlignmentY y coordinate of above
243 * @param allowanceFactor number of pixels in all directons to search from the center
244 * @return {@link AlignmentPattern} if found, or null otherwise
245 * @throws ReaderException if an unexpected error occurs during detection
247 private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
250 float allowanceFactor)
251 throws ReaderException {
252 // Look for an alignment pattern (3 modules in size) around where it
254 int allowance = (int) (allowanceFactor * overallEstModuleSize);
255 int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
256 int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
257 int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
258 int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
260 AlignmentPatternFinder alignmentFinder =
261 new AlignmentPatternFinder(
265 alignmentAreaRightX - alignmentAreaLeftX,
266 alignmentAreaBottomY - alignmentAreaTopY,
267 overallEstModuleSize);
268 return alignmentFinder.find();
272 * Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int,
273 * where x.5 rounds up.
275 private static int round(float d) {
276 return (int) (d + 0.5f);