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.Hashtable;
31 * Encapsulates functionality and implementation that is common to all families
32 * of one-dimensional barcodes.
34 * @author dswitkin@google.com (Daniel Switkin)
37 public abstract class OneDReader implements Reader {
39 private static final int INTEGER_MATH_SHIFT = 8;
40 static final int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
42 public Result decode(BinaryBitmap image) throws ReaderException {
43 return decode(image, null);
46 // Note that we don't try rotation without the try harder flag, even if rotation was supported.
47 public Result decode(BinaryBitmap 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 BinaryBitmap 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 +
61 ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
63 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
72 * We're going to examine rows from the middle outward, searching alternately above and below the
73 * middle, and farther out each time. rowStep is the number of rows between each successive
74 * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
75 * middle + rowStep, then middle - (2 * rowStep), etc.
76 * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
77 * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
78 * image if "trying harder".
80 * @param image The image to decode
81 * @param hints Any hints that were requested
82 * @return The contents of the decoded barcode
83 * @throws ReaderException Any spontaneous errors which occur
85 private Result doDecode(BinaryBitmap image, Hashtable hints) throws ReaderException {
86 int width = image.getWidth();
87 int height = image.getHeight();
88 BitArray row = new BitArray(width);
90 int middle = height >> 1;
91 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
92 int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
95 maxLines = height; // Look at the whole image, not just the center
97 maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
100 for (int x = 0; x < maxLines; x++) {
102 // Scanning from the middle out. Determine which row we're looking at next:
103 int rowStepsAboveOrBelow = (x + 1) >> 1;
104 boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
105 int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
106 if (rowNumber < 0 || rowNumber >= height) {
107 // Oops, if we run off the top or bottom, stop
111 // Estimate black point for this row and load it:
113 row = image.getBlackRow(rowNumber, row);
114 } catch (ReaderException re) {
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
123 // This means we will only ever draw result points *once* in the life of this method
124 // since we want to avoid drawing the wrong points after flipping the row, and,
125 // don't want to clutter with noise from every single row scan -- just the scans
126 // that start on the center line.
127 if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
128 hints = (Hashtable) hints.clone();
129 hints.remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
133 // Look for a barcode
134 Result result = decodeRow(rowNumber, row, hints);
135 // We found our barcode
137 // But it was upside down, so note that
138 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
139 // And remember to flip the result points horizontally.
140 ResultPoint[] points = result.getResultPoints();
141 points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
142 points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
145 } catch (ReaderException re) {
146 // continue -- just couldn't decode this row
151 throw ReaderException.getInstance();
155 * Records the size of successive runs of white and black pixels in a row, starting at a given point.
156 * The values are recorded in the given array, and the number of runs recorded is equal to the size
157 * of the array. If the row starts on a white pixel at the given start point, then the first count
158 * recorded is the run of white pixels starting from that point; likewise it is the count of a run
159 * of black pixels if the row begin on a black pixels at that point.
161 * @param row row to count from
162 * @param start offset into row to start at
163 * @param counters array into which to record counts
164 * @throws ReaderException if counters cannot be filled entirely from row before running out
167 static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
168 int numCounters = counters.length;
169 for (int i = 0; i < numCounters; i++) {
172 int end = row.getSize();
174 throw ReaderException.getInstance();
176 boolean isWhite = !row.get(start);
177 int counterPosition = 0;
180 boolean pixel = row.get(i);
181 if (pixel ^ isWhite) { // that is, exactly one is true
182 counters[counterPosition]++;
185 if (counterPosition == numCounters) {
188 counters[counterPosition] = 1;
194 // If we read fully the last section of pixels and filled up our counters -- or filled
195 // the last counter but ran off the side of the image, OK. Otherwise, a problem.
196 if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
197 throw ReaderException.getInstance();
202 * Determines how closely a set of observed counts of runs of black/white values matches a given
203 * target pattern. This is reported as the ratio of the total variance from the expected pattern
204 * proportions across all pattern elements, to the length of the pattern.
206 * @param counters observed counters
207 * @param pattern expected pattern
208 * @param maxIndividualVariance The most any counter can differ before we give up
209 * @return ratio of total variance between counters and pattern compared to total pattern size,
210 * where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
211 * the total variance between counters and patterns equals the pattern length, higher values mean
214 static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance) {
215 int numCounters = counters.length;
217 int patternLength = 0;
218 for (int i = 0; i < numCounters; i++) {
219 total += counters[i];
220 patternLength += pattern[i];
222 if (total < patternLength) {
223 // If we don't even have one pixel per unit of bar width, assume this is too small
224 // to reliably match, so fail:
225 return Integer.MAX_VALUE;
227 // We're going to fake floating-point math in integers. We just need to use more bits.
228 // Scale up patternLength so that intermediate values below like scaledCounter will have
229 // more "significant digits"
230 int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
231 maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
233 int totalVariance = 0;
234 for (int x = 0; x < numCounters; x++) {
235 int counter = counters[x] << INTEGER_MATH_SHIFT;
236 int scaledPattern = pattern[x] * unitBarWidth;
237 int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
238 if (variance > maxIndividualVariance) {
239 return Integer.MAX_VALUE;
241 totalVariance += variance;
243 return totalVariance / total;
247 * <p>Attempts to decode a one-dimensional barcode format given a single row of
250 * @param rowNumber row number from top of the row
251 * @param row the black/white pixel data of the row
252 * @param hints decode hints
253 * @return {@link Result} containing encoded string and start/end of barcode
254 * @throws ReaderException if an error occurs or barcode cannot be found
256 public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints)
257 throws ReaderException;