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