Draft of 'thinking' visualization for barcode scanning. Works for 1D and QR codes.
[zxing.git] / core / src / com / google / zxing / oned / AbstractOneDReader.java
1 /*
2  * Copyright 2008 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.oned;
18
19 import com.google.zxing.BinaryBitmap;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.ReaderException;
22 import com.google.zxing.Result;
23 import com.google.zxing.ResultMetadataType;
24 import com.google.zxing.ResultPoint;
25 import com.google.zxing.common.BitArray;
26
27 import java.util.Hashtable;
28
29 /**
30  * <p>Encapsulates functionality and implementation that is common to all families
31  * of one-dimensional barcodes.</p>
32  *
33  * @author dswitkin@google.com (Daniel Switkin)
34  * @author Sean Owen
35  */
36 public abstract class AbstractOneDReader implements OneDReader {
37
38   private static final int INTEGER_MATH_SHIFT = 8;
39   static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
40
41   public final Result decode(BinaryBitmap image) throws ReaderException {
42     return decode(image, null);
43   }
44
45   public final Result decode(BinaryBitmap image, Hashtable hints) throws ReaderException {
46     try {
47       return doDecode(image, hints);
48     } catch (ReaderException re) {
49       boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
50       if (tryHarder && image.isRotateSupported()) {
51         BinaryBitmap rotatedImage = image.rotateCounterClockwise();
52         Result result = doDecode(rotatedImage, hints);
53         // Record that we found it rotated 90 degrees CCW / 270 degrees CW
54         Hashtable metadata = result.getResultMetadata();
55         int orientation = 270;
56         if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
57           // But if we found it reversed in doDecode(), add in that result here:
58           orientation = (orientation +
59               ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
60         }
61         result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
62         return result;
63       } else {
64         throw re;
65       }
66     }
67   }
68
69   /**
70    * We're going to examine rows from the middle outward, searching alternately above and below the
71    * middle, and farther out each time. rowStep is the number of rows between each successive
72    * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
73    * middle + rowStep, then middle - (2 * rowStep), etc.
74    * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
75    * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
76    * image if "trying harder".
77    *
78    * @param image The image to decode
79    * @param hints Any hints that were requested
80    * @return The contents of the decoded barcode
81    * @throws ReaderException Any spontaneous errors which occur
82    */
83   private Result doDecode(BinaryBitmap image, Hashtable hints) throws ReaderException {
84     int width = image.getWidth();
85     int height = image.getHeight();
86     BitArray row = new BitArray(width);
87
88     int middle = height >> 1;
89     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
90     int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
91     int maxLines;
92     if (tryHarder) {
93       maxLines = height; // Look at the whole image, not just the center
94     } else {
95       maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
96     }
97
98     for (int x = 0; x < maxLines; x++) {
99
100       // Scanning from the middle out. Determine which row we're looking at next:
101       int rowStepsAboveOrBelow = (x + 1) >> 1;
102       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
103       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
104       if (rowNumber < 0 || rowNumber >= height) {
105         // Oops, if we run off the top or bottom, stop
106         break;
107       }
108
109       // Estimate black point for this row and load it:
110       try {
111         row = image.getBlackRow(rowNumber, row);
112       } catch (ReaderException re) {
113         continue;
114       }      
115
116       // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
117       // handle decoding upside down barcodes.
118       for (int attempt = 0; attempt < 2; attempt++) {
119         if (attempt == 1) { // trying again?
120           row.reverse(); // reverse the row and continue
121           // This means we will only ever draw result points *once* in the life of this method
122           // since we want to avoid drawing the wrong points after flipping the row, and,
123           // don't want to clutter with noise from every single row scan -- just the scans
124           // that start on the center line.
125           if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
126             hints = (Hashtable) hints.clone();
127             hints.remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
128           }
129         }
130         try {
131           // Look for a barcode
132           Result result = decodeRow(rowNumber, row, hints);
133           // We found our barcode
134           if (attempt == 1) {
135             // But it was upside down, so note that
136             result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
137             // And remember to flip the result points horizontally.
138             ResultPoint[] points = result.getResultPoints();
139             points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
140             points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
141           }
142           return result;
143         } catch (ReaderException re) {
144           // continue -- just couldn't decode this row
145         }
146       }
147     }
148
149     throw ReaderException.getInstance();
150   }
151
152   /**
153    * Records the size of successive runs of white and black pixels in a row, starting at a given point.
154    * The values are recorded in the given array, and the number of runs recorded is equal to the size
155    * of the array. If the row starts on a white pixel at the given start point, then the first count
156    * recorded is the run of white pixels starting from that point; likewise it is the count of a run
157    * of black pixels if the row begin on a black pixels at that point.
158    *
159    * @param row row to count from
160    * @param start offset into row to start at
161    * @param counters array into which to record counts
162    * @throws ReaderException if counters cannot be filled entirely from row before running out
163    *  of pixels
164    */
165   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
166     int numCounters = counters.length;
167     for (int i = 0; i < numCounters; i++) {
168       counters[i] = 0;
169     }
170     int end = row.getSize();
171     if (start >= end) {
172       throw ReaderException.getInstance();
173     }
174     boolean isWhite = !row.get(start);
175     int counterPosition = 0;
176     int i = start;
177     while (i < end) {
178       boolean pixel = row.get(i);
179       if (pixel ^ isWhite) { // that is, exactly one is true
180         counters[counterPosition]++;
181       } else {
182         counterPosition++;
183         if (counterPosition == numCounters) {
184           break;
185         } else {
186           counters[counterPosition] = 1;
187           isWhite ^= true; // isWhite = !isWhite;  Is this too clever? shorter byte code, no conditional
188         }
189       }
190       i++;
191     }
192     // If we read fully the last section of pixels and filled up our counters -- or filled
193     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
194     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
195       throw ReaderException.getInstance();
196     }
197   }
198
199   /**
200    * Determines how closely a set of observed counts of runs of black/white values matches a given
201    * target pattern. This is reported as the ratio of the total variance from the expected pattern
202    * proportions across all pattern elements, to the length of the pattern.
203    *
204    * @param counters observed counters
205    * @param pattern expected pattern
206    * @param maxIndividualVariance The most any counter can differ before we give up
207    * @return ratio of total variance between counters and pattern compared to total pattern size,
208    *  where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
209    *  the total variance between counters and patterns equals the pattern length, higher values mean
210    *  even more variance
211    */
212   static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
213     int numCounters = counters.length;
214     int total = 0;
215     int patternLength = 0;
216     for (int i = 0; i < numCounters; i++) {
217       total += counters[i];
218       patternLength += pattern[i];
219     }
220     if (total < patternLength) {
221       // If we don't even have one pixel per unit of bar width, assume this is too small
222       // to reliably match, so fail:
223       return Integer.MAX_VALUE;
224     }
225     // We're going to fake floating-point math in integers. We just need to use more bits.
226     // Scale up patternLength so that intermediate values below like scaledCounter will have
227     // more "significant digits"
228     int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
229     maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
230
231     int totalVariance = 0;
232     for (int x = 0; x < numCounters; x++) {
233       int counter = counters[x] << INTEGER_MATH_SHIFT;
234       int scaledPattern = pattern[x] * unitBarWidth;
235       int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
236       if (variance > maxIndividualVariance) {
237         return Integer.MAX_VALUE;
238       }
239       totalVariance += variance; 
240     }
241     return totalVariance / total;
242   }
243
244   // This declaration should not be necessary, since this class is
245   // abstract and so does not have to provide an implementation for every
246   // method of an interface it implements, but it is causing NoSuchMethodError
247   // issues on some Nokia JVMs. So we add this superfluous declaration:
248
249   public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
250       throws ReaderException;
251
252 }