Issue 158: Correct some off-by-one problems in Data Matrix detector and a few more...
[zxing.git] / core / src / com / google / zxing / common / GridSampler.java
1 /*
2  * Copyright 2007 ZXing authors
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.common;
18
19 import com.google.zxing.MonochromeBitmapSource;
20 import com.google.zxing.ReaderException;
21
22 /**
23  * Implementations of this class can, given locations of finder patterns for a QR code in an
24  * image, sample the right points in the image to reconstruct the QR code, accounting for
25  * perspective distortion. It is abstracted since it is relatively expensive and should be allowed
26  * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
27  * Imaging library, but which may not be available in other environments such as J2ME, and vice
28  * versa.
29  *
30  * The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
31  * with an instance of a class which implements this interface.
32  *
33  * @author Sean Owen
34  */
35 public abstract class GridSampler {
36
37   private static GridSampler gridSampler = null;
38
39   /**
40    * Sets the implementation of {@link GridSampler} used by the library. One global
41    * instance is stored, which may sound problematic. But, the implementation provided
42    * ought to be appropriate for the entire platform, and all uses of this library
43    * in the whole lifetime of the JVM. For instance, an Android activity can swap in
44    * an implementation that takes advantage of native platform libraries.
45    * 
46    * @param newGridSampler
47    */
48   public static void setGridSampler(GridSampler newGridSampler) {
49     if (newGridSampler == null) {
50       throw new IllegalArgumentException();
51     }
52     gridSampler = newGridSampler;
53   }
54
55   /**
56    * @return the current implementation of {@link GridSampler}
57    */
58   public static GridSampler getInstance() {
59     // No real point in trying to make this thread-safe;
60     // doesn't matter if a second instance is created
61     if (gridSampler == null) {
62       gridSampler = new DefaultGridSampler();
63     }
64     return gridSampler;
65   }
66
67   /**
68    * <p>Samples an image for a square matrix of bits of the given dimension. This is used to extract the
69    * black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode may be
70    * rotated or perspective-distorted, the caller supplies four points in the source image that define
71    * known points in the barcode, so that the image may be sampled appropriately.</p>
72    *
73    * <p>The last eight "from" parameters are four X/Y coordinate pairs of locations of points in
74    * the image that define some significant points in the image to be sample. For example,
75    * these may be the location of finder pattern in a QR Code.</p>
76    *
77    * <p>The first eight "to" parameters are four X/Y coordinate pairs measured in the destination
78    * {@link BitMatrix}, from the top left, where the known points in the image given by the "from" parameters
79    * map to.</p>
80    *
81    * <p>These 16 parameters define the transformation needed to sample the image.</p>
82    *
83    * @param image image to sample
84    * @param dimension width/height of {@link BitMatrix} to sample from iamge
85    * @return {@link BitMatrix} representing a grid of points sampled from the image within a region
86    *  defined by the "from" parameters
87    * @throws ReaderException if image can't be sampled, for example, if the transformation defined by
88    *  the given points is invalid or results in sampling outside the image boundaries
89    */
90   public abstract BitMatrix sampleGrid(MonochromeBitmapSource image,
91                                        int dimension,
92                                        float p1ToX, float p1ToY,
93                                        float p2ToX, float p2ToY,
94                                        float p3ToX, float p3ToY,
95                                        float p4ToX, float p4ToY,
96                                        float p1FromX, float p1FromY,
97                                        float p2FromX, float p2FromY,
98                                        float p3FromX, float p3FromY,
99                                        float p4FromX, float p4FromY) throws ReaderException;
100
101   /**
102    * <p>Checks a set of points that have been transformed to sample points on an image against
103    * the image's dimensions to see if the point are even within the image.</p>
104    *
105    * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be barely
106    * (less than 1 pixel) off the image. This accounts for imperfect detection of finder patterns in an image
107    * where the QR Code runs all the way to the image border.</p>
108    *
109    * <p>For efficiency, the method will check points from either end of the line until one is found
110    * to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
111    *
112    * @param image image into which the points should map
113    * @param points actual points in x1,y1,...,xn,yn form
114    * @throws ReaderException if an endpoint is lies outside the image boundaries
115    */
116   protected static void checkAndNudgePoints(MonochromeBitmapSource image, float[] points) throws ReaderException {
117     int width = image.getWidth();
118     int height = image.getHeight();
119     // Check and nudge points from start until we see some that are OK:
120     boolean nudged = true;
121     for (int offset = 0; offset < points.length && nudged; offset += 2) {
122       int x = (int) points[offset];
123       int y = (int) points[offset + 1];
124       if (x < -1 || x > width || y < -1 || y > height) {
125         throw ReaderException.getInstance();
126       }
127       nudged = false;
128       if (x == -1) {
129         points[offset] = 0.0f;
130         nudged = true;
131       } else if (x == width) {
132         points[offset] = width - 1;
133         nudged = true;
134       }
135       if (y == -1) {
136         points[offset + 1] = 0.0f;
137         nudged = true;
138       } else if (y == height) {
139         points[offset + 1] = height - 1;
140         nudged = true;
141       }
142     }
143     // Check and nudge points from end:
144     nudged = true;
145     for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
146       int x = (int) points[offset];
147       int y = (int) points[offset + 1];
148       if (x < -1 || x > width || y < -1 || y > height) {
149         throw ReaderException.getInstance();
150       }
151       nudged = false;
152       if (x == -1) {
153         points[offset] = 0.0f;
154         nudged = true;
155       } else if (x == width) {
156         points[offset] = width - 1;
157         nudged = true;
158       }
159       if (y == -1) {
160         points[offset + 1] = 0.0f;
161         nudged = true;
162       } else if (y == height) {
163         points[offset + 1] = height - 1;
164         nudged = true;
165       }
166     }
167   }
168
169 }