"Skip 0 barcodes" was incorrectly not returning the first barcode found
[zxing.git] / core / src / com / google / zxing / oned / AbstractOneDReader.java
1 /*
2  * Copyright 2008 Google Inc.
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.oned;
18
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;
26
27 import java.util.Hashtable;
28
29 /**
30  * <p>Encapsulates functionality and implementation that is common to all families
31  * of one-dimensional barcodes.</p>
32  *
33  * @author dswitkin@google.com (Daniel Switkin)
34  * @author srowen@google.com (Sean Owen)
35  */
36 public abstract class AbstractOneDReader implements OneDReader {
37
38   public final Result decode(MonochromeBitmapSource image) throws ReaderException {
39     return decode(image, null);
40   }
41
42   public final Result decode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
43     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
44     try {
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;
56         }
57         result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation));
58         return result;
59       } else {
60         throw re;
61       }
62     }
63   }
64
65   private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException {
66
67     int width = image.getWidth();
68     int height = image.getHeight();
69
70     BitArray row = new BitArray(width);
71
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
78     // "trying harder"
79     int middle = height >> 1;
80     int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4));
81     int maxLines;
82     //if (tryHarder || barcodesToSkip > 0) {
83     if (tryHarder) {
84       maxLines = height; // Look at the whole image; looking for more than one barcode
85     } else {
86       maxLines = 7;
87     }
88
89     Hashtable lastResults = null;
90     boolean skippingSomeBarcodes =
91       hints != null &&
92       hints.containsKey(DecodeHintType.SKIP_N_BARCODES) &&
93       ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue() > 0;
94
95     for (int x = 0; x < maxLines; x++) {
96
97       // Scanning from the middle out. Determine which row we're looking at next:
98       int rowStepsAboveOrBelow = (x + 1) >> 1;
99       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
100       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
101       if (rowNumber < 0 || rowNumber >= height) {
102         // Oops, if we run off the top or bottom, stop
103         break;
104       }
105
106       // Estimate black point for this row and load it:
107       try {
108         image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
109       } catch (ReaderException re) {
110         continue;
111       }
112       image.getBlackRow(rowNumber, row, 0, width);
113
114       // We may try twice for each row, if "trying harder":
115       for (int attempt = 0; attempt < 2; attempt++) {
116
117         if (attempt == 1) { // trying again?
118           if (tryHarder) { // only if "trying harder"
119             row.reverse(); // reverse the row and continue
120           } else {
121             break;
122           }
123         }
124
125         try {
126
127           // Look for a barcode
128           Result result = decodeRow(rowNumber, row, hints);
129
130           if (lastResults != null && lastResults.containsKey(result.getText())) {
131             // Just saw the last barcode again, proceed
132             continue;
133           }
134
135           if (skippingSomeBarcodes) { // See if we should skip and keep looking
136             int oldValue = ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue();
137             if (oldValue > 1) {
138               hints.put(DecodeHintType.SKIP_N_BARCODES, new Integer(oldValue - 1));
139             } else {
140               hints.remove(DecodeHintType.SKIP_N_BARCODES);
141               skippingSomeBarcodes = false;
142             }
143             if (lastResults == null) {
144               lastResults = new Hashtable(3);
145             }
146             lastResults.put(result.getText(), Boolean.TRUE); // Remember what we just saw
147           } else {
148             // We found our barcode
149             if (attempt == 1) {
150               // But it was upside down, so note that
151               result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
152             }
153             return result;
154           }
155
156         } catch (ReaderException re) {
157           // continue -- just couldn't decode this row
158         }
159
160       }
161     }
162
163     throw new ReaderException("No barcode found");
164   }
165
166   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
167     int numCounters = counters.length;
168     for (int i = 0; i < numCounters; i++) {
169       counters[i] = 0;
170     }
171     int end = row.getSize();
172     if (start >= end) {
173       throw new ReaderException("Couldn't fully read a pattern");
174     }
175     boolean isWhite = !row.get(start);
176     int counterPosition = 0;
177     int i = start;
178     while (i < end) {
179       boolean pixel = row.get(i);
180       if ((!pixel && isWhite) || (pixel && !isWhite)) {
181         counters[counterPosition]++;
182       } else {
183         counterPosition++;
184         if (counterPosition == numCounters) {
185           break;
186         } else {
187           counters[counterPosition] = 1;
188           isWhite = !isWhite;
189         }
190       }
191       i++;
192     }
193     // If we read fully the last section of pixels and filled up our counters -- or filled
194     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
195     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
196       throw new ReaderException("Couldn't fully read a pattern");
197     }
198   }
199
200   /**
201    * Determines how closely a set of observed counts of runs of black/white values matches a given
202    * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
203    * across all pattern elements, to the length of the pattern.
204    *
205    * @param counters observed counters
206    * @param pattern expected pattern
207    * @return average variance between counters and pattern
208    */
209   static float patternMatchVariance(int[] counters, int[] pattern) {
210     int total = 0;
211     int numCounters = counters.length;
212     int patternLength = 0;
213     for (int i = 0; i < numCounters; i++) {
214       total += counters[i];
215       patternLength += pattern[i];
216     }
217     float unitBarWidth = (float) total / (float) patternLength;
218
219     float totalVariance = 0.0f;
220     for (int x = 0; x < numCounters; x++) {
221       float scaledCounter = (float) counters[x] / unitBarWidth;
222       float width = pattern[x];
223       float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
224       totalVariance += abs;
225     }
226     return totalVariance / (float) patternLength;
227   }
228
229 }