2 * Copyright 2007 ZXing authors
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.DecodeHintType;
20 import com.google.zxing.FormatException;
21 import com.google.zxing.NotFoundException;
22 import com.google.zxing.ResultPoint;
23 import com.google.zxing.ResultPointCallback;
24 import com.google.zxing.common.BitMatrix;
25 import com.google.zxing.common.DetectorResult;
26 import com.google.zxing.common.GridSampler;
27 import com.google.zxing.common.PerspectiveTransform;
28 import com.google.zxing.common.detector.MathUtils;
29 import com.google.zxing.qrcode.decoder.Version;
34 * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
35 * is rotated or skewed, or partially obscured.</p>
39 public class Detector {
41 private final BitMatrix image;
42 private ResultPointCallback resultPointCallback;
44 public Detector(BitMatrix image) {
48 protected final BitMatrix getImage() {
52 protected final ResultPointCallback getResultPointCallback() {
53 return resultPointCallback;
57 * <p>Detects a QR Code in an image, simply.</p>
59 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
60 * @throws NotFoundException if no QR Code can be found
62 public DetectorResult detect() throws NotFoundException, FormatException {
67 * <p>Detects a QR Code in an image, simply.</p>
69 * @param hints optional hints to detector
70 * @return {@link NotFoundException} encapsulating results of detecting a QR Code
71 * @throws NotFoundException if QR Code cannot be found
72 * @throws FormatException if a QR Code cannot be decoded
74 public final DetectorResult detect(Map<DecodeHintType,?> hints) throws NotFoundException, FormatException {
76 resultPointCallback = hints == null ? null :
77 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
79 FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
80 FinderPatternInfo info = finder.find(hints);
82 return processFinderPatternInfo(info);
85 protected final DetectorResult processFinderPatternInfo(FinderPatternInfo info)
86 throws NotFoundException, FormatException {
88 FinderPattern topLeft = info.getTopLeft();
89 FinderPattern topRight = info.getTopRight();
90 FinderPattern bottomLeft = info.getBottomLeft();
92 float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
93 if (moduleSize < 1.0f) {
94 throw NotFoundException.getNotFoundInstance();
96 int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
97 Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
98 int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
100 AlignmentPattern alignmentPattern = null;
101 // Anything above version 1 has an alignment pattern
102 if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
104 // Guess where a "bottom right" finder pattern would have been
105 float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
106 float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
108 // Estimate that alignment pattern is closer by 3 modules
109 // from "bottom right" to known top left location
110 float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
111 int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
112 int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
114 // Kind of arbitrary -- expand search radius before giving up
115 for (int i = 4; i <= 16; i <<= 1) {
117 alignmentPattern = findAlignmentInRegion(moduleSize,
122 } catch (NotFoundException re) {
126 // If we didn't find alignment pattern... well try anyway without it
129 PerspectiveTransform transform =
130 createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
132 BitMatrix bits = sampleGrid(image, transform, dimension);
134 ResultPoint[] points;
135 if (alignmentPattern == null) {
136 points = new ResultPoint[]{bottomLeft, topLeft, topRight};
138 points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
140 return new DetectorResult(bits, points);
143 private static PerspectiveTransform createTransform(ResultPoint topLeft,
144 ResultPoint topRight,
145 ResultPoint bottomLeft,
146 ResultPoint alignmentPattern,
148 float dimMinusThree = (float) dimension - 3.5f;
151 float sourceBottomRightX;
152 float sourceBottomRightY;
153 if (alignmentPattern != null) {
154 bottomRightX = alignmentPattern.getX();
155 bottomRightY = alignmentPattern.getY();
156 sourceBottomRightX = dimMinusThree - 3.0f;
157 sourceBottomRightY = sourceBottomRightX;
159 // Don't have an alignment pattern, just make up the bottom-right point
160 bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX();
161 bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY();
162 sourceBottomRightX = dimMinusThree;
163 sourceBottomRightY = dimMinusThree;
166 return PerspectiveTransform.quadrilateralToQuadrilateral(
185 private static BitMatrix sampleGrid(BitMatrix image,
186 PerspectiveTransform transform,
187 int dimension) throws NotFoundException {
189 GridSampler sampler = GridSampler.getInstance();
190 return sampler.sampleGrid(image, dimension, dimension, transform);
194 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
195 * of the finder patterns and estimated module size.</p>
197 private static int computeDimension(ResultPoint topLeft,
198 ResultPoint topRight,
199 ResultPoint bottomLeft,
200 float moduleSize) throws NotFoundException {
201 int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
202 int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
203 int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
204 switch (dimension & 0x03) { // mod 4
213 throw NotFoundException.getNotFoundInstance();
219 * <p>Computes an average estimated module size based on estimated derived from the positions
220 * of the three finder patterns.</p>
222 protected final float calculateModuleSize(ResultPoint topLeft,
223 ResultPoint topRight,
224 ResultPoint bottomLeft) {
226 return (calculateModuleSizeOneWay(topLeft, topRight) +
227 calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
231 * <p>Estimates module size based on two finder patterns -- it uses
232 * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
233 * width of each, measuring along the axis between their centers.</p>
235 private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) {
236 float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
237 (int) pattern.getY(),
238 (int) otherPattern.getX(),
239 (int) otherPattern.getY());
240 float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(),
241 (int) otherPattern.getY(),
242 (int) pattern.getX(),
243 (int) pattern.getY());
244 if (Float.isNaN(moduleSizeEst1)) {
245 return moduleSizeEst2 / 7.0f;
247 if (Float.isNaN(moduleSizeEst2)) {
248 return moduleSizeEst1 / 7.0f;
250 // Average them, and divide by 7 since we've counted the width of 3 black modules,
251 // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
252 return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
256 * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
257 * a finder pattern by looking for a black-white-black run from the center in the direction
258 * of another point (another finder pattern center), and in the opposite direction too.</p>
260 private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
262 float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
264 // Now count other way -- don't run off image though of course
266 int otherToX = fromX - (toX - fromX);
268 scale = (float) fromX / (float) (fromX - otherToX);
270 } else if (otherToX >= image.getWidth()) {
271 scale = (float) (image.getWidth() - 1 - fromX) / (float) (otherToX - fromX);
272 otherToX = image.getWidth() - 1;
274 int otherToY = (int) (fromY - (toY - fromY) * scale);
278 scale = (float) fromY / (float) (fromY - otherToY);
280 } else if (otherToY >= image.getHeight()) {
281 scale = (float) (image.getHeight() - 1 - fromY) / (float) (otherToY - fromY);
282 otherToY = image.getHeight() - 1;
284 otherToX = (int) (fromX + (otherToX - fromX) * scale);
286 result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
288 // Middle pixel is double-counted this way; subtract 1
289 return result - 1.0f;
293 * <p>This method traces a line from a point in the image, in the direction towards another point.
294 * It begins in a black region, and keeps going until it finds white, then black, then white again.
295 * It reports the distance from the start to this point.</p>
297 * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
298 * may be skewed or rotated.</p>
300 private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
301 // Mild variant of Bresenham's algorithm;
302 // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
303 boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
313 int dx = Math.abs(toX - fromX);
314 int dy = Math.abs(toY - fromY);
315 int error = -dx >> 1;
316 int xstep = fromX < toX ? 1 : -1;
317 int ystep = fromY < toY ? 1 : -1;
319 // In black pixels, looking for white, first or second time.
321 // Loop up until x == toX, but not beyond
322 int xLimit = toX + xstep;
323 for (int x = fromX, y = fromY; x != xLimit; x += xstep) {
324 int realX = steep ? y : x;
325 int realY = steep ? x : y;
327 // Does current pixel mean we have moved white to black or vice versa?
328 // Scanning black in state 0,2 and white in state 1, so if we find the wrong
329 // color, advance to next state or end if we are in state 2 already
330 if ((state == 1) == image.get(realX, realY)) {
332 return MathUtils.distance(x, y, fromX, fromY);
346 // Found black-white-black; give the benefit of the doubt that the next pixel outside the image
347 // is "white" so this last point at (toX+xStep,toY) is the right ending. This is really a
348 // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.
350 return MathUtils.distance(toX + xstep, toY, fromX, fromY);
352 // else we didn't find even black-white-black; no estimate is really possible
357 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
358 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
360 * @param overallEstModuleSize estimated module size so far
361 * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
362 * @param estAlignmentY y coordinate of above
363 * @param allowanceFactor number of pixels in all directions to search from the center
364 * @return {@link AlignmentPattern} if found, or null otherwise
365 * @throws NotFoundException if an unexpected error occurs during detection
367 protected final AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
370 float allowanceFactor)
371 throws NotFoundException {
372 // Look for an alignment pattern (3 modules in size) around where it
374 int allowance = (int) (allowanceFactor * overallEstModuleSize);
375 int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
376 int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
377 if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
378 throw NotFoundException.getNotFoundInstance();
381 int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
382 int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
383 if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {
384 throw NotFoundException.getNotFoundInstance();
387 AlignmentPatternFinder alignmentFinder =
388 new AlignmentPatternFinder(
392 alignmentAreaRightX - alignmentAreaLeftX,
393 alignmentAreaBottomY - alignmentAreaTopY,
394 overallEstModuleSize,
395 resultPointCallback);
396 return alignmentFinder.find();