"Try harder" now examines a lot more lines in the image
[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     int barcodesToSkip = 0;
73     if (hints != null) {
74       Integer number = (Integer) hints.get(DecodeHintType.SKIP_N_BARCODES);
75       if (number != null) {
76         barcodesToSkip = number.intValue();
77       }
78     }
79
80     // We're going to examine rows from the middle outward, searching alternately above and below the middle,
81     // and farther out each time. rowStep is the number of rows between each successive attempt above and below
82     // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep,
83     // then middle - 2*rowStep, etc.
84     // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided
85     // that moving up and down by about 1/16 of the image is pretty good.
86     int middle = height >> 1;
87     int rowStep;
88     if (tryHarder) {
89       rowStep = 2; // Look at every other line if "trying harder"
90     } else {
91       rowStep = Math.max(1, height >> 4);
92     }
93     int maxLines;
94     if (tryHarder || barcodesToSkip > 0) {
95       maxLines = height; // Look at the whole image; looking for more than one barcode
96     } else {
97       maxLines = 7;
98     }
99     for (int x = 0; x < maxLines; x++) {
100
101       int rowStepsAboveOrBelow = (x + 1) >> 1;
102       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
103       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
104       if (rowNumber < 0 || rowNumber >= height) {
105         break;
106       }
107
108       image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
109       image.getBlackRow(rowNumber, row, 0, width);
110
111       try {
112         Result result = decodeRow(rowNumber, row, hints);
113         if (barcodesToSkip > 0) { // See if we should skip and keep looking
114           barcodesToSkip--;
115         } else {
116           return result;
117         }
118       } catch (ReaderException re) {
119         if (tryHarder) {
120           row.reverse(); // try scanning the row backwards
121           try {
122             Result result = decodeRow(rowNumber, row, hints);
123             if (barcodesToSkip > 0) { // See if we should skip and keep looking
124               barcodesToSkip--;
125             } else {
126               // Found it, but upside-down:
127               result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180));
128               return result;
129             }
130           } catch (ReaderException re2) {
131             // continue
132           }
133         }
134       }
135
136     }
137
138     throw new ReaderException("No barcode found");
139   }
140
141   static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
142     int numCounters = counters.length;
143     for (int i = 0; i < numCounters; i++) {
144       counters[i] = 0;
145     }
146     int end = row.getSize();
147     if (start >= end) {
148       throw new ReaderException("Couldn't fully read a pattern");
149     }
150     boolean isWhite = !row.get(start);
151     int counterPosition = 0;
152     int i = start;
153     while (i < end) {
154       boolean pixel = row.get(i);
155       if ((!pixel && isWhite) || (pixel && !isWhite)) {
156         counters[counterPosition]++;
157       } else {
158         counterPosition++;
159         if (counterPosition == numCounters) {
160           break;
161         } else {
162           counters[counterPosition] = 1;
163           isWhite = !isWhite;
164         }
165       }
166       i++;
167     }
168     // If we read fully the last section of pixels and filled up our counters -- or filled
169     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
170     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
171       throw new ReaderException("Couldn't fully read a pattern");
172     }
173   }
174
175   /**
176    * Determines how closely a set of observed counts of runs of black/white values matches a given
177    * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
178    * across all pattern elements, to the length of the pattern.
179    *
180    * @param counters observed counters
181    * @param pattern expected pattern
182    * @return average variance between counters and pattern
183    */
184   static float patternMatchVariance(int[] counters, int[] pattern) {
185     int total = 0;
186     int numCounters = counters.length;
187     int patternLength = 0;
188     for (int i = 0; i < numCounters; i++) {
189       total += counters[i];
190       patternLength += pattern[i];
191     }
192     float unitBarWidth = (float) total / (float) patternLength;
193
194     float totalVariance = 0.0f;
195     for (int x = 0; x < numCounters; x++) {
196       float scaledCounter = (float) counters[x] / unitBarWidth;
197       float width = pattern[x];
198       float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
199       totalVariance += abs;
200     }
201     return totalVariance / (float) patternLength;
202   }
203
204 }