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.MonochromeBitmapSource;
20 import com.google.zxing.ReaderException;
21 import com.google.zxing.ResultPoint;
22 import com.google.zxing.common.BitMatrix;
23 import com.google.zxing.qrcode.decoder.Version;
26 * @author srowen@google.com (Sean Owen)
28 public final class Detector {
30 private final MonochromeBitmapSource image;
32 public Detector(MonochromeBitmapSource image) {
36 public DetectorResult detect() throws ReaderException {
38 MonochromeBitmapSource image = this.image;
40 FinderPatternFinder finder = new FinderPatternFinder(image);
41 FinderPatternInfo info = finder.find();
43 FinderPattern topLeft = info.getTopLeft();
44 FinderPattern topRight = info.getTopRight();
45 FinderPattern bottomLeft = info.getBottomLeft();
47 float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
48 int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
49 Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
50 int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;
52 // Guess where a "bottom right" finder pattern would have been
53 float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
54 float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();
56 AlignmentPattern alignmentPattern = null;
57 // Anything above version 1 has an alignment pattern
58 if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
60 // Estimate that alignment pattern is closer by 3 modules
61 // from "bottom right" to known top left location
62 float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
63 int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
64 int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));
66 // Kind of arbitrary -- expand search radius before giving up
67 for (int i = 4; i <= 16; i <<= 1) {
69 alignmentPattern = findAlignmentInRegion(moduleSize,
74 } catch (ReaderException de) {
78 if (alignmentPattern == null) {
79 throw new ReaderException("Could not find alignment pattern");
84 GridSampler sampler = GridSampler.getInstance();
85 BitMatrix bits = sampler.sampleGrid(image,
94 BufferedImage outImage =
95 new BufferedImage(dimension,
97 BufferedImage.TYPE_BYTE_BINARY);
98 for (int i = 0; i < dimension; i++) {
99 for (int j = 0; j < dimension; j++) {
100 if (bits.get(i, j)) {
101 outImage.setRGB(j, i, 0xFF000000);
103 outImage.setRGB(j, i, 0xFFFFFFFF);
107 ImageIO.write(outImage, "PNG",
108 new File("/home/srowen/out.png"));
109 } catch (IOException ioe) {
110 ioe.printStackTrace();
114 ResultPoint[] points;
115 if (alignmentPattern == null) {
116 points = new ResultPoint[] { bottomLeft, topLeft, topRight };
118 points = new ResultPoint[] { bottomLeft, topLeft, topRight, alignmentPattern };
120 return new DetectorResult(bits, points);
123 private static int computeDimension(ResultPoint topLeft,
124 ResultPoint topRight,
125 ResultPoint bottomLeft,
127 throws ReaderException {
128 int tltrCentersDimension =
129 round(FinderPatternFinder.distance(topLeft, topRight) / moduleSize);
130 int tlblCentersDimension =
131 round(FinderPatternFinder.distance(topLeft, bottomLeft) / moduleSize);
132 int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
133 switch (dimension & 0x03) { // mod 4
142 throw new ReaderException("Bad dimension: " + dimension);
147 private float calculateModuleSize(ResultPoint topLeft,
148 ResultPoint topRight,
149 ResultPoint bottomLeft) {
151 return (calculateModuleSizeOneWay(topLeft, topRight) +
152 calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
155 private float calculateModuleSizeOneWay(ResultPoint pattern,
156 ResultPoint otherPattern) {
157 float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.getX(),
158 (int) pattern.getY(),
159 (int) otherPattern.getX(),
160 (int) otherPattern.getY());
161 float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.getX(),
162 (int) otherPattern.getY(),
163 (int) pattern.getX(),
164 (int) pattern.getY());
165 if (Float.isNaN(moduleSizeEst1)) {
166 return moduleSizeEst2;
168 if (Float.isNaN(moduleSizeEst2)) {
169 return moduleSizeEst1;
171 // Average them, and divide by 7 since we've counted the width of 3 black modules,
172 // and 1 white and 1 black module on either side. Ergo, divide sum by 14.
173 return (moduleSizeEst1 + moduleSizeEst2) / 14.0f;
176 private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
177 float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
178 result += sizeOfBlackWhiteBlackRun(fromX, fromY, fromX - (toX - fromX), fromY - (toY - fromY));
179 return result - 1.0f; // -1 because we counted the middle pixel twice
182 private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) {
183 // Mild variant of Bresenham's algorithm;
184 // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm
185 boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
195 int dx = Math.abs(toX - fromX);
196 int dy = Math.abs(toY - fromY);
197 int error = -dx >> 1;
198 int ystep = fromY < toY ? 1 : -1;
199 int xstep = fromX < toX ? 1 : -1;
200 int state = 0; // In black pixels, looking for white, first or second time
201 for (int x = fromX, y = fromY; x != toX; x += xstep) {
203 int realX = steep ? y : x;
204 int realY = steep ? x : y;
205 if (state == 1) { // In white pixels, looking for black
206 if (image.isBlack(realX, realY)) {
210 if (!image.isBlack(realX, realY)) {
215 if (state == 3) { // Found black, white, black, and stumbled back onto white; done
216 int diffX = x - fromX;
217 int diffY = y - fromY;
218 return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
226 // Hmm, couldn't find all of what we wanted -- don't know
230 private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
233 float allowanceFactor)
234 throws ReaderException {
235 // Look for an alignment pattern (3 modules in size) around where it
237 int allowance = (int) (allowanceFactor * overallEstModuleSize);
238 int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
239 int alignmentAreaRightX = Math.min(image.getWidth() - 1,
240 estAlignmentX + allowance);
241 int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
242 int alignmentAreaBottomY = Math.min(image.getHeight() - 1,
243 estAlignmentY + allowance);
245 AlignmentPatternFinder alignmentFinder =
246 new AlignmentPatternFinder(
250 alignmentAreaRightX - alignmentAreaLeftX,
251 alignmentAreaBottomY - alignmentAreaTopY,
252 overallEstModuleSize);
253 return alignmentFinder.find();
257 * Ends up being a bit faster than Math.round()
259 private static int round(float d) {
260 return (int) (d + 0.5f);