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