Extended the command line tool to dump the results of black point calculation. You...
[zxing.git] / javase / src / com / google / zxing / client / j2se / CommandLineRunner.java
1 /*
2  * Copyright 2007 ZXing authors
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.client.j2se;
18
19 import com.google.zxing.BlackPointEstimationMethod;
20 import com.google.zxing.DecodeHintType;
21 import com.google.zxing.MonochromeBitmapSource;
22 import com.google.zxing.MultiFormatReader;
23 import com.google.zxing.ReaderException;
24 import com.google.zxing.Result;
25 import com.google.zxing.client.result.ParsedResult;
26 import com.google.zxing.client.result.ResultParser;
27 import com.google.zxing.common.BitArray;
28
29 import javax.imageio.ImageIO;
30 import java.awt.image.BufferedImage;
31 import java.io.File;
32 import java.io.FileNotFoundException;
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.io.OutputStream;
36 import java.io.OutputStreamWriter;
37 import java.io.Writer;
38 import java.net.URI;
39 import java.net.URISyntaxException;
40 import java.nio.charset.Charset;
41 import java.util.Hashtable;
42
43 /**
44  * <p>This simple command line utility decodes files, directories of files, or URIs which are passed
45  * as arguments. By default it uses the normal decoding algorithms, but you can pass --try_harder to
46  * request that hint. The raw text of each barcode is printed, and when running against directories,
47  * summary statistics are also displayed.</p>
48  *
49  * @author Sean Owen
50  * @author dswitkin@google.com (Daniel Switkin)
51  */
52 public final class CommandLineRunner {
53
54   private CommandLineRunner() {
55   }
56
57   public static void main(String[] args) throws Exception {
58     Hashtable<DecodeHintType, Object> hints = null;
59     boolean dumpResults = false;
60     boolean dumpBlackPoint = false;
61     for (String arg : args) {
62       if ("--try_harder".equals(arg)) {
63         hints = new Hashtable<DecodeHintType, Object>(3);
64         hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
65       } else if ("--dump_results".equals(arg)) {
66         dumpResults = true;
67       } else if ("--dump_black_point".equals(arg)) {
68         dumpBlackPoint = true;
69       } else if (arg.startsWith("--")) {
70         System.out.println("Unknown command line option " + arg);
71         return;
72       }
73     }
74     for (String arg : args) {
75       if (!arg.startsWith("--")) {
76         decodeOneArgument(arg, hints, dumpResults, dumpBlackPoint);
77       }
78     }
79   }
80
81   private static void decodeOneArgument(String argument, Hashtable<DecodeHintType, Object> hints,
82       boolean dumpResults, boolean dumpBlackPoint) throws IOException,
83       URISyntaxException {
84
85     File inputFile = new File(argument);
86     if (inputFile.exists()) {
87       if (inputFile.isDirectory()) {
88         int successful = 0;
89         int total = 0;
90         for (File input : inputFile.listFiles()) {
91           String filename = input.getName().toLowerCase();
92           // Skip hidden files and text files (the latter is found in the blackbox tests).
93           if (filename.startsWith(".") || filename.endsWith(".txt")) {
94             continue;
95           }
96           // Skip the results of dumping the black point.
97           if (filename.contains(".mono.png")) {
98             continue;
99           }
100           Result result = decode(input.toURI(), hints, dumpBlackPoint);
101           if (result != null) {
102             successful++;
103             if (dumpResults) {
104               dumpResult(input, result);
105             }
106           }
107           total++;
108         }
109         System.out.println("\nDecoded " + successful + " files out of " + total +
110             " successfully (" + (successful * 100 / total) + "%)\n");
111       } else {
112         Result result = decode(inputFile.toURI(), hints, dumpBlackPoint);
113         if (dumpResults) {
114           dumpResult(inputFile, result);
115         }
116       }
117     } else {
118       decode(new URI(argument), hints, dumpBlackPoint);
119     }
120   }
121
122   private static void dumpResult(File input, Result result) throws IOException {
123     String name = input.getAbsolutePath();
124     int pos = name.lastIndexOf('.');
125     if (pos > 0) {
126       name = name.substring(0, pos);
127     }
128     File dump = new File(name + ".txt");
129     writeStringToFile(result.getText(), dump);
130   }
131
132   private static void writeStringToFile(String value, File file) throws IOException {
133     Writer out = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF8"));
134     try {
135       out.write(value);
136     } finally {
137       out.close();
138     }
139   }
140
141   private static Result decode(URI uri, Hashtable<DecodeHintType, Object> hints,
142       boolean dumpBlackPoint) throws IOException {
143     BufferedImage image;
144     try {
145       image = ImageIO.read(uri.toURL());
146     } catch (IllegalArgumentException iae) {
147       throw new FileNotFoundException("Resource not found: " + uri);
148     }
149     if (image == null) {
150       System.err.println(uri.toString() + ": Could not load image");
151       return null;
152     }
153     try {
154       MonochromeBitmapSource source = new BufferedImageMonochromeBitmapSource(image);
155       if (dumpBlackPoint) {
156         dumpBlackPoint(uri, image, source);
157       }
158       Result result = new MultiFormatReader().decode(source, hints);
159       ParsedResult parsedResult = ResultParser.parseResult(result);
160       System.out.println(uri.toString() + " (format: " + result.getBarcodeFormat() +
161           ", type: " + parsedResult.getType() + "):\nRaw result:\n" + result.getText() +
162           "\nParsed result:\n" + parsedResult.getDisplayResult());
163       return result;
164     } catch (ReaderException e) {
165       System.out.println(uri.toString() + ": No barcode found");
166       return null;
167     }
168   }
169
170   // Writes out a single PNG which is three times the width of the input image, containing from left
171   // to right: the original image, the row sampling monochrome version, and the 2D sampling
172   // monochrome version.
173   // TODO: Currently fails on URLs. Would be nice to handle gracefully and write the output to pwd.
174   private static void dumpBlackPoint(URI uri, BufferedImage image, MonochromeBitmapSource source) {
175     String inputName = uri.getPath();
176     if (inputName.contains(".mono.png")) {
177       return;
178     }
179
180     int width = source.getWidth();
181     int height = source.getHeight();
182     int stride = width * 3;
183     int[] pixels = new int[stride * height];
184
185     // The original image
186     int[] argb = new int[width];
187     for (int y = 0; y < height; y++) {
188       image.getRGB(0, y, width, 1, argb, 0, width);
189       System.arraycopy(argb, 0, pixels, y * stride, width);
190     }
191     argb = null;
192
193     // Row sampling
194     BitArray row = new BitArray(width);
195     for (int y = 0; y < height; y++) {
196       try {
197         source.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, y);
198       } catch (ReaderException e) {
199         // If the row histogram failed, draw a red line and keep going
200         int offset = y * stride + width;
201         for (int x = 0; x < width; x++) {
202           pixels[offset + x] = 0xffff0000;
203         }
204         continue;
205       }
206       source.getBlackRow(y, row, 0, width);
207       int offset = y * stride + width;
208       for (int x = 0; x < width; x++) {
209         if (row.get(x)) {
210           pixels[offset + x] = 0xff000000;
211         } else {
212           pixels[offset + x] = 0xffffffff;
213         }
214       }
215     }
216
217     // 2D sampling
218     try {
219       source.estimateBlackPoint(BlackPointEstimationMethod.TWO_D_SAMPLING, 0);
220       for (int y = 0; y < height; y++) {
221         source.getBlackRow(y, row, 0, width);
222         int offset = y * stride + width * 2;
223         for (int x = 0; x < width; x++) {
224           if (row.get(x)) {
225             pixels[offset + x] = 0xff000000;
226           } else {
227             pixels[offset + x] = 0xffffffff;
228           }
229         }
230       }
231     } catch (ReaderException e) {
232     }
233
234     // Write the result
235     BufferedImage result = new BufferedImage(stride, height, BufferedImage.TYPE_INT_ARGB);
236     result.setRGB(0, 0, stride, height, pixels, 0, stride);
237
238     String resultName = inputName;
239     int pos = resultName.lastIndexOf('.');
240     if (pos > 0) {
241       resultName = resultName.substring(0, pos);
242     }
243     resultName += ".mono.png";
244     try {
245       OutputStream outStream = new FileOutputStream(resultName);
246       ImageIO.write(result, "png", outStream);
247     } catch (FileNotFoundException e) {
248       System.out.println("Could not create " + resultName);
249     } catch (IOException e) {
250       System.out.println("Could not write to " + resultName);
251     }
252   }
253
254 }