2 * Copyright 2008 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.datamatrix.detector;
19 import com.google.zxing.NotFoundException;
20 import com.google.zxing.ResultPoint;
21 import com.google.zxing.common.BitMatrix;
22 import com.google.zxing.common.Collections;
23 import com.google.zxing.common.Comparator;
24 import com.google.zxing.common.DetectorResult;
25 import com.google.zxing.common.GridSampler;
26 import com.google.zxing.common.detector.WhiteRectangleDetector;
28 import java.util.Enumeration;
29 import java.util.Hashtable;
30 import java.util.Vector;
33 * <p>Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code
34 * is rotated or skewed, or partially obscured.</p>
38 public final class Detector {
40 // Trick to avoid creating new Integer objects below -- a sort of crude copy of
41 // the Integer.valueOf(int) optimization added in Java 5, not in J2ME
42 private static final Integer[] INTEGERS =
43 { new Integer(0), new Integer(1), new Integer(2), new Integer(3), new Integer(4) };
44 // No, can't use valueOf()
46 private final BitMatrix image;
47 private final WhiteRectangleDetector rectangleDetector;
49 public Detector(BitMatrix image) {
51 rectangleDetector = new WhiteRectangleDetector(image);
55 * <p>Detects a Data Matrix Code in an image.</p>
57 * @return {@link DetectorResult} encapsulating results of detecting a Data Matrix Code
58 * @throws NotFoundException if no Data Matrix Code can be found
60 public DetectorResult detect() throws NotFoundException {
62 ResultPoint[] cornerPoints = rectangleDetector.detect();
63 ResultPoint pointA = cornerPoints[0];
64 ResultPoint pointB = cornerPoints[1];
65 ResultPoint pointC = cornerPoints[2];
66 ResultPoint pointD = cornerPoints[3];
68 // Point A and D are across the diagonal from one another,
69 // as are B and C. Figure out which are the solid black lines
70 // by counting transitions
71 Vector transitions = new Vector(4);
72 transitions.addElement(transitionsBetween(pointA, pointB));
73 transitions.addElement(transitionsBetween(pointA, pointC));
74 transitions.addElement(transitionsBetween(pointB, pointD));
75 transitions.addElement(transitionsBetween(pointC, pointD));
76 Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator());
78 // Sort by number of transitions. First two will be the two solid sides; last two
79 // will be the two alternating black/white sides
80 ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions) transitions.elementAt(0);
81 ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions) transitions.elementAt(1);
83 // Figure out which point is their intersection by tallying up the number of times we see the
84 // endpoints in the four endpoints. One will show up twice.
85 Hashtable pointCount = new Hashtable();
86 increment(pointCount, lSideOne.getFrom());
87 increment(pointCount, lSideOne.getTo());
88 increment(pointCount, lSideTwo.getFrom());
89 increment(pointCount, lSideTwo.getTo());
91 ResultPoint maybeTopLeft = null;
92 ResultPoint bottomLeft = null;
93 ResultPoint maybeBottomRight = null;
94 Enumeration points = pointCount.keys();
95 while (points.hasMoreElements()) {
96 ResultPoint point = (ResultPoint) points.nextElement();
97 Integer value = (Integer) pointCount.get(point);
98 if (value.intValue() == 2) {
99 bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides
101 // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now
102 if (maybeTopLeft == null) {
103 maybeTopLeft = point;
105 maybeBottomRight = point;
110 if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) {
111 throw NotFoundException.getNotFoundInstance();
114 // Bottom left is correct but top left and bottom right might be switched
115 ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight };
116 // Use the dot product trick to sort them out
117 ResultPoint.orderBestPatterns(corners);
119 // Now we know which is which:
120 ResultPoint bottomRight = corners[0];
121 bottomLeft = corners[1];
122 ResultPoint topLeft = corners[2];
124 // Which point didn't we find in relation to the "L" sides? that's the top right corner
125 ResultPoint topRight;
126 if (!pointCount.containsKey(pointA)) {
128 } else if (!pointCount.containsKey(pointB)) {
130 } else if (!pointCount.containsKey(pointC)) {
136 // Next determine the dimension by tracing along the top or right side and counting black/white
137 // transitions. Since we start inside a black module, we should see a number of transitions
138 // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to
139 // end on a black module:
141 // The top right point is actually the corner of a module, which is one of the two black modules
142 // adjacent to the white module at the top right. Tracing to that corner from either the top left
143 // or bottom right should work here.
146 int dimensionTop = transitionsBetween(topLeft, topRight).getTransitions();
147 int dimensionRight = transitionsBetween(bottomRight, topRight).getTransitions();
149 if ((dimensionTop & 0x01) == 1) {
150 // it can't be odd, so, round... up?
155 if ((dimensionRight & 0x01) == 1) {
156 // it can't be odd, so, round... up?
161 BitMatrix bits = null;
162 ResultPoint correctedTopRight = null;
164 if (dimensionTop >= dimensionRight * 2 || dimensionRight >= dimensionTop * 2){
165 //The matrix is rectangular
167 correctedTopRight = correctTopRightRectangular(bottomLeft, bottomRight, topLeft, topRight, dimensionTop, dimensionRight);
168 if (correctedTopRight == null){
169 correctedTopRight = topRight;
172 dimensionTop = transitionsBetween(topLeft, correctedTopRight).getTransitions();
173 dimensionRight = transitionsBetween(bottomRight, correctedTopRight).getTransitions();
175 if ((dimensionTop & 0x01) == 1) {
176 // it can't be odd, so, round... up?
180 if ((dimensionRight & 0x01) == 1) {
181 // it can't be odd, so, round... up?
185 bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionTop, dimensionRight);
188 //The matrix is square
190 int dimension = Math.min(dimensionRight, dimensionTop);
191 //correct top right point to match the white module
192 correctedTopRight = correctTopRight(bottomLeft, bottomRight, topLeft, topRight, dimension);
193 if (correctedTopRight == null){
194 correctedTopRight = topRight;
197 //We redetermine the dimension using the corrected top right point
198 int dimensionCorrected = Math.max(transitionsBetween(topLeft, correctedTopRight).getTransitions(),
199 transitionsBetween(bottomRight, correctedTopRight).getTransitions());
200 dimensionCorrected++;
201 if ((dimensionCorrected & 0x01) == 1) {
202 dimensionCorrected++;
205 bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionCorrected, dimensionCorrected);
209 return new DetectorResult(bits, new ResultPoint[]{topLeft, bottomLeft, bottomRight, correctedTopRight});
213 * Calculates the position of the white top right module using the output of the rectangle detector for a rectangular matrix
215 private ResultPoint correctTopRightRectangular(ResultPoint bottomLeft,
216 ResultPoint bottomRight, ResultPoint topLeft, ResultPoint topRight,
217 int dimensionTop, int dimensionRight) {
219 float corr = distance(bottomLeft, bottomRight) / (float)dimensionTop;
220 int norm = distance(topLeft, topRight);
221 float cos = (topRight.getX() - topLeft.getX()) / norm;
222 float sin = (topRight.getY() - topLeft.getY()) / norm;
224 ResultPoint c1 = new ResultPoint(topRight.getX()+corr*cos, topRight.getY()+corr*sin);
226 corr = distance(bottomLeft, topLeft) / (float)dimensionRight;
227 norm = distance(bottomRight, topRight);
228 cos = (topRight.getX() - bottomRight.getX()) / norm;
229 sin = (topRight.getY() - bottomRight.getY()) / norm;
231 ResultPoint c2 = new ResultPoint(topRight.getX()+corr*cos, topRight.getY()+corr*sin);
238 } else if (!isValid(c2)){
242 int l1 = Math.abs(dimensionTop - transitionsBetween(topLeft, c1).getTransitions()) +
243 Math.abs(dimensionRight - transitionsBetween(bottomRight, c1).getTransitions());
244 int l2 = Math.abs(dimensionTop - transitionsBetween(topLeft, c2).getTransitions()) +
245 Math.abs(dimensionRight - transitionsBetween(bottomRight, c2).getTransitions());
255 * Calculates the position of the white top right module using the output of the rectangle detector for a square matrix
257 private ResultPoint correctTopRight(ResultPoint bottomLeft,
258 ResultPoint bottomRight,
260 ResultPoint topRight,
263 float corr = distance(bottomLeft, bottomRight) / (float) dimension;
264 int norm = distance(topLeft, topRight);
265 float cos = (topRight.getX() - topLeft.getX()) / norm;
266 float sin = (topRight.getY() - topLeft.getY()) / norm;
268 ResultPoint c1 = new ResultPoint(topRight.getX() + corr * cos, topRight.getY() + corr * sin);
270 corr = distance(bottomLeft, bottomRight) / (float) dimension;
271 norm = distance(bottomRight, topRight);
272 cos = (topRight.getX() - bottomRight.getX()) / norm;
273 sin = (topRight.getY() - bottomRight.getY()) / norm;
275 ResultPoint c2 = new ResultPoint(topRight.getX() + corr * cos, topRight.getY() + corr * sin);
282 } else if (!isValid(c2)) {
286 int l1 = Math.abs(transitionsBetween(topLeft, c1).getTransitions() -
287 transitionsBetween(bottomRight, c1).getTransitions());
288 int l2 = Math.abs(transitionsBetween(topLeft, c2).getTransitions() -
289 transitionsBetween(bottomRight, c2).getTransitions());
291 return l1 <= l2 ? c1 : c2;
294 private boolean isValid(ResultPoint p) {
295 return (p.getX() >= 0 && p.getX() < image.width && p.getY() > 0 && p.getY() < image.height);
299 * Ends up being a bit faster than Math.round(). This merely rounds its
300 * argument to the nearest int, where x.5 rounds up.
302 private static int round(float d) {
303 return (int) (d + 0.5f);
307 private static int distance(ResultPoint a, ResultPoint b) {
308 return round((float) Math.sqrt((a.getX() - b.getX())
309 * (a.getX() - b.getX()) + (a.getY() - b.getY())
310 * (a.getY() - b.getY())));
314 * Increments the Integer associated with a key by one.
316 private static void increment(Hashtable table, ResultPoint key) {
317 Integer value = (Integer) table.get(key);
318 table.put(key, value == null ? INTEGERS[1] : INTEGERS[value.intValue() + 1]);
321 private static BitMatrix sampleGrid(BitMatrix image,
323 ResultPoint bottomLeft,
324 ResultPoint bottomRight,
325 ResultPoint topRight,
327 int dimensionY) throws NotFoundException {
329 GridSampler sampler = GridSampler.getInstance();
331 return sampler.sampleGrid(image,
353 * Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.
355 private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to) {
356 // See QR Code Detector, sizeOfBlackWhiteBlackRun()
357 int fromX = (int) from.getX();
358 int fromY = (int) from.getY();
359 int toX = (int) to.getX();
360 int toY = (int) to.getY();
361 boolean steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);
371 int dx = Math.abs(toX - fromX);
372 int dy = Math.abs(toY - fromY);
373 int error = -dx >> 1;
374 int ystep = fromY < toY ? 1 : -1;
375 int xstep = fromX < toX ? 1 : -1;
377 boolean inBlack = image.get(steep ? fromY : fromX, steep ? fromX : fromY);
378 for (int x = fromX, y = fromY; x != toX; x += xstep) {
379 boolean isBlack = image.get(steep ? y : x, steep ? x : y);
380 if (isBlack != inBlack) {
393 return new ResultPointsAndTransitions(from, to, transitions);
397 * Simply encapsulates two points and a number of transitions between them.
399 private static class ResultPointsAndTransitions {
400 private final ResultPoint from;
401 private final ResultPoint to;
402 private final int transitions;
403 private ResultPointsAndTransitions(ResultPoint from, ResultPoint to, int transitions) {
406 this.transitions = transitions;
408 public ResultPoint getFrom() {
411 public ResultPoint getTo() {
414 public int getTransitions() {
417 public String toString() {
418 return from + "/" + to + '/' + transitions;
423 * Orders ResultPointsAndTransitions by number of transitions, ascending.
425 private static class ResultPointsAndTransitionsComparator implements Comparator {
426 public int compare(Object o1, Object o2) {
427 return ((ResultPointsAndTransitions) o1).getTransitions() - ((ResultPointsAndTransitions) o2).getTransitions();