Completed some modest tweaks to new Data Matrix code based on IntelliJ suggestions
[zxing.git] / core / src / com / google / zxing / qrcode / detector / Detector.java
1 /*
2  * Copyright 2007 Google Inc.
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.qrcode.detector;
18
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;
26
27 /**
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>
30  *
31  * @author srowen@google.com (Sean Owen)
32  */
33 public final class Detector {
34
35   private final MonochromeBitmapSource image;
36
37   public Detector(MonochromeBitmapSource image) {
38     this.image = image;
39   }
40
41   /**
42    * <p>Detects a QR Code in an image, simply.</p>
43    *
44    * @return {@link DetectorResult} encapsulating results of detecting a QR Code
45    * @throws ReaderException if no QR Code can be found
46    */
47   public DetectorResult detect() throws ReaderException {
48
49     MonochromeBitmapSource image = this.image;
50     if (!BlackPointEstimationMethod.TWO_D_SAMPLING.equals(image.getLastEstimationMethod())) {
51       image.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
52     }
53
54     FinderPatternFinder finder = new FinderPatternFinder(image);
55     FinderPatternInfo info = finder.find();
56
57     FinderPattern topLeft = info.getTopLeft();
58     FinderPattern topRight = info.getTopRight();
59     FinderPattern bottomLeft = info.getBottomLeft();
60
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;
65
66     AlignmentPattern alignmentPattern = null;
67     // Anything above version 1 has an alignment pattern
68     if (provisionalVersion.getAlignmentPatternCenters().length > 0) {
69
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();
73
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()));
79
80       // Kind of arbitrary -- expand search radius before giving up
81       for (int i = 4; i <= 16; i <<= 1) {
82         try {
83           alignmentPattern = findAlignmentInRegion(moduleSize,
84               estAlignmentX,
85               estAlignmentY,
86               (float) i);
87           break;
88         } catch (ReaderException re) {
89           // try next round
90         }
91       }
92       if (alignmentPattern == null) {
93         throw new ReaderException("Could not find alignment pattern");
94       }
95
96     }
97
98     GridSampler sampler = GridSampler.getInstance();
99     BitMatrix bits = sampler.sampleGrid(image, topLeft, topRight, bottomLeft, alignmentPattern, dimension);
100
101     ResultPoint[] points;
102     if (alignmentPattern == null) {
103       points = new ResultPoint[]{bottomLeft, topLeft, topRight};
104     } else {
105       points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
106     }
107     return new DetectorResult(bits, points);
108   }
109
110   /**
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>
113    */
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
122       case 0:
123         dimension++;
124         break;
125         // 1? do nothing
126       case 2:
127         dimension--;
128         break;
129       case 3:
130         throw new ReaderException("Bad dimension: " + dimension);
131     }
132     return dimension;
133   }
134
135   /**
136    * <p>Computes an average estimated module size based on estimated derived from the positions
137    * of the three finder patterns.</p>
138    */
139   private float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) {
140     // Take the average
141     return (calculateModuleSizeOneWay(topLeft, topRight) +
142         calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f;
143   }
144
145   /**
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>
149    */
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;
161     }
162     if (Float.isNaN(moduleSizeEst2)) {
163       return moduleSizeEst1;
164     }
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;
168   }
169
170   /**
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>
174    */
175   private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) {
176
177     float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);
178
179     // Now count other way -- don't run off image though of course
180     int otherToX = fromX - (toX - fromX);
181     if (otherToX < 0) {
182       // "to" should the be the first value not included, so, the first value off
183       // the edge is -1
184       otherToX = -1;
185     } else if (otherToX >= image.getWidth()) {
186       otherToX = image.getWidth();
187     }
188     int otherToY = fromY - (toY - fromY);
189     if (otherToY < 0) {
190       otherToY = -1;
191     } else if (otherToY >= image.getHeight()) {
192       otherToY = image.getHeight();
193     }
194     result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);
195     return result - 1.0f; // -1 because we counted the middle pixel twice
196   }
197
198   /**
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>
202    *
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>
205    */
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);
210     if (steep) {
211       int temp = fromX;
212       fromX = fromY;
213       fromY = temp;
214       temp = toX;
215       toX = toY;
216       toY = temp;
217     }
218
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) {
226
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)) {
231           state++;
232         }
233       } else {
234         if (!image.isBlack(realX, realY)) {
235           state++;
236         }
237       }
238
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));
243       }
244       error += dy;
245       if (error > 0) {
246         y += ystep;
247         error -= dx;
248       }
249     }
250     int diffX = toX - fromX;
251     int diffY = toY - fromY;
252     return (float) Math.sqrt((double) (diffX * diffX + diffY * diffY));
253   }
254
255   /**
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>
258    *
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
265    */
266   private AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
267                                                  int estAlignmentX,
268                                                  int estAlignmentY,
269                                                  float allowanceFactor)
270       throws ReaderException {
271     // Look for an alignment pattern (3 modules in size) around where it
272     // should be
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);
278
279     AlignmentPatternFinder alignmentFinder =
280         new AlignmentPatternFinder(
281             image,
282             alignmentAreaLeftX,
283             alignmentAreaTopY,
284             alignmentAreaRightX - alignmentAreaLeftX,
285             alignmentAreaBottomY - alignmentAreaTopY,
286             overallEstModuleSize);
287     return alignmentFinder.find();
288   }
289
290   /**
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.
293    */
294   private static int round(float d) {
295     return (int) (d + 0.5f);
296   }
297
298 }