Update Codabar style and disable it as its causing too many false positives
[zxing.git] / core / src / com / google / zxing / oned / CodaBarReader.java
1 /*\r
2  * Copyright 2008 ZXing authors\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.google.zxing.oned;\r
18 \r
19 import java.util.Hashtable;\r
20 \r
21 import com.google.zxing.BarcodeFormat;\r
22 import com.google.zxing.NotFoundException;\r
23 import com.google.zxing.Result;\r
24 import com.google.zxing.ResultPoint;\r
25 import com.google.zxing.common.BitArray;\r
26 \r
27 /**\r
28  * <p>Decodes Codabar barcodes.</p>\r
29  *\r
30  * @author Bas Vijfwinkel\r
31  */\r
32 public final class CodaBarReader extends OneDReader {\r
33 \r
34   private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";\r
35   private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();\r
36 \r
37   /**\r
38    * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of\r
39    * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE\r
40    * : c is equal to the  * pattern NOTE : d is equal to the e pattern\r
41    */\r
42   private static final int[] CHARACTER_ENCODINGS = {\r
43       0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9\r
44       0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD\r
45       0x01A, 0x029 //TN\r
46   };\r
47 \r
48   // multiple start/end patterns\r
49   // official start and end patterns\r
50   // some codabar generator allow the codabar string to be closed by every character\r
51   private static final char[] STARTEND_ENCODING = {\r
52       '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};\r
53 \r
54   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException {\r
55     int[] start = findAsteriskPattern(row);\r
56     start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?\r
57     int nextStart = start[1];\r
58     int end = row.getSize();\r
59 \r
60     // Read off white space\r
61     while (nextStart < end && !row.get(nextStart)) {\r
62       nextStart++;\r
63     }\r
64 \r
65     StringBuffer result = new StringBuffer();\r
66     //int[] counters = new int[7];\r
67     int[] counters;\r
68     int lastStart;\r
69 \r
70     do {\r
71       counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters\r
72       recordPattern(row, nextStart, counters);\r
73 \r
74       char decodedChar = toNarrowWidePattern(counters);\r
75       if (decodedChar == '!') {\r
76         throw NotFoundException.getNotFoundInstance();\r
77       }\r
78       result.append(decodedChar);\r
79       lastStart = nextStart;\r
80       for (int i = 0; i < counters.length; i++) {\r
81         nextStart += counters[i];\r
82       }\r
83 \r
84       // Read off white space\r
85       while (nextStart < end && !row.get(nextStart)) {\r
86         nextStart++;\r
87       }\r
88     } while (nextStart < end); // no fixed end pattern so keep on reading while data is available\r
89 \r
90     // find last character in STARTEND_ENCODING\r
91     for (int k = result.length() - 1; k >= 0; k--) {\r
92       if (arrayContains(STARTEND_ENCODING, result.charAt(k))) {\r
93         // valid character -> remove and break out of loop\r
94         result.deleteCharAt(k);\r
95         k = -1;// break out of loop\r
96       } else {\r
97         // not a valid character -> remove anyway\r
98         result.deleteCharAt(k);\r
99       }\r
100     }\r
101 \r
102 \r
103     // remove first character\r
104     if (result.length() > 0) {\r
105       result.deleteCharAt(0);\r
106     }\r
107 \r
108     // Look for whitespace after pattern:\r
109     int lastPatternSize = 0;\r
110     for (int i = 0; i < counters.length; i++) {\r
111       lastPatternSize += counters[i];\r
112     }\r
113     int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;\r
114     // If 50% of last pattern size, following last pattern, is not whitespace, fail\r
115     // (but if it's whitespace to the very end of the image, that's OK)\r
116     if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {\r
117       throw NotFoundException.getNotFoundInstance();\r
118     }\r
119 \r
120 \r
121     String resultString = result.toString();\r
122     if (resultString.length() == 0) {\r
123       // Almost surely a false positive\r
124       throw NotFoundException.getNotFoundInstance();\r
125     }\r
126 \r
127     float left = (float) (start[1] + start[0]) / 2.0f;\r
128     float right = (float) (nextStart + lastStart) / 2.0f;\r
129     return new Result(\r
130         resultString,\r
131         null,\r
132         new ResultPoint[]{\r
133             new ResultPoint(left, (float) rowNumber),\r
134             new ResultPoint(right, (float) rowNumber)},\r
135         BarcodeFormat.CODABAR);\r
136   }\r
137 \r
138   private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {\r
139     int width = row.getSize();\r
140     int rowOffset = 0;\r
141     while (rowOffset < width) {\r
142       if (row.get(rowOffset)) {\r
143         break;\r
144       }\r
145       rowOffset++;\r
146     }\r
147 \r
148     int counterPosition = 0;\r
149     int[] counters = new int[7];\r
150     int patternStart = rowOffset;\r
151     boolean isWhite = false;\r
152     int patternLength = counters.length;\r
153 \r
154     for (int i = rowOffset; i < width; i++) {\r
155       boolean pixel = row.get(i);\r
156       if (pixel ^ isWhite) {\r
157         counters[counterPosition]++;\r
158       } else {\r
159         if (counterPosition == patternLength - 1) {\r
160           try {\r
161             if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {\r
162               // Look for whitespace before start pattern, >= 50% of width of start pattern\r
163               if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {\r
164                 return new int[]{patternStart, i};\r
165               }\r
166             }\r
167           } catch (IllegalArgumentException re) {\r
168             // no match, continue\r
169           }\r
170           patternStart += counters[0] + counters[1];\r
171           for (int y = 2; y < patternLength; y++) {\r
172             counters[y - 2] = counters[y];\r
173           }\r
174           counters[patternLength - 2] = 0;\r
175           counters[patternLength - 1] = 0;\r
176           counterPosition--;\r
177         } else {\r
178           counterPosition++;\r
179         }\r
180         counters[counterPosition] = 1;\r
181         isWhite ^= true; // isWhite = !isWhite;\r
182       }\r
183     }\r
184     throw NotFoundException.getNotFoundInstance();\r
185   }\r
186 \r
187   private static boolean arrayContains(char[] array, char key) {\r
188     if (array != null) {\r
189       for (int i = 0; i < array.length; i++) {\r
190         if (array[i] == key) {\r
191           return true;\r
192         }\r
193       }\r
194     }\r
195     return false;\r
196   }\r
197 \r
198   private static char toNarrowWidePattern(int[] counters) {\r
199     // BAS : I have changed the following part because some codabar images would fail with the original routine\r
200     //        I took from the Code39Reader.java file\r
201     // ----------- change start\r
202     int numCounters = counters.length;\r
203     int maxNarrowCounter = 0;\r
204 \r
205     int minCounter = Integer.MAX_VALUE;\r
206     for (int i = 0; i < numCounters; i++) {\r
207       if (counters[i] < minCounter) {\r
208         minCounter = counters[i];\r
209       }\r
210       if (counters[i] > maxNarrowCounter) {\r
211         maxNarrowCounter = counters[i];\r
212       }\r
213     }\r
214     // ---------- change end\r
215 \r
216 \r
217     do {\r
218       int wideCounters = 0;\r
219       int pattern = 0;\r
220       for (int i = 0; i < numCounters; i++) {\r
221         if (counters[i] > maxNarrowCounter) {\r
222           pattern |= 1 << (numCounters - 1 - i);\r
223           wideCounters++;\r
224         }\r
225       }\r
226 \r
227       if ((wideCounters == 2) || (wideCounters == 3)) {\r
228         for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {\r
229           if (CHARACTER_ENCODINGS[i] == pattern) {\r
230             return ALPHABET[i];\r
231           }\r
232         }\r
233       }\r
234       maxNarrowCounter--;\r
235     } while (maxNarrowCounter > minCounter);\r
236     return '!';\r
237   }\r
238 \r
239 }\r