2 * Copyright 2008 ZXing authors
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.google.zxing.oned;
19 import com.google.zxing.BinaryBitmap;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.Reader;
22 import com.google.zxing.ReaderException;
23 import com.google.zxing.Result;
24 import com.google.zxing.ResultMetadataType;
25 import com.google.zxing.ResultPoint;
26 import com.google.zxing.common.BitArray;
28 import java.util.Enumeration;
29 import java.util.Hashtable;
32 * Encapsulates functionality and implementation that is common to all families
33 * of one-dimensional barcodes.
35 * @author dswitkin@google.com (Daniel Switkin)
38 public abstract class OneDReader implements Reader {
40 private static final int INTEGER_MATH_SHIFT = 8;
41 protected static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
43 public Result decode(BinaryBitmap image) throws ReaderException {
44 return decode(image, null);
47 // Note that we don't try rotation without the try harder flag, even if rotation was supported.
48 public Result decode(BinaryBitmap image, Hashtable hints) throws ReaderException {
50 return doDecode(image, hints);
51 } catch (ReaderException re) {
52 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
53 if (tryHarder && image.isRotateSupported()) {
54 BinaryBitmap rotatedImage = image.rotateCounterClockwise();
55 Result result = doDecode(rotatedImage, hints);
56 // Record that we found it rotated 90 degrees CCW / 270 degrees CW
57 Hashtable metadata = result.getResultMetadata();
58 int orientation = 270;
59 if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
60 // But if we found it reversed in doDecode(), add in that result here:
61 orientation = (orientation +
62 ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
64 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
65 // Update result points
66 ResultPoint[] points = result.getResultPoints();
67 int height = rotatedImage.getHeight();
68 for (int i = 0; i < points.length; i++) {
69 points[i] = new ResultPoint(height - points[i].getY() - 1, points[i].getX());
83 * We're going to examine rows from the middle outward, searching alternately above and below the
84 * middle, and farther out each time. rowStep is the number of rows between each successive
85 * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
86 * middle + rowStep, then middle - (2 * rowStep), etc.
87 * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
88 * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
89 * image if "trying harder".
91 * @param image The image to decode
92 * @param hints Any hints that were requested
93 * @return The contents of the decoded barcode
94 * @throws ReaderException Any spontaneous errors which occur
96 private Result doDecode(BinaryBitmap image, Hashtable hints) throws ReaderException {
97 int width = image.getWidth();
98 int height = image.getHeight();
99 BitArray row = new BitArray(width);
101 int middle = height >> 1;
102 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
103 int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
106 maxLines = height; // Look at the whole image, not just the center
108 maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
111 for (int x = 0; x < maxLines; x++) {
113 // Scanning from the middle out. Determine which row we're looking at next:
114 int rowStepsAboveOrBelow = (x + 1) >> 1;
115 boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
116 int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
117 if (rowNumber < 0 || rowNumber >= height) {
118 // Oops, if we run off the top or bottom, stop
122 // Estimate black point for this row and load it:
124 row = image.getBlackRow(rowNumber, row);
125 } catch (ReaderException re) {
129 // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
130 // handle decoding upside down barcodes.
131 for (int attempt = 0; attempt < 2; attempt++) {
132 if (attempt == 1) { // trying again?
133 row.reverse(); // reverse the row and continue
134 // This means we will only ever draw result points *once* in the life of this method
135 // since we want to avoid drawing the wrong points after flipping the row, and,
136 // don't want to clutter with noise from every single row scan -- just the scans
137 // that start on the center line.
138 if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
139 Hashtable newHints = new Hashtable(); // Can't use clone() in J2ME
140 Enumeration hintEnum = hints.keys();
141 while (hintEnum.hasMoreElements()) {
142 Object key = hintEnum.nextElement();
143 if (!key.equals(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
144 newHints.put(key, hints.get(key));
151 // Look for a barcode
152 Result result = decodeRow(rowNumber, row, hints);
153 // We found our barcode
155 // But it was upside down, so note that
156 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
157 // And remember to flip the result points horizontally.
158 ResultPoint[] points = result.getResultPoints();
159 points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
160 points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
163 } catch (ReaderException re) {
164 // continue -- just couldn't decode this row
169 throw ReaderException.getInstance();
173 * Records the size of successive runs of white and black pixels in a row, starting at a given point.
174 * The values are recorded in the given array, and the number of runs recorded is equal to the size
175 * of the array. If the row starts on a white pixel at the given start point, then the first count
176 * recorded is the run of white pixels starting from that point; likewise it is the count of a run
177 * of black pixels if the row begin on a black pixels at that point.
179 * @param row row to count from
180 * @param start offset into row to start at
181 * @param counters array into which to record counts
182 * @throws ReaderException if counters cannot be filled entirely from row before running out
185 protected static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
186 int numCounters = counters.length;
187 for (int i = 0; i < numCounters; i++) {
190 int end = row.getSize();
192 throw ReaderException.getInstance();
194 boolean isWhite = !row.get(start);
195 int counterPosition = 0;
198 boolean pixel = row.get(i);
199 if (pixel ^ isWhite) { // that is, exactly one is true
200 counters[counterPosition]++;
203 if (counterPosition == numCounters) {
206 counters[counterPosition] = 1;
212 // If we read fully the last section of pixels and filled up our counters -- or filled
213 // the last counter but ran off the side of the image, OK. Otherwise, a problem.
214 if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
215 throw ReaderException.getInstance();
219 protected static void recordPatternInReverse(BitArray row, int start, int[] counters)
220 throws ReaderException {
221 // This could be more efficient I guess
222 int numTransitionsLeft = counters.length;
223 boolean last = row.get(start);
224 while (start > 0 && numTransitionsLeft >= 0) {
225 if (row.get(--start) != last) {
226 numTransitionsLeft--;
230 if (numTransitionsLeft >= 0) {
231 throw ReaderException.getInstance();
233 recordPattern(row, start + 1, counters);
237 * Determines how closely a set of observed counts of runs of black/white values matches a given
238 * target pattern. This is reported as the ratio of the total variance from the expected pattern
239 * proportions across all pattern elements, to the length of the pattern.
241 * @param counters observed counters
242 * @param pattern expected pattern
243 * @param maxIndividualVariance The most any counter can differ before we give up
244 * @return ratio of total variance between counters and pattern compared to total pattern size,
245 * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
246 * the total variance between counters and patterns equals the pattern length, higher values mean
249 protected static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
250 int numCounters = counters.length;
252 int patternLength = 0;
253 for (int i = 0; i < numCounters; i++) {
254 total += counters[i];
255 patternLength += pattern[i];
257 if (total < patternLength) {
258 // If we don't even have one pixel per unit of bar width, assume this is too small
259 // to reliably match, so fail:
260 return Integer.MAX_VALUE;
262 // We're going to fake floating-point math in integers. We just need to use more bits.
263 // Scale up patternLength so that intermediate values below like scaledCounter will have
264 // more "significant digits"
265 int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
266 maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
268 int totalVariance = 0;
269 for (int x = 0; x < numCounters; x++) {
270 int counter = counters[x] << INTEGER_MATH_SHIFT;
271 int scaledPattern = pattern[x] * unitBarWidth;
272 int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
273 if (variance > maxIndividualVariance) {
274 return Integer.MAX_VALUE;
276 totalVariance += variance;
278 return totalVariance / total;
282 * <p>Attempts to decode a one-dimensional barcode format given a single row of
285 * @param rowNumber row number from top of the row
286 * @param row the black/white pixel data of the row
287 * @param hints decode hints
288 * @return {@link Result} containing encoded string and start/end of barcode
289 * @throws ReaderException if an error occurs or barcode cannot be found
291 public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
292 throws ReaderException;