2 * Copyright 2008 Google Inc.
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.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;
27 import java.util.Hashtable;
30 * <p>Encapsulates functionality and implementation that is common to all families
31 * of one-dimensional barcodes.</p>
33 * @author dswitkin@google.com (Daniel Switkin)
34 * @author srowen@google.com (Sean Owen)
36 public abstract class AbstractOneDReader implements OneDReader {
38 private static final int INTEGER_MATH_SHIFT = 8;
39 public static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 256;
41 public final Result decode(MonochromeBitmapSource image) throws ReaderException {
42 return decode(image, null);
45 public final Result decode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
46 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
48 return doDecode(image, hints, tryHarder);
49 } catch (ReaderException re) {
50 if (tryHarder && image.isRotateSupported()) {
51 MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise();
52 Result result = doDecode(rotatedImage, hints, tryHarder);
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 + ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
60 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
68 private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException {
70 int width = image.getWidth();
71 int height = image.getHeight();
73 BitArray row = new BitArray(width);
75 // We're going to examine rows from the middle outward, searching alternately above and below the middle,
76 // and farther out each time. rowStep is the number of rows between each successive attempt above and below
77 // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep,
78 // then middle - 2*rowStep, etc.
79 // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided
80 // that moving up and down by about 1/16 of the image is pretty good; we try more of the image if
82 int middle = height >> 1;
83 int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
86 maxLines = height; // Look at the whole image; looking for more than one barcode
91 for (int x = 0; x < maxLines; x++) {
93 // Scanning from the middle out. Determine which row we're looking at next:
94 int rowStepsAboveOrBelow = (x + 1) >> 1;
95 boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
96 int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
97 if (rowNumber < 0 || rowNumber >= height) {
98 // Oops, if we run off the top or bottom, stop
102 // Estimate black point for this row and load it:
104 image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
105 } catch (ReaderException re) {
108 image.getBlackRow(rowNumber, row, 0, width);
110 // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
111 // handle decoding upside down barcodes.
112 for (int attempt = 0; attempt < 2; attempt++) {
113 if (attempt == 1) { // trying again?
114 row.reverse(); // reverse the row and continue
117 // Look for a barcode
118 Result result = decodeRow(rowNumber, row, hints);
119 // We found our barcode
121 // But it was upside down, so note that
122 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
125 } catch (ReaderException re) {
126 // continue -- just couldn't decode this row
131 throw new ReaderException("No barcode found");
135 * Records the size of successive runs of white and black pixels in a row, starting at a given point.
136 * The values are recorded in the given array, and the number of runs recorded is equal to the size
137 * of the array. If the row starts on a white pixel at the given start point, then the first count
138 * recorded is the run of white pixels starting from that point; likewise it is the count of a run
139 * of black pixels if the row begin on a black pixels at that point.
141 * @param row row to count from
142 * @param start offset into row to start at
143 * @param counters array into which to record counts
144 * @throws ReaderException if counters cannot be filled entirely from row before running out of pixels
146 static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
147 int numCounters = counters.length;
148 for (int i = 0; i < numCounters; i++) {
151 int end = row.getSize();
153 throw new ReaderException("Couldn't fully read a pattern");
155 boolean isWhite = !row.get(start);
156 int counterPosition = 0;
159 boolean pixel = row.get(i);
160 if ((!pixel && isWhite) || (pixel && !isWhite)) {
161 counters[counterPosition]++;
164 if (counterPosition == numCounters) {
167 counters[counterPosition] = 1;
173 // If we read fully the last section of pixels and filled up our counters -- or filled
174 // the last counter but ran off the side of the image, OK. Otherwise, a problem.
175 if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
176 throw new ReaderException("Couldn't fully read a pattern");
181 * Determines how closely a set of observed counts of runs of black/white values matches a given
182 * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
183 * across all pattern elements, to the length of the pattern.
185 * @param counters observed counters
186 * @param pattern expected pattern
187 * @param maxIndividualVariance
188 * @return ratio of total variance between counters and pattern compared to total pattern size,
189 * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
190 * the total variance between counters and patterns equals the pattern length, higher values mean
193 static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
194 int numCounters = counters.length;
196 int patternLength = 0;
197 for (int i = 0; i < numCounters; i++) {
198 total += counters[i];
199 patternLength += pattern[i];
201 if (total < patternLength) {
202 // If we don't even have one pixel per unit of bar width, assume this is too small
203 // to reliably match, so fail:
204 return Integer.MAX_VALUE;
206 // We're going to fake floating-point math in integers. We just need to use more bits.
207 // Scale up patternLength so that intermediate values below like scaledCounter will have
208 // more "significant digits"
209 int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
210 maxIndividualVariance *= unitBarWidth;
212 int totalVariance = 0;
213 for (int x = 0; x < numCounters; x++) {
214 int counter = counters[x] << INTEGER_MATH_SHIFT;
215 int scaledPattern = pattern[x] * unitBarWidth;
216 int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
217 if (variance > maxIndividualVariance) {
218 return Integer.MAX_VALUE;
220 totalVariance += variance;
222 return totalVariance / total;
225 // This declaration should not be necessary, since this class is
226 // abstract and so does not have to provide an implementation for every
227 // method of an interface it implements, but it is causing NoSuchMethodError
228 // issues on some Nokia JVMs. So we add this superfluous declaration:
230 public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException;