热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

JavaOCRtesseract图像智能文字字符识别技术实例代码

这篇文章主要介绍了JavaOCRtesseract图像智能文字字符识别技术实例代码,非常具有实用价值,需要的朋友可以参考下

接着上一篇OCR所说的,上一篇给大家介绍了tesseract 在命令行的简单用法,当然了要继承到我们的程序中,还是需要代码实现的,下面给大家分享下Java实现的例子。

拿代码扫描上面的图片,然后输出结果。主要思想就是利用Java调用系统任务。

下面是核心代码:

package com.zhy.test; 
 
import java.io.BufferedReader; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 
 
import org.jdesktop.swingx.util.OS; 
 
public class OCRHelper 
{ 
 private final String LANG_OPTION = "-l"; 
 private final String EOL = System.getProperty("line.separator"); 
 /** 
  * 文件位置我防止在,项目同一路径 
  */ 
 private String tessPath = new File("tesseract").getAbsolutePath(); 
 
 /** 
  * @param imageFile 
  *   传入的图像文件 
  * @param imageFormat 
  *   传入的图像格式 
  * @return 识别后的字符串 
  */ 
 public String recognizeText(File imageFile) throws Exception 
 { 
  /** 
   * 设置输出文件的保存的文件目录 
   */ 
  File outputFile = new File(imageFile.getParentFile(), "output"); 
 
  StringBuffer strB = new StringBuffer(); 
  List cmd = new ArrayList(); 
  if (OS.isWindowsXP()) 
  { 
   cmd.add(tessPath + "\\tesseract"); 
  } else if (OS.isLinux()) 
  { 
   cmd.add("tesseract"); 
  } else 
  { 
   cmd.add(tessPath + "\\tesseract"); 
  } 
  cmd.add(""); 
  cmd.add(outputFile.getName()); 
  cmd.add(LANG_OPTION); 
//  cmd.add("chi_sim"); 
  cmd.add("eng"); 
 
  ProcessBuilder pb = new ProcessBuilder(); 
  /** 
   *Sets this process builder's working directory. 
   */ 
  pb.directory(imageFile.getParentFile()); 
  cmd.set(1, imageFile.getName()); 
  pb.command(cmd); 
  pb.redirectErrorStream(true); 
  Process process = pb.start(); 
  // tesseract.exe 1.jpg 1 -l chi_sim 
  // Runtime.getRuntime().exec("tesseract.exe 1.jpg 1 -l chi_sim"); 
  /** 
   * the exit value of the process. By convention, 0 indicates normal 
   * termination. 
   */ 
//  System.out.println(cmd.toString()); 
  int w = process.waitFor(); 
  if (w == 0)// 0代表正常退出 
  { 
   BufferedReader in = new BufferedReader(new InputStreamReader( 
     new FileInputStream(outputFile.getAbsolutePath() + ".txt"), 
     "UTF-8")); 
   String str; 
 
   while ((str = in.readLine()) != null) 
   { 
    strB.append(str).append(EOL); 
   } 
   in.close(); 
  } else 
  { 
   String msg; 
   switch (w) 
   { 
   case 1: 
    msg = "Errors accessing files. There may be spaces in your image's filename."; 
    break; 
   case 29: 
    msg = "Cannot recognize the image or its selected region."; 
    break; 
   case 31: 
    msg = "Unsupported image format."; 
    break; 
   default: 
    msg = "Errors occurred."; 
   } 
   throw new RuntimeException(msg); 
  } 
  new File(outputFile.getAbsolutePath() + ".txt").delete(); 
  return strB.toString().replaceAll("\\s*", ""); 
 } 
} 

代码很简单,中间那部分ProcessBuilder其实就类似Runtime.getRuntime().exec("tesseract.exe 1.jpg 1 -l chi_sim"),大家不习惯的可以使用Runtime。

测试代码:

package com.zhy.test; 
 
import java.io.File; 
 
public class Test 
{ 
 public static void main(String[] args) 
 { 
  try 
  { 
    
   File testDataDir = new File("testdata"); 
   System.out.println(testDataDir.listFiles().length); 
   int i = 0 ; 
   for(File file :testDataDir.listFiles()) 
   { 
    i++ ; 
    String recognizeText = new OCRHelper().recognizeText(file); 
    System.out.print(recognizeText+"\t"); 
 
    if( i % 5 == 0 ) 
    { 
     System.out.println(); 
    } 
   } 
    
  } catch (Exception e) 
  { 
   e.printStackTrace(); 
  } 
 
 } 
} 

输出结果:

对比第一张图片,是不是很完美~哈哈 ,当然了如果你只需要实现验证码的读写,那么上面就足够了。下面继续普及图像处理的知识。

当然了,有时候图片被扭曲或者模糊的很厉害,很不容易识别,所以下面我给大家介绍一个去噪的辅助类,绝对碉堡了,先看下效果图。

 

来张特写:

一个类,不依赖任何jar,把图像中的干扰线消灭了,是不是很给力,然后再拿这样的图片去识别,会不会效果更好呢,嘿嘿,大家自己实验~

代码:

package com.zhy.test; 
 
import java.awt.Color; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
 
import javax.imageio.ImageIO; 
 
public class ClearImageHelper 
{ 
 
 public static void main(String[] args) throws IOException 
 { 
 
   
  File testDataDir = new File("testdata"); 
  final String destDir = testDataDir.getAbsolutePath()+"/tmp"; 
  for (File file : testDataDir.listFiles()) 
  { 
   cleanImage(file, destDir); 
  } 
 
 } 
 
