1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
| import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.List;
import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
public class OcrProcess {
private static Logger logger = LogManager.getLogger(OcrProcess.class);
private String tessPath = "";
private String ocr_psm_num = "3";
private String ocr_language = "eng";
private String ocr_result_path = "";
private String ocr_result_file_path = "";
private final String OS = System.getProperty("os.name");
private final String ocr_lang_option = "-l";
public final String ocr_psm_option = "-psm";
private long procID = 0;
private final String EOL = System.getProperty("line.separator");
private final String FIS = System.getProperties().getProperty("file.separator");
public OcrProcess(String tessPath) { this.tessPath = tessPath;
if(logger.isDebugEnabled()){ logger.debug("OcrProcess Created ."); logger.debug("OcrProcess Current OS >>> {} ",this.OS); logger.debug("OcrProcess User tessPath >>> {} ",this.tessPath); }else if(logger.isInfoEnabled()){ logger.info("OcrProcess Created ."); } }
public void setPageSegMode(Integer psm){
if(logger.isDebugEnabled()){ logger.debug("OcrProcess User set OCR Process PageSeqMode >>> {}",psm); }else if(logger.isInfoEnabled()){ logger.info("OcrProcess User set OCR Process PageSeqMode >>> {}",psm); }
if(psm == null){ throw new IllegalArgumentException("param psm is null,will use default 3"); } if(psm > 10 || psm < 0){ throw new IllegalArgumentException("param psm only between 0 and 10,will use default 3"); }
this.ocr_psm_num = String.valueOf(psm); }
public void setSaveDir(String savePath) throws FileNotFoundException {
if(logger.isDebugEnabled()){ logger.debug("OcrProcess User set OCR Process Result TXT SavePath >>> {}",savePath); }else if(logger.isInfoEnabled()){ logger.info("OcrProcess User set OCR Process Result TXT SavePath >>> {}",savePath); }
File saveDir = new File(savePath);
if(!saveDir.exists()){ throw new FileNotFoundException("the savePath is not found!"); }
this.ocr_result_path = savePath;
}
public String doOCR(File file , String language) throws NoSupportFileTypeException { this.procID = new Random().nextInt(1000);
if(logger.isDebugEnabled()){ logger.debug("OcrProcess Begin. The file >>> [{}], the procID is [{}] .",file.getName(),this.procID); }else if(logger.isInfoEnabled()){ logger.info("OcrProcess Begin. The file >>> [{}], the procID is [{}] . See More info PLZ set logger Debug or Trace.",file.getName(),this.procID); }
String textSavePath = "";
if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : FilePath >>> {}",this.procID,file.getAbsolutePath()); logger.debug("[{}] OCR process info : FileName >>> {}",this.procID,file.getName()); logger.debug("[{}] OCR process info : FileSize >>> {} KB",this.procID,(file.length() / 1024f)); logger.debug("[{}] OCR process info : OCR Language >>> {}",this.procID,language); }
this.ocr_language = language;
int fileType = this.getFileType(file.getName());
if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : FileType >>> {}",this.procID,fileType); } if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : The FileType is Image .",this.procID); } textSavePath = callTesseractCommand(file);
return textSavePath; }
private String getOutPutDir(File sourceFile){
if(StringUtils.isEmpty(this.ocr_result_path)){ return sourceFile.getAbsolutePath().substring(0,sourceFile.getAbsolutePath().lastIndexOf(this.FIS)); }
return this.ocr_result_path; }
private Integer getFileType(String fileName) throws NoSupportFileTypeException {
Integer type = null;
if(type == null){ }
return type; }
private ProcessBuilder createProcessBuilder(File sourceFile){
ProcessBuilder pb = new ProcessBuilder();
if(this.OS.startsWith("Mac OS") || this.OS.startsWith("Linux")){
pb.directory(new File(this.tessPath)); if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : Set ProcessBuilder working dir >>> {}",this.procID,this.tessPath); }
}else if(this.OS.startsWith("Windows")){ pb.directory(sourceFile.getParentFile()); if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : Set ProcessBuilder working dir >>> {}",this.procID,sourceFile.getParentFile()); } }
pb.redirectErrorStream(true);
return pb; }
private List<String> createCommand(File sourceFile){
List<String> cmd = new ArrayList<String>();
String result_out_dir = getOutPutDir(sourceFile);
String ocr_result_filename = sourceFile.getName().substring(0 , sourceFile.getName().lastIndexOf("."));
String result_out_filePath = result_out_dir + this.FIS + ocr_result_filename + ".txt";
this.ocr_result_file_path = result_out_filePath;
if(logger.isDebugEnabled()) { logger.debug("[{}] OCR process info : Result SaveDir >>> {}",this.procID,result_out_dir); logger.debug("[{}] OCR process info : Result SaveFilePath >>> {}",this.procID,result_out_filePath); }else if(logger.isInfoEnabled()){ logger.info("[{}] OCR process info : Result SaveFilePath >>> {}",this.procID,result_out_filePath); }
if(this.OS.startsWith("Mac OS") || this.OS.startsWith("Linux")){ cmd.add("tesseract"); cmd.add(sourceFile.getAbsolutePath());
}else if(this.OS.startsWith("Windows")){ cmd.add(this.tessPath + this.FIS + "tesseract"); cmd.add(sourceFile.getName()); }
cmd.add(result_out_dir + this.FIS + ocr_result_filename); cmd.add(this.ocr_psm_option); cmd.add(this.ocr_psm_num); cmd.add(this.ocr_lang_option); cmd.add(this.ocr_language);
if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : The Command >>> {}",this.procID,cmd.toString()); }else if(logger.isInfoEnabled()){ logger.info("[{}] OCR process info : The Command >>> {}",this.procID,cmd.toString()); }
return cmd; }
private void processSpace(String txtFilePath) throws FileNotFoundException {
FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; String str;
FileOutputStream fos = null; OutputStreamWriter osw = null; BufferedWriter bw = null;
boolean readSuccess = true;
File txtFile = new File(txtFilePath);
if(!txtFile.exists()){ throw new FileNotFoundException("OCR process Result file is not exist!"); }
StringBuilder sb = new StringBuilder();
try { fis = new FileInputStream(txtFile); isr = new InputStreamReader(fis,"UTF-8"); br = new BufferedReader(isr);
while ((str = br.readLine()) != null) { sb.append(str).append(this.EOL); } } catch (Exception e){ logger.error("[{}] OCR process space read file faild .",this.procID,e); readSuccess = false; } finally { try { br.close(); }catch (Exception e){ } try { isr.close(); }catch (Exception e){ } try { fis.close(); }catch (Exception e){ } }
if(readSuccess){ try { fos = new FileOutputStream(txtFile); osw = new OutputStreamWriter(fos,"UTF-8"); bw = new BufferedWriter(osw); bw.write(sb.toString().replaceAll(" ", "")); } catch (Exception e){ logger.error("[{}] OCR process space write file faild .",this.procID,e); } finally { try { bw.close(); }catch (Exception e){ } try { osw.close(); }catch (Exception e){ } try { fos.close(); }catch (Exception e){ } } } }
private void printCommandError(Process process){ InputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; try { fis = process.getInputStream(); isr = new InputStreamReader(fis); br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { logger.warn("[{}] OCR process warning : {} ",this.procID,line); } } catch (Exception e){ logger.warn("[{}] OCR process print command error Faild!",e); } finally { try { br.close(); } catch (Exception e){ } try { isr.close(); } catch (Exception e){ } try { fis.close(); } catch (Exception e){ } } }
private String callTesseractCommand(File imageFile) {
String txt_path = "";
List<String> comand = this.createCommand(imageFile);
ProcessBuilder pb = this.createProcessBuilder(imageFile);
pb.command(comand);
if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : Add command to ProcessBuilder",this.procID); }
Process process = null; try {
if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : Excute OCR Command.",this.procID); } process = pb.start();
int w = process.waitFor(); if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : Command excute result >>> {}",this.procID,w); }else if(logger.isInfoEnabled()){ logger.info("[{}] OCR process info : Command excute result >>> {}",this.procID,w); }
if (w == 0) { txt_path = this.ocr_result_file_path; this.processSpace(txt_path); } else { this.printCommandError(process); String msg = "[%s] excute command Faild ! Result %d , Reason : %s !"; switch (w) { case 1: msg = String.format(msg,this.procID,w,"无法访问文件,可能文件名中存在空格等特殊字符"); break; case 29: msg = String.format(msg,this.procID,w,"无法识别图像或其选定区域"); break; case 31: msg = String.format(msg,this.procID,w,"不支持的图片格式"); break; default: msg = String.format(msg,this.procID,w,"未知错误"); } throw new RuntimeException(msg); }
} catch (IOException e) { logger.error("[{}] OCR process info : Command excute [pb.start()] Faild !",this.procID,e); } catch (InterruptedException e) { logger.error("[{}] OCR process info : Command excute [process.waitFor()] Faild !",this.procID,e); }
if(logger.isDebugEnabled()){ logger.debug("[{}] OCR process info : OCR Process End.",this.procID); }else if(logger.isInfoEnabled()){ logger.info("[{}] OCR process info : OCR Process End.",this.procID); }
return txt_path; }
}
|