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.qrcode.decoder.Version;
30 import java.util.Hashtable;
33 * <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code
34 * is rotated or skewed, or partially obscured.</p>
38 public class Detector {
40 private final BitMatrix image;
41 private ResultPointCallback resultPointCallback;
43 public Detector(BitMatrix image) {
47 protected BitMatrix getImage() {
51 protected ResultPointCallback getResultPointCallback() {
52 return resultPointCallback;
56 * <p>Detects a QR Code in an image, simply.</p>
58 * @return {@link DetectorResult} encapsulating results of detecting a QR Code
59 * @throws NotFoundException if no QR Code can be found
61 public DetectorResult detect() throws NotFoundException, FormatException {
66 * <p>Detects a QR Code in an image, simply.</p>
68 * @param hints optional hints to detector
69 * @return {@link NotFoundException} encapsulating results of detecting a QR Code
70 * @throws NotFoundException if QR Code cannot be found
71 * @throws FormatException if a QR Code cannot be decoded
73 public DetectorResult detect(Hashtable hints) throws NotFoundException, FormatException {
75 resultPointCallback = hints == null ? null :
76 (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
78 FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback);
79 FinderPatternInfo info = finder.find(hints);
81 return processFinderPatternInfo(info);
84 protected DetectorResult processFinderPatternInfo(FinderPatternInfo info)
85 throws NotFoundException, FormatException {
87 FinderPattern topLeft = info.getTopLeft();
88 FinderPattern topRight = info.getTopRight();
89 FinderPattern bottomLeft = info.getBottomLeft();
91 float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
92 if (moduleSize < 1.0f) {
93 throw NotFoundException.getNotFoundInstance();
95 int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
96 Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
97 int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
99 AlignmentPattern alignmentPattern = null;
100 // Anything above version 1 has an alignment pattern
101 if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
103 // Guess where a "bottom right" finder pattern would have been
104 float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
105 float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
107 // Estimate that alignment pattern is closer by 3 modules
108 // from "bottom right" to known top left location
109 float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
110 int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
111 int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
113 // Kind of arbitrary -- expand search radius before giving up
114 for (int i = 4; i <= 16; i <<= 1) {
116 alignmentPattern = findAlignmentInRegion(moduleSize,
121 } catch (NotFoundException re) {
125 // If we didn't find alignment pattern... well try anyway without it
128 PerspectiveTransform transform =
129 createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);
131 BitMatrix bits = sampleGrid(image, transform, dimension);
133 ResultPoint[] points;
134 if (alignmentPattern == null) {
135 points = new ResultPoint[]{bottomLeft, topLeft, topRight};
137 points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
139 return new DetectorResult(bits, points);
142 public PerspectiveTransform createTransform(ResultPoint topLeft,
143 ResultPoint topRight,
144 ResultPoint bottomLeft,
145 ResultPoint alignmentPattern,
147 float dimMinusThree = (float) dimension - 3.5f;
150 float sourceBottomRightX;
151 float sourceBottomRightY;
152 if (alignmentPattern != null) {
153 bottomRightX = alignmentPattern.getX();
154 bottomRightY = alignmentPattern.getY();
155 sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f;
157 // Don't have an alignment pattern, just make up the bottom-right point
158 bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX();
159 bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY();
160 sourceBottomRightX = sourceBottomRightY = dimMinusThree;
163 return PerspectiveTransform.quadrilateralToQuadrilateral(
182 private static BitMatrix sampleGrid(BitMatrix image,
183 PerspectiveTransform transform,
184 int dimension) throws NotFoundException {
186 GridSampler sampler = GridSampler.getInstance();
187 return sampler.sampleGrid(image, dimension, dimension, transform);
191 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
192 * of the finder patterns and estimated module size.</p>
194 protected static int computeDimension(ResultPoint topLeft,
195 ResultPoint topRight,
196 ResultPoint bottomLeft,
197 float moduleSize) throws NotFoundException {
198 int tltrCentersDimension = round(ResultPoint.distance(topLeft, topRight) / moduleSize);
199 int tlblCentersDimension = round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
200 int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
201 switch (dimension & 0x03) { // mod 4
210 throw NotFoundException.getNotFoundInstance();
216 * <p>Computes an average estimated module size based on estimated derived from the positions
217 * of the three finder patterns.</p>
219 protected float calculateModuleSize(ResultPoint topLeft,
220 ResultPoint topRight,
221 ResultPoint bottomLeft) {
223 return (calculateModuleSizeOneWay(topLeft, topRight) +
224 calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
228 * <p>Estimates module size based on two finder patterns -- it uses
229 * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the
230 * width of each, measuring along the axis between their centers.</p>
232 private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) {
233 float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
234 (int) pattern.getY(),
235 (int) otherPattern.getX(),
236 (int) otherPattern.getY());
237 float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(),
238 (int) otherPattern.getY(),
239 (int) pattern.getX(),
240 (int) pattern.getY());
241 if (Float.isNaN(moduleSizeEst1)) {
242 return moduleSizeEst2 / 7.0f;
244 if (Float.isNaN(moduleSizeEst2)) {
245 return moduleSizeEst1 / 7.0f;
247 // Average them, and divide by 7 since we've counted the width of 3 black modules,
248 // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
249 return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
253 * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of
254 * a finder pattern by looking for a black-white-black run from the center in the direction
255 * of another point (another finder pattern center), and in the opposite direction too.</p>
257 private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
259 float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
261 // Now count other way -- don't run off image though of course
263 int otherToX = fromX - (toX - fromX);
265 scale = (float) fromX / (float) (fromX - otherToX);
267 } else if (otherToX > image.getWidth()) {
268 scale = (float) (image.getWidth() - fromX) / (float) (otherToX - fromX);
269 otherToX = image.getWidth();
271 int otherToY = (int) (fromY - (toY - fromY) * scale);
275 scale = (float) fromY / (float) (fromY - otherToY);
277 } else if (otherToY > image.getHeight()) {
278 scale = (float) (image.getHeight() - fromY) / (float) (otherToY - fromY);
279 otherToY = image.getHeight();
281 otherToX = (int) (fromX + (otherToX - fromX) * scale);
283 result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
288 * <p>This method traces a line from a point in the image, in the direction towards another point.
289 * It begins in a black region, and keeps going until it finds white, then black, then white again.
290 * It reports the distance from the start to this point.</p>
292 * <p>This is used when figuring out how wide a finder pattern is, when the finder pattern
293 * may be skewed or rotated.</p>
295 private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
296 // Mild variant of Bresenham's algorithm;
297 // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
298 boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
308 int dx = Math.abs(toX - fromX);
309 int dy = Math.abs(toY - fromY);
310 int error = -dx >> 1;
311 int ystep = fromY < toY ? 1 : -1;
312 int xstep = fromX < toX ? 1 : -1;
313 int state = 0; // In black pixels, looking for white, first or second time
314 for (int x = fromX, y = fromY; x != toX; x += xstep) {
316 int realX = steep ? y : x;
317 int realY = steep ? x : y;
318 if (state == 1) { // In white pixels, looking for black
319 if (image.get(realX, realY)) {
323 if (!image.get(realX, realY)) {
328 if (state == 3) { // Found black, white, black, and stumbled back onto white; done
329 int diffX = x - fromX;
330 int diffY = y - fromY;
334 return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
345 int diffX = toX - fromX;
346 int diffY = toY - fromY;
347 return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
351 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
352 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
354 * @param overallEstModuleSize estimated module size so far
355 * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
356 * @param estAlignmentY y coordinate of above
357 * @param allowanceFactor number of pixels in all directions to search from the center
358 * @return {@link AlignmentPattern} if found, or null otherwise
359 * @throws NotFoundException if an unexpected error occurs during detection
361 protected AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
364 float allowanceFactor)
365 throws NotFoundException {
366 // Look for an alignment pattern (3 modules in size) around where it
368 int allowance = (int) (allowanceFactor * overallEstModuleSize);
369 int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
370 int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
371 if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
372 throw NotFoundException.getNotFoundInstance();
375 int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
376 int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
377 if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {
378 throw NotFoundException.getNotFoundInstance();
381 AlignmentPatternFinder alignmentFinder =
382 new AlignmentPatternFinder(
386 alignmentAreaRightX - alignmentAreaLeftX,
387 alignmentAreaBottomY - alignmentAreaTopY,
388 overallEstModuleSize,
389 resultPointCallback);
390 return alignmentFinder.find();
394 * Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int,
395 * where x.5 rounds up.
397 private static int round(float d) {
398 return (int) (d + 0.5f);