Undo the ^= true thing in more files
[zxing.git] / core / src / com / google / zxing / oned / ITFReader.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 com.google.zxing.BarcodeFormat;\r
20 import com.google.zxing.DecodeHintType;\r
21 import com.google.zxing.ReaderException;\r
22 import com.google.zxing.Result;\r
23 import com.google.zxing.ResultPoint;\r
24 import com.google.zxing.common.BitArray;\r
25 \r
26 import java.util.Hashtable;\r
27 \r
28 /**\r
29  * <p>Implements decoding of the ITF format.</p>\r
30  *\r
31  * <p>"ITF" stands for Interleaved Two of Five. This Reader will scan ITF barcode with 6, 10 or 14\r
32  * digits. The checksum is optional and is not applied by this Reader. The consumer of the decoded\r
33  * value will have to apply a checksum if required.</p>\r
34  *\r
35  * <p><a href="http://en.wikipedia.org/wiki/Interleaved_2_of_5">http://en.wikipedia.org/wiki/Interleaved_2_of_5</a>\r
36  * is a great reference for Interleaved 2 of 5 information.</p>\r
37  *\r
38  * @author kevin.osullivan@sita.aero, SITA Lab.\r
39  */\r
40 public final class ITFReader extends OneDReader {\r
41 \r
42   private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);\r
43   private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f);\r
44 \r
45   private static final int W = 3; // Pixel width of a wide line\r
46   private static final int N = 1; // Pixed width of a narrow line\r
47 \r
48   private static final int[] DEFAULT_ALLOWED_LENGTHS = { 6, 10, 14, 44 };\r
49 \r
50   // Stores the actual narrow line width of the image being decoded.\r
51   private int narrowLineWidth = -1;\r
52 \r
53   /**\r
54    * Start/end guard pattern.\r
55    *\r
56    * Note: The end pattern is reversed because the row is reversed before\r
57    * searching for the END_PATTERN\r
58    */\r
59   private static final int[] START_PATTERN = {N, N, N, N};\r
60   private static final int[] END_PATTERN_REVERSED = {N, N, W};\r
61 \r
62   /**\r
63    * Patterns of Wide / Narrow lines to indicate each digit\r
64    */\r
65   private static final int[][] PATTERNS = {\r
66       {N, N, W, W, N}, // 0\r
67       {W, N, N, N, W}, // 1\r
68       {N, W, N, N, W}, // 2\r
69       {W, W, N, N, N}, // 3\r
70       {N, N, W, N, W}, // 4\r
71       {W, N, W, N, N}, // 5\r
72       {N, W, W, N, N}, // 6\r
73       {N, N, N, W, W}, // 7\r
74       {W, N, N, W, N}, // 8\r
75       {N, W, N, W, N}  // 9\r
76   };\r
77 \r
78   public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {\r
79 \r
80     // Find out where the Middle section (payload) starts & ends\r
81     int[] startRange = decodeStart(row);\r
82     int[] endRange = decodeEnd(row);\r
83 \r
84     StringBuffer result = new StringBuffer(20);\r
85     decodeMiddle(row, startRange[1], endRange[0], result);\r
86     String resultString = result.toString();\r
87 \r
88     int[] allowedLengths = null;\r
89     if (hints != null) {\r
90       allowedLengths = (int[]) hints.get(DecodeHintType.ALLOWED_LENGTHS);\r
91 \r
92     }\r
93     if (allowedLengths == null) {\r
94       allowedLengths = DEFAULT_ALLOWED_LENGTHS;\r
95     }\r
96 \r
97     // To avoid false positives with 2D barcodes (and other patterns), make\r
98     // an assumption that the decoded string must be 6, 10 or 14 digits.\r
99     int length = resultString.length();\r
100     boolean lengthOK = false;\r
101     for (int i = 0; i < allowedLengths.length; i++) {\r
102       if (length == allowedLengths[i]) {\r
103         lengthOK = true;\r
104         break;\r
105       }\r
106 \r
107     }\r
108     if (!lengthOK) {\r
109       throw ReaderException.getInstance();\r
110     }\r
111 \r
112     return new Result(\r
113         resultString,\r
114         null, // no natural byte representation for these barcodes\r
115         new ResultPoint[] { new ResultPoint(startRange[1], (float) rowNumber),\r
116                             new ResultPoint(endRange[0], (float) rowNumber)},\r
117         BarcodeFormat.ITF);\r
118   }\r
119 \r
120   /**\r
121    * @param row          row of black/white values to search\r
122    * @param payloadStart offset of start pattern\r
123    * @param resultString {@link StringBuffer} to append decoded chars to\r
124    * @throws ReaderException if decoding could not complete successfully\r
125    */\r
126   private static void decodeMiddle(BitArray row, int payloadStart, int payloadEnd,\r
127       StringBuffer resultString) throws ReaderException {\r
128 \r
129     // Digits are interleaved in pairs - 5 black lines for one digit, and the\r
130     // 5\r
131     // interleaved white lines for the second digit.\r
132     // Therefore, need to scan 10 lines and then\r
133     // split these into two arrays\r
134     int[] counterDigitPair = new int[10];\r
135     int[] counterBlack = new int[5];\r
136     int[] counterWhite = new int[5];\r
137 \r
138     while (payloadStart < payloadEnd) {\r
139 \r
140       // Get 10 runs of black/white.\r
141       recordPattern(row, payloadStart, counterDigitPair);\r
142       // Split them into each array\r
143       for (int k = 0; k < 5; k++) {\r
144         int twoK = k << 1;\r
145         counterBlack[k] = counterDigitPair[twoK];\r
146         counterWhite[k] = counterDigitPair[twoK + 1];\r
147       }\r
148 \r
149       int bestMatch = decodeDigit(counterBlack);\r
150       resultString.append((char) ('0' + bestMatch));\r
151       bestMatch = decodeDigit(counterWhite);\r
152       resultString.append((char) ('0' + bestMatch));\r
153 \r
154       for (int i = 0; i < counterDigitPair.length; i++) {\r
155         payloadStart += counterDigitPair[i];\r
156       }\r
157     }\r
158   }\r
159 \r
160   /**\r
161    * Identify where the start of the middle / payload section starts.\r
162    *\r
163    * @param row row of black/white values to search\r
164    * @return Array, containing index of start of 'start block' and end of\r
165    *         'start block'\r
166    * @throws ReaderException\r
167    */\r
168   int[] decodeStart(BitArray row) throws ReaderException {\r
169     int endStart = skipWhiteSpace(row);\r
170     int[] startPattern = findGuardPattern(row, endStart, START_PATTERN);\r
171 \r
172     // Determine the width of a narrow line in pixels. We can do this by\r
173     // getting the width of the start pattern and dividing by 4 because its\r
174     // made up of 4 narrow lines.\r
175     this.narrowLineWidth = (startPattern[1] - startPattern[0]) >> 2;\r
176 \r
177     validateQuietZone(row, startPattern[0]);\r
178 \r
179     return startPattern;\r
180   }\r
181 \r
182   /**\r
183    * The start & end patterns must be pre/post fixed by a quiet zone. This\r
184    * zone must be at least 10 times the width of a narrow line.  Scan back until\r
185    * we either get to the start of the barcode or match the necessary number of\r
186    * quiet zone pixels.\r
187    *\r
188    * Note: Its assumed the row is reversed when using this method to find\r
189    * quiet zone after the end pattern.\r
190    *\r
191    * ref: http://www.barcode-1.net/i25code.html\r
192    *\r
193    * @param row bit array representing the scanned barcode.\r
194    * @param startPattern index into row of the start or end pattern.\r
195    * @throws ReaderException if the quiet zone cannot be found, a ReaderException is thrown.\r
196    */\r
197   private void validateQuietZone(BitArray row, int startPattern) throws ReaderException {\r
198 \r
199     int quietCount = this.narrowLineWidth * 10;  // expect to find this many pixels of quiet zone\r
200 \r
201     for (int i = startPattern - 1; quietCount > 0 && i >= 0; i--) {\r
202       if (row.get(i)) {\r
203         break;\r
204       }\r
205       quietCount--;\r
206     }\r
207     if (quietCount != 0) {\r
208       // Unable to find the necessary number of quiet zone pixels.\r
209       throw ReaderException.getInstance();\r
210     }\r
211   }\r
212 \r
213   /**\r
214    * Skip all whitespace until we get to the first black line.\r
215    *\r
216    * @param row row of black/white values to search\r
217    * @return index of the first black line.\r
218    * @throws ReaderException Throws exception if no black lines are found in the row\r
219    */\r
220   private static int skipWhiteSpace(BitArray row) throws ReaderException {\r
221     int width = row.getSize();\r
222     int endStart = 0;\r
223     while (endStart < width) {\r
224       if (row.get(endStart)) {\r
225         break;\r
226       }\r
227       endStart++;\r
228     }\r
229     if (endStart == width) {\r
230       throw ReaderException.getInstance();\r
231     }\r
232 \r
233     return endStart;\r
234   }\r
235 \r
236   /**\r
237    * Identify where the end of the middle / payload section ends.\r
238    *\r
239    * @param row row of black/white values to search\r
240    * @return Array, containing index of start of 'end block' and end of 'end\r
241    *         block'\r
242    * @throws ReaderException\r
243    */\r
244 \r
245   int[] decodeEnd(BitArray row) throws ReaderException {\r
246 \r
247     // For convenience, reverse the row and then\r
248     // search from 'the start' for the end block\r
249     row.reverse();\r
250     try {\r
251       int endStart = skipWhiteSpace(row);\r
252       int[] endPattern = findGuardPattern(row, endStart, END_PATTERN_REVERSED);\r
253 \r
254       // The start & end patterns must be pre/post fixed by a quiet zone. This\r
255       // zone must be at least 10 times the width of a narrow line.\r
256       // ref: http://www.barcode-1.net/i25code.html\r
257       validateQuietZone(row, endPattern[0]);\r
258 \r
259       // Now recalculate the indices of where the 'endblock' starts & stops to\r
260       // accommodate\r
261       // the reversed nature of the search\r
262       int temp = endPattern[0];\r
263       endPattern[0] = row.getSize() - endPattern[1];\r
264       endPattern[1] = row.getSize() - temp;\r
265 \r
266       return endPattern;\r
267     } finally {\r
268       // Put the row back the right way.\r
269       row.reverse();\r
270     }\r
271   }\r
272 \r
273   /**\r
274    * @param row       row of black/white values to search\r
275    * @param rowOffset position to start search\r
276    * @param pattern   pattern of counts of number of black and white pixels that are\r
277    *                  being searched for as a pattern\r
278    * @return start/end horizontal offset of guard pattern, as an array of two\r
279    *         ints\r
280    * @throws ReaderException if pattern is not found\r
281    */\r
282   private static int[] findGuardPattern(BitArray row, int rowOffset, int[] pattern) throws ReaderException {\r
283 \r
284     // TODO: This is very similar to implementation in UPCEANReader. Consider if they can be\r
285     // merged to a single method.\r
286     int patternLength = pattern.length;\r
287     int[] counters = new int[patternLength];\r
288     int width = row.getSize();\r
289     boolean isWhite = false;\r
290 \r
291     int counterPosition = 0;\r
292     int patternStart = rowOffset;\r
293     for (int x = rowOffset; x < width; x++) {\r
294       boolean pixel = row.get(x);\r
295       if (pixel ^ isWhite) {\r
296         counters[counterPosition]++;\r
297       } else {\r
298         if (counterPosition == patternLength - 1) {\r
299           if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {\r
300             return new int[]{patternStart, x};\r
301           }\r
302           patternStart += counters[0] + counters[1];\r
303           for (int y = 2; y < patternLength; y++) {\r
304             counters[y - 2] = counters[y];\r
305           }\r
306           counters[patternLength - 2] = 0;\r
307           counters[patternLength - 1] = 0;\r
308           counterPosition--;\r
309         } else {\r
310           counterPosition++;\r
311         }\r
312         counters[counterPosition] = 1;\r
313         isWhite = !isWhite;\r
314       }\r
315     }\r
316     throw ReaderException.getInstance();\r
317   }\r
318 \r
319   /**\r
320    * Attempts to decode a sequence of ITF black/white lines into single\r
321    * digit.\r
322    *\r
323    * @param counters the counts of runs of observed black/white/black/... values\r
324    * @return The decoded digit\r
325    * @throws ReaderException if digit cannot be decoded\r
326    */\r
327   private static int decodeDigit(int[] counters) throws ReaderException {\r
328 \r
329     int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept\r
330     int bestMatch = -1;\r
331     int max = PATTERNS.length;\r
332     for (int i = 0; i < max; i++) {\r
333       int[] pattern = PATTERNS[i];\r
334       int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);\r
335       if (variance < bestVariance) {\r
336         bestVariance = variance;\r
337         bestMatch = i;\r
338       }\r
339     }\r
340     if (bestMatch >= 0) {\r
341       return bestMatch;\r
342                 } else {\r
343                         throw ReaderException.getInstance();\r
344                 }\r
345         }\r
346 \r
347 }\r