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.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.ResultPoint;
26 import com.google.zxing.common.BitArray;
27 import com.google.zxing.common.GenericResultPoint;
29 import java.util.Hashtable;
32 * <p>Encapsulates functionality and implementation that is common to all families
33 * of one-dimensional barcodes.</p>
35 * @author dswitkin@google.com (Daniel Switkin)
38 public abstract class AbstractOneDReader implements OneDReader {
40 private static final int INTEGER_MATH_SHIFT = 8;
41 static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
43 public final Result decode(MonochromeBitmapSource image) throws ReaderException {
44 return decode(image, null);
47 public final Result decode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
49 return doDecode(image, hints);
50 } catch (ReaderException re) {
51 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
52 if (tryHarder && image.isRotateSupported()) {
53 MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise();
54 Result result = doDecode(rotatedImage, hints);
55 // Record that we found it rotated 90 degrees CCW / 270 degrees CW
56 Hashtable metadata = result.getResultMetadata();
57 int orientation = 270;
58 if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
59 // But if we found it reversed in doDecode(), add in that result here:
60 orientation = (orientation + ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
62 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
71 * We're going to examine rows from the middle outward, searching alternately above and below the
72 * middle, and farther out each time. rowStep is the number of rows between each successive
73 * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
74 * middle + rowStep, then middle - (2 * rowStep), etc.
75 * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
76 * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
77 * image if "trying harder".
79 * @param image The image to decode
80 * @param hints Any hints that were requested
81 * @return The contents of the decoded barcode
82 * @throws ReaderException Any spontaneous errors which occur
84 private Result doDecode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
85 int width = image.getWidth();
86 int height = image.getHeight();
87 BitArray row = new BitArray(width);
89 int middle = height >> 1;
90 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
91 int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
94 maxLines = height; // Look at the whole image, not just the center
96 maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
99 for (int x = 0; x < maxLines; x++) {
101 // Scanning from the middle out. Determine which row we're looking at next:
102 int rowStepsAboveOrBelow = (x + 1) >> 1;
103 boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
104 int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
105 if (rowNumber < 0 || rowNumber >= height) {
106 // Oops, if we run off the top or bottom, stop
110 // Estimate black point for this row and load it:
112 image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
113 } catch (ReaderException re) {
116 image.getBlackRow(rowNumber, row, 0, width);
118 // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
119 // handle decoding upside down barcodes.
120 for (int attempt = 0; attempt < 2; attempt++) {
121 if (attempt == 1) { // trying again?
122 row.reverse(); // reverse the row and continue
125 // Look for a barcode
126 Result result = decodeRow(rowNumber, row, hints);
127 // We found our barcode
129 // But it was upside down, so note that
130 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
131 // And remember to flip the result points horizontally.
132 ResultPoint[] points = result.getResultPoints();
133 points[0] = new GenericResultPoint(width - points[0].getX() - 1, points[0].getY());
134 points[1] = new GenericResultPoint(width - points[1].getX() - 1, points[1].getY());
137 } catch (ReaderException re) {
138 // continue -- just couldn't decode this row
143 throw ReaderException.getInstance();
147 * Records the size of successive runs of white and black pixels in a row, starting at a given point.
148 * The values are recorded in the given array, and the number of runs recorded is equal to the size
149 * of the array. If the row starts on a white pixel at the given start point, then the first count
150 * recorded is the run of white pixels starting from that point; likewise it is the count of a run
151 * of black pixels if the row begin on a black pixels at that point.
153 * @param row row to count from
154 * @param start offset into row to start at
155 * @param counters array into which to record counts
156 * @throws ReaderException if counters cannot be filled entirely from row before running out of pixels
158 static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
159 int numCounters = counters.length;
160 for (int i = 0; i < numCounters; i++) {
163 int end = row.getSize();
165 throw ReaderException.getInstance();
167 boolean isWhite = !row.get(start);
168 int counterPosition = 0;
171 boolean pixel = row.get(i);
172 if ((!pixel && isWhite) || (pixel && !isWhite)) {
173 counters[counterPosition]++;
176 if (counterPosition == numCounters) {
179 counters[counterPosition] = 1;
185 // If we read fully the last section of pixels and filled up our counters -- or filled
186 // the last counter but ran off the side of the image, OK. Otherwise, a problem.
187 if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
188 throw ReaderException.getInstance();
193 * Determines how closely a set of observed counts of runs of black/white values matches a given
194 * target pattern. This is reported as the ratio of the total variance from the expected pattern
195 * proportions across all pattern elements, to the length of the pattern.
197 * @param counters observed counters
198 * @param pattern expected pattern
199 * @param maxIndividualVariance The most any counter can differ before we give up
200 * @return ratio of total variance between counters and pattern compared to total pattern size,
201 * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
202 * the total variance between counters and patterns equals the pattern length, higher values mean
205 static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
206 int numCounters = counters.length;
208 int patternLength = 0;
209 for (int i = 0; i < numCounters; i++) {
210 total += counters[i];
211 patternLength += pattern[i];
213 if (total < patternLength) {
214 // If we don't even have one pixel per unit of bar width, assume this is too small
215 // to reliably match, so fail:
216 return Integer.MAX_VALUE;
218 // We're going to fake floating-point math in integers. We just need to use more bits.
219 // Scale up patternLength so that intermediate values below like scaledCounter will have
220 // more "significant digits"
221 int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
222 maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
224 int totalVariance = 0;
225 for (int x = 0; x < numCounters; x++) {
226 int counter = counters[x] << INTEGER_MATH_SHIFT;
227 int scaledPattern = pattern[x] * unitBarWidth;
228 int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
229 if (variance > maxIndividualVariance) {
230 return Integer.MAX_VALUE;
232 totalVariance += variance;
234 return totalVariance / total;
237 // This declaration should not be necessary, since this class is
238 // abstract and so does not have to provide an implementation for every
239 // method of an interface it implements, but it is causing NoSuchMethodError
240 // issues on some Nokia JVMs. So we add this superfluous declaration:
242 public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException;