3b55eb696b101fb563622ab288aaa22aebac250b
[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   public BitMatrix sampleGrid(BitMatrix image,
96                               int dimension,
97                               PerspectiveTransform transform) throws NotFoundException {
98     throw new IllegalStateException(); // Can't use UnsupportedOperationException
99   }
100   
101
102   /**
103    * <p>Checks a set of points that have been transformed to sample points on an image against
104    * the image's dimensions to see if the point are even within the image.</p>
105    *
106    * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
107    * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
108    * patterns in an image where the QR Code runs all the way to the image border.</p>
109    *
110    * <p>For efficiency, the method will check points from either end of the line until one is found
111    * to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
112    *
113    * @param image image into which the points should map
114    * @param points actual points in x1,y1,...,xn,yn form
115    * @throws NotFoundException if an endpoint is lies outside the image boundaries
116    */
117   protected static void checkAndNudgePoints(BitMatrix image, float[] points)
118       throws NotFoundException {
119     int width = image.getWidth();
120     int height = image.getHeight();
121     // Check and nudge points from start until we see some that are OK:
122     boolean nudged = true;
123     for (int offset = 0; offset < points.length && nudged; offset += 2) {
124       int x = (int) points[offset];
125       int y = (int) points[offset + 1];
126       if (x < -1 || x > width || y < -1 || y > height) {
127         throw NotFoundException.getNotFoundInstance();
128       }
129       nudged = false;
130       if (x == -1) {
131         points[offset] = 0.0f;
132         nudged = true;
133       } else if (x == width) {
134         points[offset] = width - 1;
135         nudged = true;
136       }
137       if (y == -1) {
138         points[offset + 1] = 0.0f;
139         nudged = true;
140       } else if (y == height) {
141         points[offset + 1] = height - 1;
142         nudged = true;
143       }
144     }
145     // Check and nudge points from end:
146     nudged = true;
147     for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {
148       int x = (int) points[offset];
149       int y = (int) points[offset + 1];
150       if (x < -1 || x > width || y < -1 || y > height) {
151         throw NotFoundException.getNotFoundInstance();
152       }
153       nudged = false;
154       if (x == -1) {
155         points[offset] = 0.0f;
156         nudged = true;
157       } else if (x == width) {
158         points[offset] = width - 1;
159         nudged = true;
160       }
161       if (y == -1) {
162         points[offset + 1] = 0.0f;
163         nudged = true;
164       } else if (y == height) {
165         points[offset + 1] = height - 1;
166         nudged = true;
167       }
168     }
169   }
170
171 }