 /** 
  * 
  * @param sfile 
  *   需要去噪的图像 
  * @param destDir 
  *   去噪后的图像保存地址 
  * @throws IOException 
  */ 
 public static void cleanImage(File sfile, String destDir) 
   throws IOException 
 { 
  File destF = new File(destDir); 
  if (!destF.exists()) 
  { 
   destF.mkdirs(); 
  } 
 
  BufferedImage bufferedImage = ImageIO.read(sfile); 
  int h = bufferedImage.getHeight(); 
  int w = bufferedImage.getWidth(); 
 
  // 灰度化 
  int[][] gray = new int[w][h]; 
  for (int x = 0; x > 16) & 0xFF) * 1.1 + 30); 
    int g = (int) (((argb >> 8) & 0xFF) * 1.1 + 30); 
    int b = (int) (((argb >> 0) & 0xFF) * 1.1 + 30); 
    if (r >= 255) 
    { 
     r = 255; 
    } 
    if (g >= 255) 
    { 
     g = 255; 
    } 
    if (b >= 255) 
    { 
     b = 255; 
    } 
    gray[x][y] = (int) Math 
      .pow((Math.pow(r, 2.2) * 0.2973 + Math.pow(g, 2.2) 
        * 0.6274 + Math.pow(b, 2.2) * 0.0753), 1 / 2.2); 
   } 
  } 
 
  // 二值化 
  int threshold = ostu(gray, w, h); 
  BufferedImage binaryBufferedImage = new BufferedImage(w, h, 
    BufferedImage.TYPE_BYTE_BINARY); 
  for (int x = 0; x  threshold) 
    { 
     gray[x][y] |= 0x00FFFF; 
    } else 
    { 
     gray[x][y] &= 0xFF0000; 
    } 
    binaryBufferedImage.setRGB(x, y, gray[x][y]); 
   } 
  } 
 
  // 矩阵打印 
  for (int y = 0; y  300) 
  { 
   return true; 
  } 
  return false; 
 } 
 
 public static int isBlackOrWhite(int colorInt) 
 { 
  if (getColorBright(colorInt) <30 || getColorBright(colorInt) > 730) 
  { 
   return 1; 
  } 
  return 0; 
 } 
 
 public static int getColorBright(int colorInt) 
 { 
  Color color = new Color(colorInt); 
  return color.getRed() + color.getGreen() + color.getBlue(); 
 } 
 
 public static int ostu(int[][] gray, int w, int h) 
 { 
  int[] histData = new int[w * h]; 
  // Calculate histogram 
  for (int x = 0; x  varMax) 
   { 
    varMax = varBetween; 
    threshold = t; 
   } 
  } 
 
  return threshold; 
 } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。 


推荐阅读
  • 优化联通光猫DNS服务器设置
    本文详细介绍了如何为联通光猫配置DNS服务器地址,以提高网络解析效率和访问体验。通过智能线路解析功能,域名解析可以根据访问者的IP来源和类型进行差异化处理,从而实现更优的网络性能。 ... [详细]
  • 本文详细分析了JSP(JavaServer Pages)技术的主要优点和缺点,帮助开发者更好地理解其适用场景及潜在挑战。JSP作为一种服务器端技术,广泛应用于Web开发中。 ... [详细]
  • PyCharm下载与安装指南
    本文详细介绍如何从官方渠道下载并安装PyCharm集成开发环境(IDE),涵盖Windows、macOS和Linux系统,同时提供详细的安装步骤及配置建议。 ... [详细]
  • 本文详细介绍如何使用Python进行配置文件的读写操作,涵盖常见的配置文件格式(如INI、JSON、TOML和YAML),并提供具体的代码示例。 ... [详细]
  • 在计算机技术的学习道路上,51CTO学院以其专业性和专注度给我留下了深刻印象。从2012年接触计算机到2014年开始系统学习网络技术和安全领域,51CTO学院始终是我信赖的学习平台。 ... [详细]
  • Linux 系统启动故障排除指南:MBR 和 GRUB 问题
    本文详细介绍了 Linux 系统启动过程中常见的 MBR 扇区和 GRUB 引导程序故障及其解决方案,涵盖从备份、模拟故障到恢复的具体步骤。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 解决Linux系统中pygraphviz安装问题
    本文探讨了在Linux环境下安装pygraphviz时遇到的常见问题,并提供了详细的解决方案和最佳实践。 ... [详细]
  • 本文介绍了一款用于自动化部署 Linux 服务的 Bash 脚本。该脚本不仅涵盖了基本的文件复制和目录创建,还处理了系统服务的配置和启动,确保在多种 Linux 发行版上都能顺利运行。 ... [详细]
  • CMake跨平台开发实践
    本文介绍如何使用CMake支持不同平台的代码编译。通过一个简单的示例,我们将展示如何编写CMakeLists.txt以适应Linux和Windows平台,并实现跨平台的函数调用。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • Valve 发布 Steam Deck 的新版 Windows 驱动程序
    Valve 最新发布了针对 Steam Deck 掌机的 Windows 驱动程序,旨在提升其在 Windows 环境下的兼容性、安全性和性能表现。 ... [详细]
  • 本文详细介绍如何使用arm-eabi-gdb调试Android平台上的C/C++程序。通过具体步骤和实用技巧,帮助开发者更高效地进行调试工作。 ... [详细]
  • 在 Windows 10 中,F1 至 F12 键默认设置为快捷功能键。本文将介绍几种有效方法来禁用这些快捷键,并恢复其标准功能键的作用。请注意,部分笔记本电脑的快捷键可能无法完全关闭。 ... [详细]
  • 本文总结了2018年的关键成就,包括职业变动、购车、考取驾照等重要事件,并分享了读书、工作、家庭和朋友方面的感悟。同时,展望2019年,制定了健康、软实力提升和技术学习的具体目标。 ... [详细]
author-avatar
ndo2205188
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有