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 public final Result decode(MonochromeBitmapSource image) throws ReaderException {
39 return decode(image, null);
42 public final Result decode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
43 boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
45 return doDecode(image, hints, tryHarder);
46 } catch (ReaderException re) {
47 if (tryHarder && image.isRotateSupported()) {
48 MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise();
49 Result result = doDecode(rotatedImage, hints, tryHarder);
50 // Record that we found it rotated 90 degrees CCW / 270 degrees CW
51 Hashtable metadata = result.getResultMetadata();
52 int orientation = 270;
53 if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) {
54 // But if we found it reversed in doDecode(), add in that result here:
55 orientation = (orientation + ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360;
57 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
65 private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException {
67 int width = image.getWidth();
68 int height = image.getHeight();
70 BitArray row = new BitArray(width);
72 // We're going to examine rows from the middle outward, searching alternately above and below the middle,
73 // and farther out each time. rowStep is the number of rows between each successive attempt above and below
74 // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep,
75 // then middle - 2*rowStep, etc.
76 // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided
77 // that moving up and down by about 1/16 of the image is pretty good; we try more of the image if
79 int middle = height >> 1;
80 int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
82 //if (tryHarder || barcodesToSkip > 0) {
84 maxLines = height; // Look at the whole image; looking for more than one barcode
89 Hashtable lastResults = null;
90 boolean skippingSomeBarcodes = hints != null && hints.containsKey(DecodeHintType.SKIP_N_BARCODES);
92 for (int x = 0; x < maxLines; x++) {
94 // Scanning from the middle out. Determine which row we're looking at next:
95 int rowStepsAboveOrBelow = (x + 1) >> 1;
96 boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
97 int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
98 if (rowNumber < 0 || rowNumber >= height) {
99 // Oops, if we run off the top or bottom, stop
103 // Estimate black point for this row and load it:
105 image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
106 } catch (ReaderException re) {
109 image.getBlackRow(rowNumber, row, 0, width);
111 // We may try twice for each row, if "trying harder":
112 for (int attempt = 0; attempt < 2; attempt++) {
114 if (attempt == 1) { // trying again?
115 if (tryHarder) { // only if "trying harder"
116 row.reverse(); // reverse the row and continue
124 // Look for a barcode
125 Result result = decodeRow(rowNumber, row, hints);
127 if (lastResults != null && lastResults.containsKey(result.getText())) {
128 // Just saw the last barcode again, proceed
132 if (skippingSomeBarcodes) { // See if we should skip and keep looking
133 int oldValue = ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue();
135 hints.put(DecodeHintType.SKIP_N_BARCODES, new Integer(oldValue - 1));
137 hints.remove(DecodeHintType.SKIP_N_BARCODES);
138 skippingSomeBarcodes = false;
140 if (lastResults == null) {
141 lastResults = new Hashtable(3);
143 lastResults.put(result.getText(), Boolean.TRUE); // Remember what we just saw
145 // We found our barcode
147 // But it was upside down, so note that
148 result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
153 } catch (ReaderException re) {
154 // continue -- just couldn't decode this row
160 throw new ReaderException("No barcode found");
163 static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
164 int numCounters = counters.length;
165 for (int i = 0; i < numCounters; i++) {
168 int end = row.getSize();
170 throw new ReaderException("Couldn't fully read a pattern");
172 boolean isWhite = !row.get(start);
173 int counterPosition = 0;
176 boolean pixel = row.get(i);
177 if ((!pixel && isWhite) || (pixel && !isWhite)) {
178 counters[counterPosition]++;
181 if (counterPosition == numCounters) {
184 counters[counterPosition] = 1;
190 // If we read fully the last section of pixels and filled up our counters -- or filled
191 // the last counter but ran off the side of the image, OK. Otherwise, a problem.
192 if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
193 throw new ReaderException("Couldn't fully read a pattern");
198 * Determines how closely a set of observed counts of runs of black/white values matches a given
199 * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
200 * across all pattern elements, to the length of the pattern.
202 * @param counters observed counters
203 * @param pattern expected pattern
204 * @return average variance between counters and pattern
206 static float patternMatchVariance(int[] counters, int[] pattern) {
208 int numCounters = counters.length;
209 int patternLength = 0;
210 for (int i = 0; i < numCounters; i++) {
211 total += counters[i];
212 patternLength += pattern[i];
214 float unitBarWidth = (float) total / (float) patternLength;
216 float totalVariance = 0.0f;
217 for (int x = 0; x < numCounters; x++) {
218 float scaledCounter = (float) counters[x] / unitBarWidth;
219 float width = pattern[x];
220 float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
221 totalVariance += abs;
223 return totalVariance / (float) patternLength;