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