Another fix to ensure that 2 barcodes with the same info are counted separately.
[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     // Remember last barcode to avoid thinking we've found a new barcode when
90     // we just rescanned the last one. Actually remember two, the last one
91     // found above and below.
92     String lastResultAboveText = null;
93     String lastResultBelowText = null;
94     boolean skippingSomeBarcodes =
95       hints != null &&
96       hints.containsKey(DecodeHintType.SKIP_N_BARCODES) &&
97       ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue() > 0;
98
99     for (int x = 0; x < maxLines; x++) {
100
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
107         break;
108       }
109
110       // Estimate black point for this row and load it:
111       try {
112         image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
113       } catch (ReaderException re) {
114         continue;
115       }
116       image.getBlackRow(rowNumber, row, 0, width);
117
118       // We may try twice for each row, if "trying harder":
119       for (int attempt = 0; attempt < 2; attempt++) {
120
121         if (attempt == 1) { // trying again?
122           if (tryHarder) { // only if "trying harder"
123             row.reverse(); // reverse the row and continue
124           } else {
125             break;
126           }
127         }
128
129         try {
130
131           // Look for a barcode
132           Result result = decodeRow(rowNumber, row, hints);
133           String resultText = result.getText();
134
135           // make sure we terminate inner loop after this because we found something
136           attempt = 1;
137           // See if we should skip and keep looking
138           if (( isAbove && resultText.equals(lastResultAboveText)) ||
139               (!isAbove && resultText.equals(lastResultBelowText))) {
140             // Just saw the last barcode again, proceed
141             continue;
142           }
143
144           if (skippingSomeBarcodes) {
145             int oldValue = ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue();
146             if (oldValue > 1) {
147               hints.put(DecodeHintType.SKIP_N_BARCODES, new Integer(oldValue - 1));
148             } else {
149               hints.remove(DecodeHintType.SKIP_N_BARCODES);
150               skippingSomeBarcodes = false;
151             }
152             if (isAbove) {
153               lastResultAboveText = resultText;
154             } else {
155               lastResultBelowText = resultText;
156             }
157           } else {
158             // We found our barcode
159             if (attempt == 1) {
160               // But it was upside down, so note that
161               result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
162             }
163             return result;
164           }
165
166         } catch (ReaderException re) {
167           // continue -- just couldn't decode this row
168           if (skippingSomeBarcodes) {
169             if (isAbove) {
170               lastResultAboveText = null;
171             } else {
172               lastResultBelowText = null;
173             }
174           }
175         }
176
177       }
178     }
179
180     throw new ReaderException("No barcode found");
181   }
182
183   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
184     int numCounters = counters.length;
185     for (int i = 0; i < numCounters; i++) {
186       counters[i] = 0;
187     }
188     int end = row.getSize();
189     if (start >= end) {
190       throw new ReaderException("Couldn't fully read a pattern");
191     }
192     boolean isWhite = !row.get(start);
193     int counterPosition = 0;
194     int i = start;
195     while (i < end) {
196       boolean pixel = row.get(i);
197       if ((!pixel && isWhite) || (pixel && !isWhite)) {
198         counters[counterPosition]++;
199       } else {
200         counterPosition++;
201         if (counterPosition == numCounters) {
202           break;
203         } else {
204           counters[counterPosition] = 1;
205           isWhite = !isWhite;
206         }
207       }
208       i++;
209     }
210     // If we read fully the last section of pixels and filled up our counters -- or filled
211     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
212     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
213       throw new ReaderException("Couldn't fully read a pattern");
214     }
215   }
216
217   /**
218    * Determines how closely a set of observed counts of runs of black/white values matches a given
219    * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
220    * across all pattern elements, to the length of the pattern.
221    *
222    * @param counters observed counters
223    * @param pattern expected pattern
224    * @return average variance between counters and pattern
225    */
226   static float patternMatchVariance(int[] counters, int[] pattern) {
227     int total = 0;
228     int numCounters = counters.length;
229     int patternLength = 0;
230     for (int i = 0; i < numCounters; i++) {
231       total += counters[i];
232       patternLength += pattern[i];
233     }
234     float unitBarWidth = (float) total / (float) patternLength;
235
236     float totalVariance = 0.0f;
237     for (int x = 0; x < numCounters; x++) {
238       float scaledCounter = (float) counters[x] / unitBarWidth;
239       float width = pattern[x];
240       float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
241       totalVariance += abs;
242     }
243     return totalVariance / (float) patternLength;
244   }
245
246 }