Use TRY_HARDER hint in javase CommandLineRunner. TRY_HARDER now tries rotating the...
[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     boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
43     try {
44       return doDecode(image, hints, tryHarder);
45     } catch (ReaderException re) {
46       if (tryHarder && image.isRotatedSupported()) {
47         MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise();
48         return doDecode(rotatedImage, hints, tryHarder);        
49       } else {
50         throw re;
51       }
52     }
53   }
54
55   private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException {
56
57     int width = image.getWidth();
58     int height = image.getHeight();
59
60     BitArray row = new BitArray(width);
61
62     // We're going to examine rows from the middle outward, searching alternately above and below the middle,
63     // and farther out each time. rowStep is the number of rows between each successive attempt above and below
64     // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep,
65     // then middle - 2*rowStep, etc.
66     // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided
67     // that moving up and down by about 1/16 of the image is pretty good.
68     int middle = height >> 1;
69     int rowStep = Math.max(1, height >> 4);
70     int maxLines = tryHarder ? 15 : 7;
71     for (int x = 0; x < maxLines; x++) {
72
73       int rowStepsAboveOrBelow = (x + 1) >> 1;
74       boolean isAbove = (x & 0x01) == 0; // i.e. is x even?
75       int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
76       if (rowNumber < 0 || rowNumber >= height) {
77         break;
78       }
79
80       image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber);
81       image.getBlackRow(rowNumber, row, 0, width);
82
83       try {
84         return decodeRow(rowNumber, row, hints);
85       } catch (ReaderException re) {
86         if (tryHarder) {
87           row.reverse(); // try scanning the row backwards
88           try {
89             return decodeRow(rowNumber, row, hints);
90           } catch (ReaderException re2) {
91             // continue
92           }
93         }
94       }
95
96     }
97
98     throw new ReaderException("No barcode found");
99   }
100
101   protected static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException {
102     int numCounters = counters.length;
103     for (int i = 0; i < numCounters; i++) {
104       counters[i] = 0;
105     }
106     int end = row.getSize();
107     if (start >= end) {
108       throw new ReaderException("Couldn't fully read a pattern");
109     }
110     boolean isWhite = !row.get(start);
111     int counterPosition = 0;
112     int i = start;
113     while (i < end) {
114       boolean pixel = row.get(i);
115       if ((!pixel && isWhite) || (pixel && !isWhite)) {
116         counters[counterPosition]++;
117       } else {
118         counterPosition++;
119         if (counterPosition == numCounters) {
120           break;
121         } else {
122           counters[counterPosition] = 1;
123           isWhite = !isWhite;
124         }
125       }
126       i++;
127     }
128     // If we read fully the last section of pixels and filled up our counters -- or filled
129     // the last counter but ran off the side of the image, OK. Otherwise, a problem.
130     if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) {
131       throw new ReaderException("Couldn't fully read a pattern");
132     }
133   }
134
135   /**
136    * Determines how closely a set of observed counts of runs of black/white values matches a given
137    * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions
138    * across all pattern elements, to the length of the pattern.
139    *
140    * @param counters observed counters
141    * @param pattern expected pattern
142    * @return average variance between counters and pattern
143    */
144   protected static float patternMatchVariance(int[] counters, int[] pattern) {
145     int total = 0;
146     int numCounters = counters.length;
147     int patternLength = 0;
148     for (int i = 0; i < numCounters; i++) {
149       total += counters[i];
150       patternLength += pattern[i];
151     }
152     float unitBarWidth = (float) total / (float) patternLength;
153
154     float totalVariance = 0.0f;
155     for (int x = 0; x < numCounters; x++) {
156       float scaledCounter = (float) counters[x] / unitBarWidth;
157       float width = pattern[x];
158       float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter;
159       totalVariance += abs;
160     }
161     return totalVariance / (float) patternLength;
162   }
163
164   /**
165    * Fast round method.
166    *
167    * @return argument rounded to nearest int
168    */
169   protected static int round(float f) {
170     return (int) (f + 0.5f);
171   }
172
173 }