Added BarcodeFormat to Result, indicating what type of barcode was detected. Added...
[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.common.BitArray;
25
26 import java.util.Hashtable;
27
28 /**
29  * <p>Encapsulates functionality and implementation that is common to all families
30  * of one-dimensional barcodes.</p>
31  *
32  * @author dswitkin@google.com (Daniel Switkin)
33  * @author srowen@google.com (Sean Owen)
34  */
35 public abstract class AbstractOneDReader implements OneDReader {
36
37   public final Result decode(MonochromeBitmapSource image) throws ReaderException {
38     return decode(image, null);
39   }
40
41   public final Result decode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException {
42
43     int width = image.getWidth();
44     int height = image.getHeight();
45
46     BitArray row = new BitArray(width);
47
48     // We're going to examine rows from the middle outward, searching alternately above and below the middle,
49     // and farther out each time. rowStep is the number of rows between each successive attempt above and below
50     // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep,
51     // then middle - 2*rowStep, etc.
52     // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided
53     // that moving up and down by about 1/16 of the image is pretty good.
54     int middle = height >> 1;
55     int rowStep = Math.max(1, height >> 4);
56     for (int x = 0; x < 7; x++) {
57
58       int rowStepsAboveOrBelow = (x + 1) >> 1;
59       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
60       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
61       if (rowNumber < 0 || rowNumber >= height) {
62         break;
63       }
64
65       image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
66       image.getBlackRow(rowNumber, row, 0, width);
67
68       try {
69         return decodeRow(rowNumber, row, hints);
70       } catch (ReaderException re) {
71         if (hints != null && hints.contains(DecodeHintType.TRY_HARDER)) {
72           row.reverse(); // try scanning the row backwards
73           try {
74             return decodeRow(rowNumber, row, hints);
75           } catch (ReaderException re2) {
76             // continue
77           }
78         }
79       }
80
81     }
82
83     throw new ReaderException("No barcode found");
84   }
85
86   protected static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
87     int numCounters = counters.length;
88     for (int i = 0; i < numCounters; i++) {
89       counters[i] = 0;
90     }
91     int end = row.getSize();
92     if (start >= end) {
93       throw new ReaderException("Couldn't fully read a pattern");
94     }
95     boolean isWhite = !row.get(start);
96     int counterPosition = 0;
97     int i = start;
98     while (i < end) {
99       boolean pixel = row.get(i);
100       if ((!pixel && isWhite) || (pixel && !isWhite)) {
101         counters[counterPosition]++;
102       } else {
103         counterPosition++;
104         if (counterPosition == numCounters) {
105           break;
106         } else {
107           counters[counterPosition] = 1;
108           isWhite = !isWhite;
109         }
110       }
111       i++;
112     }
113     // If we read fully the last section of pixels and filled up our counters -- or filled
114     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
115     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
116       throw new ReaderException("Couldn't fully read a pattern");
117     }
118   }
119
120   /**
121    * Determines how closely a set of observed counts of runs of black/white values matches a given
122    * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
123    * across all pattern elements, to the length of the pattern.
124    *
125    * @param counters observed counters
126    * @param pattern expected pattern
127    * @return average variance between counters and pattern
128    */
129   protected static float patternMatchVariance(int[] counters, int[] pattern) {
130     int total = 0;
131     int numCounters = counters.length;
132     int patternLength = 0;
133     for (int i = 0; i < numCounters; i++) {
134       total += counters[i];
135       patternLength += pattern[i];
136     }
137     float unitBarWidth = (float) total / (float) patternLength;
138
139     float totalVariance = 0.0f;
140     for (int x = 0; x < numCounters; x++) {
141       float scaledCounter = (float) counters[x] / unitBarWidth;
142       float width = pattern[x];
143       float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
144       totalVariance += abs;
145     }
146     return totalVariance / (float) patternLength;
147   }
148
149   /**
150    * Fast round method.
151    *
152    * @return argument rounded to nearest int
153    */
154   protected static int round(float f) {
155     return (int) (f + 0.5f);
156   }
157
158 }