- Added support for rotation in our blackbox test framework, and refactored the ways...
[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) {
83       maxLines = height; // Look at the whole image; looking for more than one barcode
84     } else {
85       maxLines = 7;
86     }
87
88     for (int x = 0; x < maxLines; x++) {
89
90       // Scanning from the middle out. Determine which row we're looking at next:
91       int rowStepsAboveOrBelow = (x + 1) >> 1;
92       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
93       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
94       if (rowNumber < 0 || rowNumber >= height) {
95         // Oops, if we run off the top or bottom, stop
96         break;
97       }
98
99       // Estimate black point for this row and load it:
100       try {
101         image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
102       } catch (ReaderException re) {
103         continue;
104       }
105       image.getBlackRow(rowNumber, row, 0, width);
106
107       // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
108       // handle decoding upside down barcodes.
109       for (int attempt = 0; attempt < 2; attempt++) {
110         if (attempt == 1) { // trying again?
111           row.reverse(); // reverse the row and continue
112         }
113         try {
114           // Look for a barcode
115           Result result = decodeRow(rowNumber, row, hints);
116           // We found our barcode
117           if (attempt == 1) {
118             // But it was upside down, so note that
119             result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
120           }
121           return result;
122         } catch (ReaderException re) {
123           // continue -- just couldn't decode this row
124         }
125       }
126     }
127
128     throw new ReaderException("No barcode found");
129   }
130
131   /**
132    * Records the size of successive runs of white and black pixels in a row, starting at a given point.
133    * The values are recorded in the given array, and the number of runs recorded is equal to the size
134    * of the array. If the row starts on a white pixel at the given start point, then the first count
135    * recorded is the run of white pixels starting from that point; likewise it is the count of a run
136    * of black pixels if the row begin on a black pixels at that point.
137    *
138    * @param row row to count from
139    * @param start offset into row to start at
140    * @param counters array into which to record counts
141    * @throws ReaderException if counters cannot be filled entirely from row before running out of pixels
142    */
143   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
144     int numCounters = counters.length;
145     for (int i = 0; i < numCounters; i++) {
146       counters[i] = 0;
147     }
148     int end = row.getSize();
149     if (start >= end) {
150       throw new ReaderException("Couldn't fully read a pattern");
151     }
152     boolean isWhite = !row.get(start);
153     int counterPosition = 0;
154     int i = start;
155     while (i < end) {
156       boolean pixel = row.get(i);
157       if ((!pixel && isWhite) || (pixel && !isWhite)) {
158         counters[counterPosition]++;
159       } else {
160         counterPosition++;
161         if (counterPosition == numCounters) {
162           break;
163         } else {
164           counters[counterPosition] = 1;
165           isWhite = !isWhite;
166         }
167       }
168       i++;
169     }
170     // If we read fully the last section of pixels and filled up our counters -- or filled
171     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
172     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
173       throw new ReaderException("Couldn't fully read a pattern");
174     }
175   }
176
177   /**
178    * Determines how closely a set of observed counts of runs of black/white values matches a given
179    * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
180    * across all pattern elements, to the length of the pattern.
181    *
182    * @param counters observed counters
183    * @param pattern expected pattern
184    * @return average variance between counters and pattern
185    */
186   static float patternMatchVariance(int[] counters, int[] pattern) {
187     int total = 0;
188     int numCounters = counters.length;
189     int patternLength = 0;
190     for (int i = 0; i < numCounters; i++) {
191       total += counters[i];
192       patternLength += pattern[i];
193     }
194     float unitBarWidth = (float) total / (float) patternLength;
195
196     float totalVariance = 0.0f;
197     for (int x = 0; x < numCounters; x++) {
198       float scaledCounter = (float) counters[x] / unitBarWidth;
199       float width = pattern[x];
200       float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
201       totalVariance += abs;
202     }
203     return totalVariance / (float) patternLength;
204   }
205
206   // This declaration should not be necessary, since this class is
207   // abstract and so does not have to provide an implementation for every
208   // method of an interface it implements, but it is causing NoSuchMethodError
209   // issues on some Nokia JVMs. So we add this superfluous declaration:
210
211   public abstract Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException;
212
213 }